From ec464f0938a7c623d3acad1eb8ca0b069cf799d2 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sun, 18 Feb 2024 13:18:33 +0100 Subject: [PATCH 001/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/newsletter.md`=20(#10853)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/newsletter.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/de/docs/newsletter.md diff --git a/docs/de/docs/newsletter.md b/docs/de/docs/newsletter.md new file mode 100644 index 000000000..31995b164 --- /dev/null +++ b/docs/de/docs/newsletter.md @@ -0,0 +1,5 @@ +# FastAPI und Freunde Newsletter + +<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 0;"></iframe> + +<script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script> From 122713b168f0538eba33f0ad4a921e9409ff5055 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 18 Feb 2024 12:18:59 +0000 Subject: [PATCH 002/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6a366b06c..5ee0017a2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/newsletter.md`. PR [#10853](https://github.com/tiangolo/fastapi/pull/10853) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/learn/index.md`. PR [#11142](https://github.com/tiangolo/fastapi/pull/11142) by [@hsuanchi](https://github.com/hsuanchi). * 🌐 Add Korean translation for `/docs/ko/docs/tutorial/dependencies/global-dependencies.md`. PR [#11123](https://github.com/tiangolo/fastapi/pull/11123) by [@riroan](https://github.com/riroan). * 🌐 Add Korean translation for `/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#11124](https://github.com/tiangolo/fastapi/pull/11124) by [@riroan](https://github.com/riroan). From 73ca60c273977e98a7632871653e3c0ad3dad4f8 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sun, 18 Feb 2024 13:19:32 +0100 Subject: [PATCH 003/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/fastapi.md`=20(#10813)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/fastapi.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 docs/de/docs/reference/fastapi.md diff --git a/docs/de/docs/reference/fastapi.md b/docs/de/docs/reference/fastapi.md new file mode 100644 index 000000000..4e6a56971 --- /dev/null +++ b/docs/de/docs/reference/fastapi.md @@ -0,0 +1,31 @@ +# `FastAPI`-Klasse + +Hier sind die Referenzinformationen für die Klasse `FastAPI` mit all ihren Parametern, Attributen und Methoden. + +Sie können die `FastAPI`-Klasse direkt von `fastapi` importieren: + +```python +from fastapi import FastAPI +``` + +::: fastapi.FastAPI + options: + members: + - openapi_version + - webhooks + - state + - dependency_overrides + - openapi + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event + - middleware + - exception_handler From 7ca6f1cd1aeb3f148df22af9375069cc82f3c06c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emirhan=20Soyta=C5=9F?= <emrhns61@hotmail.com> Date: Sun, 18 Feb 2024 15:20:41 +0300 Subject: [PATCH 004/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/tutorial/query-params.md`=20(#11078)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/tutorial/query-params.md | 227 ++++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 docs/tr/docs/tutorial/query-params.md diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md new file mode 100644 index 000000000..61232d5b3 --- /dev/null +++ b/docs/tr/docs/tutorial/query-params.md @@ -0,0 +1,227 @@ +# Sorgu Parametreleri + +Fonksiyonda yol parametrelerinin parçası olmayan diğer tanımlamalar otomatik olarak "sorgu" parametresi olarak yorumlanır. + +```Python hl_lines="9" +{!../../../docs_src/query_params/tutorial001.py!} +``` + +Sorgu, bağlantıdaki `?` kısmından sonra gelen ve `&` işareti ile ayrılan anahtar-değer çiftlerinin oluşturduğu bir kümedir. + +Örneğin, aşağıdaki bağlantıda: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...sorgu parametreleri şunlardır: + +* `skip`: değeri `0`'dır +* `limit`: değeri `10`'dır + +Parametreler bağlantının bir parçası oldukları için doğal olarak string olarak değerlendirilirler. + +Fakat, Python tipleri ile tanımlandıkları zaman (yukarıdaki örnekte `int` oldukları gibi), parametreler o tiplere dönüştürülür ve o tipler çerçevesinde doğrulanırlar. + +Yol parametreleri için geçerli olan her türlü işlem aynı şekilde sorgu parametreleri için de geçerlidir: + +* Editör desteği (şüphesiz) +* Veri "<abbr title="HTTP isteği ile birlikte gelen string'i Python verisine dönüştürme">ayrıştırma</abbr>" +* Veri doğrulama +* Otomatik dokümantasyon + +## Varsayılanlar + +Sorgu parametreleri, adres yolunun sabit bir parçası olmadıklarından dolayı isteğe bağlı ve varsayılan değere sahip olabilirler. + +Yukarıdaki örnekte `skip=0` ve `limit=10` varsayılan değere sahiplerdir. + +Yani, aşağıdaki bağlantıya gitmek: + +``` +http://127.0.0.1:8000/items/ +``` + +şu adrese gitmek ile aynı etkiye sahiptir: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Ancak, mesela şöyle bir adresi ziyaret ederseniz: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +Fonksiyonunuzdaki parametre değerleri aşağıdaki gibi olacaktır: + +* `skip=20`: çünkü bağlantıda böyle tanımlandı. +* `limit=10`: çünkü varsayılan değer buydu. + +## İsteğe Bağlı Parametreler + +Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial002.py!} + ``` + +Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. + +!!! check "Ek bilgi" + Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. + +## Sorgu Parametresi Tip Dönüşümü + +Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial003.py!} + ``` + +Bu durumda, eğer şu adrese giderseniz: + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +veya adres, herhangi farklı bir harf varyasyonu içermesi durumuna rağmen (büyük harf, sadece baş harfi büyük kelime, vb.) fonksiyonunuz, `bool` tipli `short` parametresini `True` olarak algılayacaktır. Aksi halde `False` olarak algılanacaktır. + + +## Çoklu Yol ve Sorgu Parametreleri + +**FastAPI** neyin ne olduğunu ayırt edebileceğinden dolayı aynı anda birden fazla yol ve sorgu parametresi tanımlayabilirsiniz. + +Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. + +İsimlerine göre belirleneceklerdir: + +=== "Python 3.10+" + + ```Python hl_lines="6 8" + {!> ../../../docs_src/query_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 10" + {!> ../../../docs_src/query_params/tutorial004.py!} + ``` + +## Zorunlu Sorgu Parametreleri + +Türü yol olmayan bir parametre (şu ana kadar sadece sorgu parametrelerini gördük) için varsayılan değer tanımlarsanız o parametre zorunlu olmayacaktır. + +Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe bağlı olmasını istiyorsanız değerini `None` olarak atayabilirsiniz. + +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!} +``` + +Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. + +Eğer tarayıcınızda şu bağlantıyı: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +...`needy` parametresini eklemeden açarsanız şuna benzer bir hata ile karşılaşırsınız: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +`needy` zorunlu bir parametre olduğundan dolayı bağlantıda tanımlanması gerekir: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...bu iş görür: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + +Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params/tutorial006.py!} + ``` + +Bu durumda, 3 tane sorgu parametresi var olacaktır: + +* `needy`, zorunlu bir `str`. +* `skip`, varsayılan değeri `0` olan bir `int`. +* `limit`, isteğe bağlı bir `int`. + +!!! tip "İpucu" + Ayrıca, [Yol Parametreleri](path-params.md#predefined-values){.internal-link target=_blank}nde de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. From f1ff930e6828088cd39b0045af0110bba410f73e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 18 Feb 2024 12:20:55 +0000 Subject: [PATCH 005/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5ee0017a2..b23e0c897 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/fastapi.md`. PR [#10813](https://github.com/tiangolo/fastapi/pull/10813) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/newsletter.md`. PR [#10853](https://github.com/tiangolo/fastapi/pull/10853) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/learn/index.md`. PR [#11142](https://github.com/tiangolo/fastapi/pull/11142) by [@hsuanchi](https://github.com/hsuanchi). * 🌐 Add Korean translation for `/docs/ko/docs/tutorial/dependencies/global-dependencies.md`. PR [#11123](https://github.com/tiangolo/fastapi/pull/11123) by [@riroan](https://github.com/riroan). From 3808d618fdebdd54840e8b8ba5252d4c2edb4c64 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 18 Feb 2024 12:21:32 +0000 Subject: [PATCH 006/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b23e0c897..98fea7bb4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11078](https://github.com/tiangolo/fastapi/pull/11078) by [@emrhnsyts](https://github.com/emrhnsyts). * 🌐 Add German translation for `docs/de/docs/reference/fastapi.md`. PR [#10813](https://github.com/tiangolo/fastapi/pull/10813) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/newsletter.md`. PR [#10853](https://github.com/tiangolo/fastapi/pull/10853) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/learn/index.md`. PR [#11142](https://github.com/tiangolo/fastapi/pull/11142) by [@hsuanchi](https://github.com/hsuanchi). From 6062ec86f3039f044a9bafa637b2544947c12afc Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Mon, 19 Feb 2024 16:53:18 +0100 Subject: [PATCH 007/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/request.md`=20(#10821)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/request.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 docs/de/docs/reference/request.md diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md new file mode 100644 index 000000000..b170c1e40 --- /dev/null +++ b/docs/de/docs/reference/request.md @@ -0,0 +1,14 @@ +# `Request`-Klasse + +Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als vom Typ `Request` deklarieren und dann direkt auf das Requestobjekt zugreifen, ohne jegliche Validierung, usw. + +Sie können es direkt von `fastapi` importieren: + +```python +from fastapi import Request +``` + +!!! tip "Tipp" + Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +::: fastapi.Request From 646e7eb3c7cc28572fbf3183b8784077a652e2c6 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Mon, 19 Feb 2024 16:53:39 +0100 Subject: [PATCH 008/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/responses.md`=20(#10825)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/responses.md | 164 ++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 docs/de/docs/reference/responses.md diff --git a/docs/de/docs/reference/responses.md b/docs/de/docs/reference/responses.md new file mode 100644 index 000000000..c0e9f07e7 --- /dev/null +++ b/docs/de/docs/reference/responses.md @@ -0,0 +1,164 @@ +# Benutzerdefinierte Responseklassen – File, HTML, Redirect, Streaming, usw. + +Es gibt mehrere benutzerdefinierte Responseklassen, von denen Sie eine Instanz erstellen und diese direkt von Ihren *Pfadoperationen* zurückgeben können. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu benutzerdefinierten Responses – HTML, Stream, Datei, andere](../advanced/custom-response.md). + +Sie können diese direkt von `fastapi.responses` importieren: + +```python +from fastapi.responses import ( + FileResponse, + HTMLResponse, + JSONResponse, + ORJSONResponse, + PlainTextResponse, + RedirectResponse, + Response, + StreamingResponse, + UJSONResponse, +) +``` + +## FastAPI-Responses + +Es gibt einige benutzerdefinierte FastAPI-Responseklassen, welche Sie verwenden können, um die JSON-Performanz zu optimieren. + +::: fastapi.responses.UJSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.ORJSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +## Starlette-Responses + +::: fastapi.responses.FileResponse + options: + members: + - chunk_size + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.HTMLResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.JSONResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.PlainTextResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.RedirectResponse + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.Response + options: + members: + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie + +::: fastapi.responses.StreamingResponse + options: + members: + - body_iterator + - charset + - status_code + - media_type + - body + - background + - raw_headers + - render + - init_headers + - headers + - set_cookie + - delete_cookie From ce1a358cbf2567012c7f85ab8b941752b1f95a39 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 19 Feb 2024 15:53:44 +0000 Subject: [PATCH 009/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 98fea7bb4..833dad61f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/request.md`. PR [#10821](https://github.com/tiangolo/fastapi/pull/10821) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11078](https://github.com/tiangolo/fastapi/pull/11078) by [@emrhnsyts](https://github.com/emrhnsyts). * 🌐 Add German translation for `docs/de/docs/reference/fastapi.md`. PR [#10813](https://github.com/tiangolo/fastapi/pull/10813) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/newsletter.md`. PR [#10853](https://github.com/tiangolo/fastapi/pull/10853) by [@nilslindemann](https://github.com/nilslindemann). From d0b143916ca1bb83e0cff25b7f36e7a0bf003ae3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 19 Feb 2024 15:54:37 +0000 Subject: [PATCH 010/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 833dad61f..2c25f82ae 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/responses.md`. PR [#10825](https://github.com/tiangolo/fastapi/pull/10825) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/request.md`. PR [#10821](https://github.com/tiangolo/fastapi/pull/10821) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11078](https://github.com/tiangolo/fastapi/pull/11078) by [@emrhnsyts](https://github.com/emrhnsyts). * 🌐 Add German translation for `docs/de/docs/reference/fastapi.md`. PR [#10813](https://github.com/tiangolo/fastapi/pull/10813) by [@nilslindemann](https://github.com/nilslindemann). From 073a05ebdd395bea1317c3a52e9a40c7fd45df64 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Mon, 19 Feb 2024 16:54:52 +0100 Subject: [PATCH 011/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/encoders.md`=20(#10840)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/encoders.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/de/docs/reference/encoders.md diff --git a/docs/de/docs/reference/encoders.md b/docs/de/docs/reference/encoders.md new file mode 100644 index 000000000..2489b8c60 --- /dev/null +++ b/docs/de/docs/reference/encoders.md @@ -0,0 +1,3 @@ +# Encoder – `jsonable_encoder` + +::: fastapi.encoders.jsonable_encoder From e76977bb3575547f1229a8b319724593302cefb5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 19 Feb 2024 15:57:07 +0000 Subject: [PATCH 012/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2c25f82ae..a02bf2a1d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/encoders.md`. PR [#10840](https://github.com/tiangolo/fastapi/pull/10840) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/responses.md`. PR [#10825](https://github.com/tiangolo/fastapi/pull/10825) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/request.md`. PR [#10821](https://github.com/tiangolo/fastapi/pull/10821) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11078](https://github.com/tiangolo/fastapi/pull/11078) by [@emrhnsyts](https://github.com/emrhnsyts). From e52bf9628f270a7e7c6fba2a99925d6e53cb30b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Mon, 19 Feb 2024 21:46:02 +0300 Subject: [PATCH 013/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Turkish=20trans?= =?UTF-8?q?lation=20for=20`docs/tr/docs/tutorial/query-params.md`=20(#1116?= =?UTF-8?q?2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/tutorial/query-params.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md index 61232d5b3..aa3915557 100644 --- a/docs/tr/docs/tutorial/query-params.md +++ b/docs/tr/docs/tutorial/query-params.md @@ -224,4 +224,4 @@ Bu durumda, 3 tane sorgu parametresi var olacaktır: * `limit`, isteğe bağlı bir `int`. !!! tip "İpucu" - Ayrıca, [Yol Parametreleri](path-params.md#predefined-values){.internal-link target=_blank}nde de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. + Ayrıca, [Yol Parametrelerinde](path-params.md#predefined-values){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. From a6bc32a61a2f57645d5535d076e38b0b3eb4138d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 19 Feb 2024 18:46:23 +0000 Subject: [PATCH 014/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a02bf2a1d..d98faea4d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Update Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11162](https://github.com/tiangolo/fastapi/pull/11162) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add German translation for `docs/de/docs/reference/encoders.md`. PR [#10840](https://github.com/tiangolo/fastapi/pull/10840) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/responses.md`. PR [#10825](https://github.com/tiangolo/fastapi/pull/10825) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/request.md`. PR [#10821](https://github.com/tiangolo/fastapi/pull/10821) by [@nilslindemann](https://github.com/nilslindemann). From 626b066e56e39162f328431395856c959d150bc4 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Wed, 21 Feb 2024 23:23:00 +0100 Subject: [PATCH 015/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/external-links.md`=20(#10852)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/external-links.md | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 docs/de/docs/external-links.md diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md new file mode 100644 index 000000000..d97f4d39c --- /dev/null +++ b/docs/de/docs/external-links.md @@ -0,0 +1,36 @@ +# Externe Links und Artikel + +**FastAPI** hat eine großartige Community, die ständig wächst. + +Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. + +Hier ist eine unvollständige Liste einiger davon. + +!!! tip "Tipp" + Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>. + +!!! note "Hinweis Deutsche Übersetzung" + Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/tiangolo/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt. + +{% for section_name, section_content in external_links.items() %} + +## {{ section_name }} + +{% for lang_name, lang_content in section_content.items() %} + +### {{ lang_name }} + +{% for item in lang_content %} + +* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. + +{% endfor %} +{% endfor %} +{% endfor %} + +## Projekte + +Die neuesten GitHub-Projekte zum Thema `fastapi`: + +<div class="github-topic-projects"> +</div> From 5da35ff980a9477675929ddc0643e7eb27ea6208 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 21 Feb 2024 22:23:21 +0000 Subject: [PATCH 016/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d98faea4d..d8d87ca46 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/external-links.md`. PR [#10852](https://github.com/tiangolo/fastapi/pull/10852) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11162](https://github.com/tiangolo/fastapi/pull/11162) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add German translation for `docs/de/docs/reference/encoders.md`. PR [#10840](https://github.com/tiangolo/fastapi/pull/10840) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/responses.md`. PR [#10825](https://github.com/tiangolo/fastapi/pull/10825) by [@nilslindemann](https://github.com/nilslindemann). From dec45c534f97bb5635492cba78a93f1409ec6b2a Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Wed, 21 Feb 2024 23:26:02 +0100 Subject: [PATCH 017/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/templating.md`=20(#10842)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/templating.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/de/docs/reference/templating.md diff --git a/docs/de/docs/reference/templating.md b/docs/de/docs/reference/templating.md new file mode 100644 index 000000000..c367a0179 --- /dev/null +++ b/docs/de/docs/reference/templating.md @@ -0,0 +1,13 @@ +# Templating – `Jinja2Templates` + +Sie können die `Jinja2Templates`-Klasse verwenden, um Jinja-Templates zu rendern. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Templates](../advanced/templates.md). + +Sie können die Klasse direkt von `fastapi.templating` importieren: + +```python +from fastapi.templating import Jinja2Templates +``` + +::: fastapi.templating.Jinja2Templates From 9210e6a330bc9639fcb3315a493e39aa2119d142 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Wed, 21 Feb 2024 23:26:48 +0100 Subject: [PATCH 018/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/background.md`=20(#10820)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/background.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 docs/de/docs/reference/background.md diff --git a/docs/de/docs/reference/background.md b/docs/de/docs/reference/background.md new file mode 100644 index 000000000..0fd389325 --- /dev/null +++ b/docs/de/docs/reference/background.md @@ -0,0 +1,11 @@ +# Hintergrundtasks – `BackgroundTasks` + +Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeitsfunktion mit dem Typ `BackgroundTasks` deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren. + +Sie können `BackgroundTasks` direkt von `fastapi` importieren: + +```python +from fastapi import BackgroundTasks +``` + +::: fastapi.BackgroundTasks From cb938740145c5d0cea78a26bc0a7215aae4506b9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 21 Feb 2024 22:27:17 +0000 Subject: [PATCH 019/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d8d87ca46..7251a4f91 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/templating.md`. PR [#10842](https://github.com/tiangolo/fastapi/pull/10842) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/external-links.md`. PR [#10852](https://github.com/tiangolo/fastapi/pull/10852) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11162](https://github.com/tiangolo/fastapi/pull/11162) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add German translation for `docs/de/docs/reference/encoders.md`. PR [#10840](https://github.com/tiangolo/fastapi/pull/10840) by [@nilslindemann](https://github.com/nilslindemann). From 6336604906d50e0aca978d15ef82236bac23fb15 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 21 Feb 2024 22:27:53 +0000 Subject: [PATCH 020/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7251a4f91..e595ed927 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/background.md`. PR [#10820](https://github.com/tiangolo/fastapi/pull/10820) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/templating.md`. PR [#10842](https://github.com/tiangolo/fastapi/pull/10842) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/external-links.md`. PR [#10852](https://github.com/tiangolo/fastapi/pull/10852) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11162](https://github.com/tiangolo/fastapi/pull/11162) by [@hasansezertasan](https://github.com/hasansezertasan). From bf771bd7817f8e8348f85836a21d1e96c0b4f7a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 25 Feb 2024 00:06:37 +0100 Subject: [PATCH 021/846] =?UTF-8?q?=F0=9F=90=9B=20Fix=20unhandled=20growin?= =?UTF-8?q?g=20memory=20for=20internal=20server=20errors,=20refactor=20dep?= =?UTF-8?q?endencies=20with=20`yield`=20and=20`except`=20to=20require=20ra?= =?UTF-8?q?ising=20again=20as=20in=20regular=20Python=20(#11191)?= 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> --- .../dependencies/dependencies-with-yield.md | 70 +++++++++++- docs_src/dependencies/tutorial008c.py | 27 +++++ docs_src/dependencies/tutorial008c_an.py | 28 +++++ docs_src/dependencies/tutorial008c_an_py39.py | 29 +++++ docs_src/dependencies/tutorial008d.py | 28 +++++ docs_src/dependencies/tutorial008d_an.py | 29 +++++ docs_src/dependencies/tutorial008d_an_py39.py | 30 +++++ fastapi/routing.py | 108 ++++++++---------- tests/test_dependency_contextmanager.py | 2 + tests/test_dependency_normal_exceptions.py | 1 + .../test_tutorial008b_an_py39.py | 20 +++- .../test_dependencies/test_tutorial008c.py | 38 ++++++ .../test_dependencies/test_tutorial008c_an.py | 38 ++++++ .../test_tutorial008c_an_py39.py | 44 +++++++ .../test_dependencies/test_tutorial008d.py | 41 +++++++ .../test_dependencies/test_tutorial008d_an.py | 41 +++++++ .../test_tutorial008d_an_py39.py | 47 ++++++++ 17 files changed, 553 insertions(+), 68 deletions(-) create mode 100644 docs_src/dependencies/tutorial008c.py create mode 100644 docs_src/dependencies/tutorial008c_an.py create mode 100644 docs_src/dependencies/tutorial008c_an_py39.py create mode 100644 docs_src/dependencies/tutorial008d.py create mode 100644 docs_src/dependencies/tutorial008d_an.py create mode 100644 docs_src/dependencies/tutorial008d_an_py39.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008c.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008c_an.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008d.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008d_an.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index de87ba315..ad5aed932 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -162,6 +162,63 @@ The same way, you could raise an `HTTPException` or similar in the exit code, af 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}. +## Dependencies with `yield` and `except` + +If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python: + +=== "Python 3.9+" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14-15" + {!> ../../../docs_src/dependencies/tutorial008c_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="13-14" + {!> ../../../docs_src/dependencies/tutorial008c.py!} + ``` + +In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱 + +### Always `raise` in Dependencies with `yield` and `except` + +If you catch an exception in a dependency with `yield`, unless you are raising another `HTTPException` or similar, you should re-raise the original exception. + +You can re-raise the same exception using `raise`: + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial008d_an.py!} + ``` + + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial008d.py!} + ``` + +Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎 + ## Execution of dependencies with `yield` The sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code. @@ -187,7 +244,6 @@ participant tasks as Background tasks operation -->> dep: Raise Exception (e.g. HTTPException) opt handle dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception - dep -->> handler: Auto forward exception end handler -->> client: HTTP error response end @@ -210,15 +266,23 @@ participant tasks as Background tasks !!! tip This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. - If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`, and then **again** to the exception handlers. If there's no exception handler for that exception, it will then be handled by the default internal `ServerErrorMiddleware`, returning a 500 HTTP status code, to let the client know that there was an error in the server. + If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled. -## Dependencies with `yield`, `HTTPException` and Background Tasks +## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks !!! warning You most probably don't need these technical details, you can skip this section and continue below. These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. +### Dependencies with `yield` and `except`, Technical Details + +Before FastAPI 0.110.0, if you used a dependency with `yield`, and then you captured an exception with `except` in that dependency, and you didn't raise the exception again, the exception would be automatically raised/forwarded to any exception handlers or the internal server error handler. + +This was changed in version 0.110.0 to fix unhandled memory consumption from forwarded exceptions without a handler (internal server errors), and to make it consistent with the behavior of regular Python code. + +### Background Tasks and Dependencies with `yield`, Technical Details + Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} would have already run. This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. diff --git a/docs_src/dependencies/tutorial008c.py b/docs_src/dependencies/tutorial008c.py new file mode 100644 index 000000000..4b99a5a31 --- /dev/null +++ b/docs_src/dependencies/tutorial008c.py @@ -0,0 +1,27 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008c_an.py b/docs_src/dependencies/tutorial008c_an.py new file mode 100644 index 000000000..94f59f9aa --- /dev/null +++ b/docs_src/dependencies/tutorial008c_an.py @@ -0,0 +1,28 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008c_an_py39.py b/docs_src/dependencies/tutorial008c_an_py39.py new file mode 100644 index 000000000..da92efa9c --- /dev/null +++ b/docs_src/dependencies/tutorial008c_an_py39.py @@ -0,0 +1,29 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d.py b/docs_src/dependencies/tutorial008d.py new file mode 100644 index 000000000..93039343d --- /dev/null +++ b/docs_src/dependencies/tutorial008d.py @@ -0,0 +1,28 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_an.py b/docs_src/dependencies/tutorial008d_an.py new file mode 100644 index 000000000..c35424574 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_an.py @@ -0,0 +1,29 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_an_py39.py b/docs_src/dependencies/tutorial008d_an_py39.py new file mode 100644 index 000000000..99bd5cb91 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_an_py39.py @@ -0,0 +1,30 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/fastapi/routing.py b/fastapi/routing.py index acebabfca..23a32d15f 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -216,19 +216,14 @@ def get_request_handler( actual_response_class = response_class async def app(request: Request) -> Response: - exception_to_reraise: Optional[Exception] = None response: Union[Response, None] = None - async with AsyncExitStack() as async_exit_stack: - # TODO: remove this scope later, after a few releases - # This scope fastapi_astack is no longer used by FastAPI, kept for - # compatibility, just in case - request.scope["fastapi_astack"] = async_exit_stack + async with AsyncExitStack() as file_stack: try: body: Any = None if body_field: if is_body_form: body = await request.form() - async_exit_stack.push_async_callback(body.close) + file_stack.push_async_callback(body.close) else: body_bytes = await request.body() if body_bytes: @@ -260,18 +255,17 @@ def get_request_handler( ], body=e.doc, ) - exception_to_reraise = validation_error raise validation_error from e - except HTTPException as e: - exception_to_reraise = e + except HTTPException: + # If a middleware raises an HTTPException, it should be raised again raise except Exception as e: http_error = HTTPException( status_code=400, detail="There was an error parsing the body" ) - exception_to_reraise = http_error raise http_error from e - try: + errors: List[Any] = [] + async with AsyncExitStack() as async_exit_stack: solved_result = await solve_dependencies( request=request, dependant=dependant, @@ -280,59 +274,53 @@ def get_request_handler( async_exit_stack=async_exit_stack, ) values, errors, background_tasks, sub_response, _ = solved_result - except Exception as e: - exception_to_reraise = e - raise e + if not errors: + raw_response = await run_endpoint_function( + dependant=dependant, values=values, is_coroutine=is_coroutine + ) + if isinstance(raw_response, Response): + if raw_response.background is None: + raw_response.background = background_tasks + response = raw_response + else: + response_args: Dict[str, Any] = {"background": background_tasks} + # If status_code was set, use it, otherwise use the default from the + # response class, in the case of redirect it's 307 + current_status_code = ( + status_code if status_code else sub_response.status_code + ) + if current_status_code is not None: + response_args["status_code"] = current_status_code + if sub_response.status_code: + response_args["status_code"] = sub_response.status_code + content = await serialize_response( + field=response_field, + response_content=raw_response, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + is_coroutine=is_coroutine, + ) + response = actual_response_class(content, **response_args) + if not is_body_allowed_for_status_code(response.status_code): + response.body = b"" + response.headers.raw.extend(sub_response.headers.raw) if errors: validation_error = RequestValidationError( _normalize_errors(errors), body=body ) - exception_to_reraise = validation_error raise validation_error - else: - try: - raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine - ) - except Exception as e: - exception_to_reraise = e - raise e - if isinstance(raw_response, Response): - if raw_response.background is None: - raw_response.background = background_tasks - response = raw_response - else: - response_args: Dict[str, Any] = {"background": background_tasks} - # If status_code was set, use it, otherwise use the default from the - # response class, in the case of redirect it's 307 - current_status_code = ( - status_code if status_code else sub_response.status_code - ) - if current_status_code is not None: - response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code - content = await serialize_response( - field=response_field, - response_content=raw_response, - include=response_model_include, - exclude=response_model_exclude, - by_alias=response_model_by_alias, - exclude_unset=response_model_exclude_unset, - exclude_defaults=response_model_exclude_defaults, - exclude_none=response_model_exclude_none, - is_coroutine=is_coroutine, - ) - response = actual_response_class(content, **response_args) - if not is_body_allowed_for_status_code(response.status_code): - response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) - # This exception was possibly handled by the dependency but it should - # still bubble up so that the ServerErrorMiddleware can return a 500 - # or the ExceptionMiddleware can catch and handle any other exceptions - if exception_to_reraise: - raise exception_to_reraise - assert response is not None, "An error occurred while generating the request" + if response is None: + raise FastAPIError( + "No response object was returned. There's a high chance that the " + "application code is raising an exception and a dependency with yield " + "has a block with a bare except, or a block with except Exception, " + "and is not raising the exception again. Read more about it in the " + "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" + ) return response return app diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index b07f9aa5b..008dab7bc 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -55,6 +55,7 @@ async def asyncgen_state_try(state: Dict[str, str] = Depends(get_state)): yield state["/async_raise"] except AsyncDependencyError: errors.append("/async_raise") + raise finally: state["/async_raise"] = "asyncgen raise finalized" @@ -65,6 +66,7 @@ def generator_state_try(state: Dict[str, str] = Depends(get_state)): yield state["/sync_raise"] except SyncDependencyError: errors.append("/sync_raise") + raise finally: state["/sync_raise"] = "generator raise finalized" diff --git a/tests/test_dependency_normal_exceptions.py b/tests/test_dependency_normal_exceptions.py index 23c366d5d..326f8fd88 100644 --- a/tests/test_dependency_normal_exceptions.py +++ b/tests/test_dependency_normal_exceptions.py @@ -20,6 +20,7 @@ async def get_database(): fake_database.update(temp_database) except HTTPException: state["except"] = True + raise finally: state["finally"] = True diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py index 7f51fc52a..7d24809a8 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py @@ -1,23 +1,33 @@ +import pytest from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial008b_an import app +from ...utils import needs_py39 -client = TestClient(app) +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008b_an_py39 import app -def test_get_no_item(): + client = TestClient(app) + return client + + +@needs_py39 +def test_get_no_item(client: TestClient): response = client.get("/items/foo") assert response.status_code == 404, response.text assert response.json() == {"detail": "Item not found"} -def test_owner_error(): +@needs_py39 +def test_owner_error(client: TestClient): response = client.get("/items/plumbus") assert response.status_code == 400, response.text assert response.json() == {"detail": "Owner error: Rick"} -def test_get_item(): +@needs_py39 +def test_get_item(client: TestClient): response = client.get("/items/portal-gun") assert response.status_code == 200, response.text assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c.py b/tests/test_tutorial/test_dependencies/test_tutorial008c.py new file mode 100644 index 000000000..27be8895a --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c.py @@ -0,0 +1,38 @@ +import pytest +from fastapi.exceptions import FastAPIError +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008c import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_fastapi_error(client: TestClient): + with pytest.raises(FastAPIError) as exc_info: + client.get("/items/portal-gun") + assert "No response object was returned" in exc_info.value.args[0] + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008c import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py new file mode 100644 index 000000000..10fa1ab50 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py @@ -0,0 +1,38 @@ +import pytest +from fastapi.exceptions import FastAPIError +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008c_an import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_fastapi_error(client: TestClient): + with pytest.raises(FastAPIError) as exc_info: + client.get("/items/portal-gun") + assert "No response object was returned" in exc_info.value.args[0] + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008c_an import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py new file mode 100644 index 000000000..6c3acff50 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py @@ -0,0 +1,44 @@ +import pytest +from fastapi.exceptions import FastAPIError +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008c_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +@needs_py39 +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +@needs_py39 +def test_fastapi_error(client: TestClient): + with pytest.raises(FastAPIError) as exc_info: + client.get("/items/portal-gun") + assert "No response object was returned" in exc_info.value.args[0] + + +@needs_py39 +def test_internal_server_error(): + from docs_src.dependencies.tutorial008c_an_py39 import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d.py b/tests/test_tutorial/test_dependencies/test_tutorial008d.py new file mode 100644 index 000000000..043496112 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d.py @@ -0,0 +1,41 @@ +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008d import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_internal_error(client: TestClient): + from docs_src.dependencies.tutorial008d import InternalError + + with pytest.raises(InternalError) as exc_info: + client.get("/items/portal-gun") + assert ( + exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" + ) + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008d import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py new file mode 100644 index 000000000..f29d8cdbe --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py @@ -0,0 +1,41 @@ +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008d_an import app + + client = TestClient(app) + return client + + +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_internal_error(client: TestClient): + from docs_src.dependencies.tutorial008d_an import InternalError + + with pytest.raises(InternalError) as exc_info: + client.get("/items/portal-gun") + assert ( + exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" + ) + + +def test_internal_server_error(): + from docs_src.dependencies.tutorial008d_an import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py new file mode 100644 index 000000000..0a585f4ad --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py @@ -0,0 +1,47 @@ +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.dependencies.tutorial008d_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_get_no_item(client: TestClient): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +@needs_py39 +def test_get(client: TestClient): + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +@needs_py39 +def test_internal_error(client: TestClient): + from docs_src.dependencies.tutorial008d_an_py39 import InternalError + + with pytest.raises(InternalError) as exc_info: + client.get("/items/portal-gun") + assert ( + exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" + ) + + +@needs_py39 +def test_internal_server_error(): + from docs_src.dependencies.tutorial008d_an_py39 import app + + client = TestClient(app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" From b6b0f2a7e6690b923957677807c5c6a4ff556422 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 24 Feb 2024 23:06:56 +0000 Subject: [PATCH 022/846] =?UTF-8?q?=F0=9F=93=9D=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 e595ed927..2e8930ea3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Breaking Changes + +* 🐛 Fix unhandled growing memory for internal server errors, refactor dependencies with `yield` and `except` to require raising again as in regular Python. PR [#11191](https://github.com/tiangolo/fastapi/pull/11191) by [@tiangolo](https://github.com/tiangolo). + ### Docs * ✏️ Fix minor typos in `docs/ko/docs/`. PR [#11126](https://github.com/tiangolo/fastapi/pull/11126) by [@KaniKim](https://github.com/KaniKim). From 32b56a8d08aece04d55331142a18f7b2ce580fa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 25 Feb 2024 00:18:13 +0100 Subject: [PATCH 023/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2e8930ea3..c442f1449 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -10,6 +10,29 @@ hide: ### Breaking Changes * 🐛 Fix unhandled growing memory for internal server errors, refactor dependencies with `yield` and `except` to require raising again as in regular Python. PR [#11191](https://github.com/tiangolo/fastapi/pull/11191) by [@tiangolo](https://github.com/tiangolo). + * This is a breaking change (and only slightly) if you used dependencies with `yield`, used `except` in those dependencies, and didn't raise again. + * This was reported internally by [@rushilsrivastava](https://github.com/rushilsrivastava) as a memory leak when the server had unhandled exceptions that would produce internal server errors, the memory allocated before that point would not be released. + * Read the new docs: [Dependencies with `yield` and `except`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except). + +In short, if you had dependencies that looked like: + +```Python +def my_dep(): + try: + yield + except SomeException: + pass +``` + +Now you need to make sure you raise again after `except`, just as you would in regular Python: + +```Python +def my_dep(): + try: + yield + except SomeException: + raise +``` ### Docs From e40747f10ae911910e9cb9a9684576f3b21304c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 25 Feb 2024 00:19:38 +0100 Subject: [PATCH 024/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?0.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c442f1449..e01c3544f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.110.0 + ### Breaking Changes * 🐛 Fix unhandled growing memory for internal server errors, refactor dependencies with `yield` and `except` to require raising again as in regular Python. PR [#11191](https://github.com/tiangolo/fastapi/pull/11191) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 3458b9e5b..234969256 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.109.2" +__version__ = "0.110.0" from starlette import status as status From 937378ff054fb760ace3779134b3d6211b825534 Mon Sep 17 00:00:00 2001 From: Vusal Abdullayev <vusal.abdullayev@khazar.org> Date: Sun, 25 Feb 2024 18:25:12 +0400 Subject: [PATCH 025/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Azerbaijani=20tran?= =?UTF-8?q?slation=20for=20`docs/az/learn/index.md`=20(#11192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/az/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/az/learn/index.md diff --git a/docs/az/learn/index.md b/docs/az/learn/index.md new file mode 100644 index 000000000..cc32108bf --- /dev/null +++ b/docs/az/learn/index.md @@ -0,0 +1,5 @@ +# Öyrən + +Burada **FastAPI** öyrənmək üçün giriş bölmələri və dərsliklər yer alır. + +Siz bunu kitab, kurs, FastAPI öyrənmək üçün rəsmi və tövsiyə olunan üsul hesab edə bilərsiniz. 😎 From 7ef0b08897afa0972c7e8418d05a0ad654e45996 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 25 Feb 2024 14:25:31 +0000 Subject: [PATCH 026/846] =?UTF-8?q?=F0=9F=93=9D=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 e01c3544f..2d5ab2d9c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Azerbaijani translation for `docs/az/learn/index.md`. PR [#11192](https://github.com/tiangolo/fastapi/pull/11192) by [@vusallyv](https://github.com/vusallyv). + ## 0.110.0 ### Breaking Changes From c4c70fd7927dbd7d23894f1a69d42457fb7cadbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 27 Feb 2024 12:18:27 +0100 Subject: [PATCH 027/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2d5ab2d9c..12f8ffd8a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -324,7 +324,7 @@ Read more in the [advisory: Content-Type Header ReDoS](https://github.com/tiango ### Upgrades -* ⬆️ Upgrade Starlette to `>=0.29.0,<0.33.0`, update docs and usage of templates with new Starlette arguments. PR [#10846](https://github.com/tiangolo/fastapi/pull/10846) by [@tiangolo](https://github.com/tiangolo). +* ⬆️ Upgrade Starlette to `>=0.29.0,<0.33.0`, update docs and usage of templates with new Starlette arguments. Remove pin of AnyIO `>=3.7.1,<4.0.0`, add support for AnyIO 4.x.x. PR [#10846](https://github.com/tiangolo/fastapi/pull/10846) by [@tiangolo](https://github.com/tiangolo). ## 0.107.0 From c0ad1ebabdb9e26b94c0e574c41bd6869e124bff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 28 Feb 2024 15:04:08 +0100 Subject: [PATCH 028/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20rem?= =?UTF-8?q?ove=20Jina,=20remove=20Powens,=20move=20TestDriven.io=20(#11213?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 -- docs/en/data/sponsors.yml | 12 +++--------- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 874abf8c6..8d3e4c68d 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,7 @@ The key features are: <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> <a href="https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> <a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> -<a href="https://testdriven.io/courses/tdd-fastapi/" target="_blank" title="Learn to build high-quality web apps with best practices"><img src="https://fastapi.tiangolo.com/img/sponsors/testdriven.svg"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> -<a href="https://careers.powens.com/" target="_blank" title="Powens is hiring!"><img src="https://fastapi.tiangolo.com/img/sponsors/powens.png"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> <a href="https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship" target="_blank" title="SDKs for your API | Speakeasy"><img src="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a> <a href="https://www.svix.com/" target="_blank" title="Svix - Webhooks as a service"><img src="https://fastapi.tiangolo.com/img/sponsors/svix.svg"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index fd8518ce3..8401fd33e 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -27,15 +27,9 @@ silver: - url: https://training.talkpython.fm/fastapi-courses title: FastAPI video courses on demand from people you trust img: https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg - - url: https://testdriven.io/courses/tdd-fastapi/ - title: Learn to build high-quality web apps with best practices - img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks img: https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg - - url: https://careers.powens.com/ - title: Powens is hiring! - img: https://fastapi.tiangolo.com/img/sponsors/powens.png - url: https://databento.com/ title: Pay as you go for market data img: https://fastapi.tiangolo.com/img/sponsors/databento.svg @@ -52,6 +46,6 @@ bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. img: https://fastapi.tiangolo.com/img/sponsors/exoflare.png - - url: https://bit.ly/3JJ7y5C - title: Build cross-modal and multimodal applications on the cloud - img: https://fastapi.tiangolo.com/img/sponsors/jina2.svg + - url: https://testdriven.io/courses/tdd-fastapi/ + title: Learn to build high-quality web apps with best practices + img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg From eef1b7d51530be64ddd48e02b5ca46f28a0ebfc1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 28 Feb 2024 14:04:27 +0000 Subject: [PATCH 029/846] =?UTF-8?q?=F0=9F=93=9D=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 12f8ffd8a..ad548327d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 🌐 Add Azerbaijani translation for `docs/az/learn/index.md`. PR [#11192](https://github.com/tiangolo/fastapi/pull/11192) by [@vusallyv](https://github.com/vusallyv). +### Internal + +* 🔧 Update sponsors, remove Jina, remove Powens, move TestDriven.io. PR [#11213](https://github.com/tiangolo/fastapi/pull/11213) by [@tiangolo](https://github.com/tiangolo). + ## 0.110.0 ### Breaking Changes From 4f20ca6a7cf6d9fe0bb8a4541b15b27f2296eaf2 Mon Sep 17 00:00:00 2001 From: JackLee <280147597@qq.com> Date: Sat, 9 Mar 2024 08:32:05 +0800 Subject: [PATCH 030/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/query-params.md`=20(#1124?= =?UTF-8?q?2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/query-params.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index b1668a2d2..a0cc7fea3 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -63,9 +63,18 @@ http://127.0.0.1:8000/items/?skip=20 通过同样的方式,你可以将它们的默认值设置为 `None` 来声明可选查询参数: -```Python hl_lines="7" -{!../../../docs_src/query_params/tutorial002.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial002.py!} + ``` + 在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`。 From 7b957e94e35f2538ed15495880f29e77ed6a7088 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 9 Mar 2024 00:32:26 +0000 Subject: [PATCH 031/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ad548327d..10aa841f9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11242](https://github.com/tiangolo/fastapi/pull/11242) by [@jackleeio](https://github.com/jackleeio). * 🌐 Add Azerbaijani translation for `docs/az/learn/index.md`. PR [#11192](https://github.com/tiangolo/fastapi/pull/11192) by [@vusallyv](https://github.com/vusallyv). ### Internal From 299bf22ad82344a05c522c5ec20e30db73b0c65e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=91=81Max=F0=9F=91=81?= <kohiry@mail.ru> Date: Sat, 9 Mar 2024 00:35:05 +0000 Subject: [PATCH 032/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/dependencies/index.md`=20(#1?= =?UTF-8?q?1223)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/dependencies/index.md | 350 ++++++++++++++++++++ 1 file changed, 350 insertions(+) create mode 100644 docs/ru/docs/tutorial/dependencies/index.md diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..ad6e835e5 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -0,0 +1,350 @@ +# Зависимости + +**FastAPI** имеет очень мощную и интуитивную систему **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>**. + +Она проектировалась таким образом, чтобы быть простой в использовании и облегчить любому разработчику интеграцию других компонентов с **FastAPI**. + +## Что такое "Dependency Injection" (инъекция зависимости) + +**"Dependency Injection"** в программировании означает, что у вашего кода (в данном случае, вашей *функции обработки пути*) есть способы объявить вещи, которые запрашиваются для работы и использования: "зависимости". + +И потом эта система (в нашем случае **FastAPI**) организует всё, что требуется, чтобы обеспечить ваш код этой зависимостью (сделать "инъекцию" зависимости). + +Это очень полезно, когда вам нужно: + +* Обеспечить общую логику (один и тот же алгоритм снова и снова). +* Общее соединение с базой данных. +* Обеспечение безопасности, аутентификации, запроса роли и т.п. +* И многое другое. + +Всё это минимизирует повторение кода. + +## Первые шаги + +Давайте рассмотрим очень простой пример. Он настолько простой, что на данный момент почти бесполезный. + +Но таким способом мы можем сфокусироваться на том, как же всё таки работает система **Dependency Injection**. + +### Создание зависимости или "зависимого" +Давайте для начала сфокусируемся на зависимостях. + +Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Подсказка" + + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +**И всё.** + +**2 строки.** + +И теперь она той же формы и структуры, что и все ваши *функции обработки пути*. + +Вы можете думать об *функции обработки пути* как о функции без "декоратора" (без `@app.get("/some-path")`). + +И она может возвращать всё, что требуется. + +В этом случае, эта зависимость ожидает: + +* Необязательный query-параметр `q` с типом `str` +* Необязательный query-параметр `skip` с типом `int`, и значением по умолчанию `0` +* Необязательный query-параметр `limit` с типом `int`, и значением по умолчанию `100` + +И в конце она возвращает `dict`, содержащий эти значения. + +!!! Информация + + **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. + + Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. + + Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. + +### Import `Depends` + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +### Объявите зависимость в "зависимом" + +Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: + +=== "Python 3.10+" + + ```Python hl_lines="13 18" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Подсказка" + Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +`Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. + +Вы **не вызываете его** на месте (не добавляете скобочки в конце: 👎 *your_best_func()*👎), просто передаёте как параметр в `Depends()`. + +И потом функция берёт параметры так же, как *функция обработки пути*. + +!!! tip "Подсказка" + В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. + +Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о: + +* Вызове вашей зависимости ("зависимого") функции с корректными параметрами. +* Получении результата из вашей функции. +* Назначении результата в параметр в вашей *функции обработки пути*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. + +!!! check "Проверка" + Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. + + Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. + +## Объединяем с `Annotated` зависимостями + +В приведенном выше примере есть небольшое **повторение кода**. + +Когда вам нужно использовать `common_parameters()` зависимость, вы должны написать весь параметр с аннотацией типов и `Depends()`: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: + +=== "Python 3.10+" + + ```Python hl_lines="12 16 21" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14 18 23" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15 19 24" + {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} + ``` + +!!! tip "Подсказка" + Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. + + Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 + + +Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`. + +Это очень полезно, когда вы интегрируете это в **большую кодовую базу**, используя **одинаковые зависимости** снова и снова во **многих** ***операциях пути***. + +## Использовать `async` или не `async` + +Для зависимостей, вызванных **FastAPI** (то же самое, что и ваши *функции обработки пути*), те же правила, что приняты для определения ваших функций. + +Вы можете использовать `async def` или обычное `def`. + +Вы также можете объявить зависимости с `async def` внутри обычной `def` *функции обработки пути*, или `def` зависимости внутри `async def` *функции обработки пути*, и так далее. + +Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 + +!!! note "Информация" + Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. + +## Интеграция с OpenAPI + +Все заявления о запросах, валидаторы, требования ваших зависимостей (и подзависимостей) будут интегрированы в соответствующую OpenAPI-схему. + +В интерактивной документации будет вся информация по этим зависимостям тоже: + +<img src="/img/tutorial/dependencies/image01.png"> + +## Простое использование + +Если вы посмотрите на фото, *функция обработки пути* объявляется каждый раз, когда вычисляется путь, и тогда **FastAPI** позаботится о вызове функции с корректными параметрами, извлекая информацию из запроса. + +На самом деле, все (или большинство) веб-фреймворков работают по схожему сценарию. + +Вы никогда не вызываете эти функции на месте. Их вызовет ваш фреймворк (в нашем случае, **FastAPI**). + +С системой Dependency Injection, вы можете сообщить **FastAPI**, что ваша *функция обработки пути* "зависит" от чего-то ещё, что должно быть извлечено перед вашей *функцией обработки пути*, и **FastAPI** позаботится об извлечении и инъекции результата. + +Другие распространённые термины для описания схожей идеи "dependency injection" являются: + +- ресурсность +- доставка +- сервисность +- инъекция +- компонентность + +## **FastAPI** подключаемые модули + +Инъекции и модули могут быть построены с использованием системы **Dependency Injection**. Но на самом деле, **нет необходимости создавать новые модули**, просто используя зависимости, можно объявить бесконечное количество интеграций и взаимодействий, которые доступны вашей *функции обработки пути*. + +И зависимости могут быть созданы очень простым и интуитивным способом, что позволяет вам просто импортировать нужные пакеты Python и интегрировать их в API функции за пару строк. + +Вы увидите примеры этого в следующих главах о реляционных и NoSQL базах данных, безопасности и т.д. + +## Совместимость с **FastAPI** + +Простота Dependency Injection делает **FastAPI** совместимым с: + +- всеми реляционными базами данных +- NoSQL базами данных +- внешними пакетами +- внешними API +- системами авторизации, аутентификации +- системами мониторинга использования API +- системами ввода данных ответов +- и так далее. + +## Просто и сильно + +Хотя иерархическая система Dependency Injection очень проста для описания и использования, она по-прежнему очень мощная. + +Вы можете описывать зависимости в очередь, и они уже будут вызываться друг за другом. + +Когда иерархическое дерево построено, система **Dependency Injection** берет на себя решение всех зависимостей для вас (и их подзависимостей) и обеспечивает (инъектирует) результат на каждом шаге. + +Например, у вас есть 4 API-эндпоинта (*операции пути*): + +- `/items/public/` +- `/items/private/` +- `/users/{user_id}/activate` +- `/items/pro/` + +Тогда вы можете требовать разные права для каждого из них, используя зависимости и подзависимости: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Интегрировано с **OpenAPI** + +Все эти зависимости, объявляя свои требования, также добавляют параметры, проверки и т.д. к вашим операциям *path*. + +**FastAPI** позаботится о добавлении всего этого в схему открытого API, чтобы это отображалось в системах интерактивной документации. From d8eccdea1bd13c38c5bd487dea5029bbc258149f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 9 Mar 2024 00:35:46 +0000 Subject: [PATCH 033/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 10aa841f9..de7391ccc 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/tutorial/dependencies/index.md`. PR [#11223](https://github.com/tiangolo/fastapi/pull/11223) by [@kohiry](https://github.com/kohiry). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11242](https://github.com/tiangolo/fastapi/pull/11242) by [@jackleeio](https://github.com/jackleeio). * 🌐 Add Azerbaijani translation for `docs/az/learn/index.md`. PR [#11192](https://github.com/tiangolo/fastapi/pull/11192) by [@vusallyv](https://github.com/vusallyv). From ce8dfd801354d8ce1348b275742941842de581df Mon Sep 17 00:00:00 2001 From: Vusal Abdullayev <abdulla.vusal.3@gmail.com> Date: Sat, 9 Mar 2024 04:39:20 +0400 Subject: [PATCH 034/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Azerbaijani=20tran?= =?UTF-8?q?slation=20for=20`docs/az/docs/fastapi-people.md`=20(#11195)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/az/docs/fastapi-people.md | 185 ++++++++++++++++++++++++++++++ docs/az/{ => docs}/learn/index.md | 0 2 files changed, 185 insertions(+) create mode 100644 docs/az/docs/fastapi-people.md rename docs/az/{ => docs}/learn/index.md (100%) diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md new file mode 100644 index 000000000..5df183888 --- /dev/null +++ b/docs/az/docs/fastapi-people.md @@ -0,0 +1,185 @@ +--- +hide: + - navigation +--- + +# FastAPI İnsanlar + +FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var. + + + +## Yaradıcı - İcraçı + +Salam! 👋 + +Bu mənəm: + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.maintainers %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablar: {{ user.answers }}</div><div class="count">Pull Request-lər: {{ user.prs }}</div></div> +{% endfor %} + +</div> +{% endif %} + +Mən **FastAPI**-ın yaradıcısı və icraçısıyam. Əlavə məlumat almaq üçün [Yardım FastAPI - Yardım alın - Müəlliflə əlaqə qurun](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} səhifəsinə baxa bilərsiniz. + +...Burada isə sizə icmanı göstərmək istəyirəm. + +--- + +**FastAPI** icmadan çoxlu dəstək alır və mən onların əməyini vurğulamaq istəyirəm. + +Bu insanlar: + +* [GitHub-da başqalarının suallarına kömək edirlər](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. +* [Pull Request-lər yaradırlar](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. +* Pull Request-ləri ([xüsusilə tərcümələr üçün vacib olan](contributing.md#translations){.internal-link target=_blank}.) nəzərdən keçirirlər. + +Bu insanlara təşəkkür edirəm. 👏 🙇 + +## Keçən ayın ən fəal istifadəçiləri + +Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. ☕ + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.last_month_active %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Mütəxəssislər + +Burada **FastAPI Mütəxəssisləri** var. 🤓 + +Bu istifadəçilər indiyə qədər [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. + +Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut ediblər. ✨ + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.experts %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Ən yaxşı əməkdaşlar + +Burada **Ən yaxşı əməkdaşlar** var. 👷 + +Bu istifadəçilərin ən çox *birləşdirilmiş* [Pull Request-ləri var](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. + +Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstərmişlər. 📦 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_contributors %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Request-lər: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Əməkdaşlar səhifəsində</a> görə bilərsiniz. 👷 + +## Ən çox rəy verənlər + +Bu istifadəçilər **ən çox rəy verənlər**dir. + +### Tərcümələr üçün rəylər + +Mən yalnız bir neçə dildə danışıram (və çox da yaxşı deyil 😅). Bu səbəbdən, rəy verənlər sənədlərin [**tərcümələrini təsdiqləmək üçün gücə malik olanlar**](contributing.md#translations){.internal-link target=_blank}dır. Onlar olmadan, bir çox dilə tərcümə olunmuş sənədlər olmazdı. + +--- + +Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun, sənədlərin və xüsusilə də **tərcümələrin** keyfiyyətini təmin edirlər. + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_reviewers %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Rəylər: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Sponsorlar + +Bunlar **Sponsorlar**dır. 😎 + +Onlar mənim **FastAPI** (və digər) işlərimi əsasən <a href="hhttps://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsorlar</a> vasitəsilə dəstəkləyirlər. + +{% if sponsors %} + +{% if sponsors.gold %} + +### Qızıl Sponsorlar + +{% for sponsor in sponsors.gold -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% if sponsors.silver %} + +### Gümüş Sponsorlar + +{% for sponsor in sponsors.silver -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% if sponsors.bronze %} + +### Bürünc Sponsorlar + +{% for sponsor in sponsors.bronze -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% endif %} + +### Fərdi Sponsorlar + +{% if github_sponsors %} +{% for group in github_sponsors.sponsors %} + +<div class="user-list user-list-center"> + +{% for user in group %} +{% if user.login not in sponsors_badge.logins %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> + +{% endif %} +{% endfor %} + +</div> + +{% endfor %} +{% endif %} + +## Məlumatlar haqqında - texniki detallar + +Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün göstərdiyi əməyi vurğulamaqdır. + +Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək. + +Bu səhifənin məlumatları hər ay hesablanır və siz <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">buradan mənbə kodunu</a> oxuya bilərsiniz. + +Burada sponsorların əməyini də vurğulamaq istəyirəm. + +Mən həmçinin alqoritmi, bölmələri, eşikləri və s. yeniləmək hüququnu da qoruyuram (hər ehtimala qarşı 🤷). diff --git a/docs/az/learn/index.md b/docs/az/docs/learn/index.md similarity index 100% rename from docs/az/learn/index.md rename to docs/az/docs/learn/index.md From 9aad9e38686b06d207d55b51584e1a9910c51761 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 9 Mar 2024 00:40:55 +0000 Subject: [PATCH 035/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index de7391ccc..fd61dca37 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Azerbaijani translation for `docs/az/docs/fastapi-people.md`. PR [#11195](https://github.com/tiangolo/fastapi/pull/11195) by [@vusallyv](https://github.com/vusallyv). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/index.md`. PR [#11223](https://github.com/tiangolo/fastapi/pull/11223) by [@kohiry](https://github.com/kohiry). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11242](https://github.com/tiangolo/fastapi/pull/11242) by [@jackleeio](https://github.com/jackleeio). * 🌐 Add Azerbaijani translation for `docs/az/learn/index.md`. PR [#11192](https://github.com/tiangolo/fastapi/pull/11192) by [@vusallyv](https://github.com/vusallyv). From 65fd7f5bb063bf33e5911ac0e5d96c49eeb83756 Mon Sep 17 00:00:00 2001 From: "Aruelius.L" <25380989+Aruelius@users.noreply.github.com> Date: Wed, 13 Mar 2024 19:57:21 +0800 Subject: [PATCH 036/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/contributing.md`=20(#10887)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/contributing.md | 235 +++++++++++++++-------------------- 1 file changed, 101 insertions(+), 134 deletions(-) diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md index 4ebd67315..3dfc3db7c 100644 --- a/docs/zh/docs/contributing.md +++ b/docs/zh/docs/contributing.md @@ -1,6 +1,6 @@ # 开发 - 贡献 -首先,你最好先了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。 +首先,你可能想了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。 ## 开发 @@ -84,6 +84,17 @@ $ python -m venv env 如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 +确保虚拟环境中的 pip 版本是最新的,以避免后续步骤出现错误: + +<div class="termy"> + +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +</div> !!! tip 每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 @@ -114,6 +125,11 @@ $ pip install -r requirements.txt 这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 +!!! note "技术细节" + 仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 + + 这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 + ### 格式化 你可以运行下面的脚本来格式化和清理所有代码: @@ -126,91 +142,93 @@ $ bash scripts/format.sh </div> -它还会自动对所有导入代码进行整理。 +它还会自动对所有导入代码进行排序整理。 为了使整理正确进行,你需要在当前环境中安装本地的 FastAPI,即在运行上述段落中的命令时添加 `-e`。 -### 格式化导入 +## 文档 + +首先,请确保按上述步骤设置好环境,这将安装所有需要的依赖。 -还有另一个脚本可以格式化所有导入,并确保你没有未使用的导入代码: +### 实时文档 + +在本地开发时,可以使用该脚本构建站点并检查所做的任何更改,并实时重载: <div class="termy"> ```console -$ bash scripts/format-imports.sh +$ python ./scripts/docs.py live + +<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008 +<span style="color: green;">[INFO]</span> Start watching changes +<span style="color: green;">[INFO]</span> Start detecting changes ``` </div> -由于它依次运行了多个命令,并修改和还原了许多文件,所以运行时间会更长一些,因此经常地使用 `scripts/format.sh` 然后仅在提交前执行 `scripts/format-imports.sh` 会更好一些。 +文档服务将运行在 `http://127.0.0.1:8008`。 -## 文档 - -首先,请确保按上述步骤设置好环境,这将安装所有需要的依赖。 - -文档使用 <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a> 生成。 - -并且在 `./scripts/docs.py` 中还有适用的额外工具/脚本来处理翻译。 +这样,你可以编辑文档 / 源文件并实时查看更改。 !!! tip - 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 + 或者你也可以手动执行和该脚本一样的操作 -所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 - -许多的教程章节里包含有代码块。 + 进入语言目录,如果是英文文档,目录则是 `docs/en/`: -在大多数情况下,这些代码块是可以直接运行的真实完整的应用程序。 - -实际上,这些代码块不是写在 Markdown 文件内的,它们是位于 `./docs_src/` 目录中的 Python 文件。 + ```console + $ cd docs/en/ + ``` -生成站点时,这些 Python 文件会被包含/注入到文档中。 + 在该目录执行 `mkdocs` 命令 -### 用于测试的文档 + ```console + $ mkdocs serve --dev-addr 8008 + ``` -大多数的测试实际上都是针对文档中的示例源文件运行的。 +#### Typer CLI (可选) -这有助于确保: +本指引向你展示了如何直接用 `python` 运行 `./scripts/docs.py` 中的脚本。 -* 文档始终是最新的。 -* 文档示例可以直接运行。 -* 绝大多数特性既在文档中得以阐述,又通过测试覆盖进行保障。 +但你也可以使用 <a href="https://typer.tiangolo.com/typer-cli/" class="external-link" target="_blank">Typer CLI</a>,而且在安装了补全功能后,你将可以在终端中对命令进行自动补全。 -在本地开发期间,有一个脚本可以实时重载地构建站点并用来检查所做的任何更改: +如果你已经安装 Typer CLI ,则可以使用以下命令安装自动补全功能: <div class="termy"> ```console -$ python ./scripts/docs.py live +$ typer --install-completion -<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008 -<span style="color: green;">[INFO]</span> Start watching changes -<span style="color: green;">[INFO]</span> Start detecting changes +zsh completion installed in /home/user/.bashrc. +Completion will take effect once you restart the terminal. ``` </div> -它将在 `http://127.0.0.1:8008` 提供对文档的访问。 +### 文档架构 -这样,你可以编辑文档/源文件并实时查看更改。 +文档使用 <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a> 生成。 -#### Typer CLI (可选) +在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。 -本指引向你展示了如何直接用 `python` 程序运行 `./scripts/docs.py` 中的脚本。 +!!! tip + 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 -但你也可以使用 <a href="https://typer.tiangolo.com/typer-cli/" class="external-link" target="_blank">Typer CLI</a>,而且在安装了补全功能后,你将可以在终端中对命令进行自动补全。 +所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 -如果你打算安装 Typer CLI ,可以使用以下命令安装自动补全功能: +许多的教程中都有一些代码块,大多数情况下,这些代码是可以直接运行的,因为这些代码不是写在 Markdown 文件里的,而是写在 `./docs_src/` 目录中的 Python 文件里。 -<div class="termy"> +在生成站点的时候,这些 Python 文件会被打包进文档中。 -```console -$ typer --install-completion +### 测试文档 -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` +大多数的测试实际上都是针对文档中的示例源文件运行的。 + +这有助于确保: + +* 文档始终是最新的。 +* 文档示例可以直接运行。 +* 绝大多数特性既在文档中得以阐述,又通过测试覆盖进行保障。 -</div> ### 应用和文档同时运行 @@ -230,7 +248,7 @@ $ uvicorn tutorial001:app --reload ### 翻译 -非常感谢你能够参与文档的翻译!这项工作需要社区的帮助才能完成。 🌎 🚀 +**非常感谢**你能够参与文档的翻译!这项工作需要社区的帮助才能完成。 🌎 🚀 以下是参与帮助翻译的步骤。 @@ -243,17 +261,19 @@ $ uvicorn tutorial001:app --reload 详情可查看关于 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">添加 pull request 评审意见</a> 以同意合并或要求修改的文档。 -* 在 <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">issues</a> 中查找是否有对你所用语言所进行的协作翻译。 +* 检查在 <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 * 每翻译一个页面新增一个 pull request。这将使其他人更容易对其进行评审。 对于我(译注:作者使用西班牙语和英语)不懂的语言,我将在等待其他人评审翻译之后将其合并。 * 你还可以查看是否有你所用语言的翻译,并对其进行评审,这将帮助我了解翻译是否正确以及能否将其合并。 + * 可以在 <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussions</a> 中查看。 + * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3A%22awaiting+review%22" class="external-link" target="_blank">`lang-es`</a>。 -* 使用相同的 Python 示例并且仅翻译文档中的文本。无需进行任何其他更改示例也能正常工作。 +* 请使用相同的 Python 示例,且只需翻译文档中的文本,不用修改其它东西。 -* 使用相同的图片、文件名以及链接地址。无需进行任何其他调整来让它们兼容。 +* 请使用相同的图片、文件名以及链接地址,不用修改其它东西。 * 你可以从 <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" class="external-link" target="_blank">ISO 639-1 代码列表</a> 表中查找你想要翻译语言的两位字母代码。 @@ -264,7 +284,7 @@ $ uvicorn tutorial001:app --reload 对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 !!! tip - 主要("官方")语言是英语,位于 `docs/en/`目录。 + 默认语言是英语,位于 `docs/en/`目录。 现在为西班牙语文档运行实时服务器: @@ -281,11 +301,24 @@ $ python ./scripts/docs.py live es </div> -现在你可以访问 <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> 实时查看你所做的更改。 +!!! tip + 或者你也可以手动执行和该脚本一样的操作 -如果你查看 FastAPI 的线上文档网站,会看到每种语言都有所有页面。但是某些页面并未被翻译并且会有一处关于缺少翻译的提示。 + 进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: -但是当你像上面这样在本地运行文档时,你只会看到已经翻译的页面。 + ```console + $ cd docs/es/ + ``` + + 在该目录执行 `mkdocs` 命令 + + ```console + $ mkdocs serve --dev-addr 8008 + ``` + +现在你可以访问 <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> 实时查看你所做的更改。 + +如果你查看 FastAPI 的线上文档网站,会看到每种语言都有所有的文档页面,但是某些页面并未被翻译并且会有一处关于缺少翻译的提示。(但是当你像上面这样在本地运行文档时,你只会看到已经翻译的页面。) 现在假设你要为 [Features](features.md){.internal-link target=_blank} 章节添加翻译。 @@ -304,49 +337,9 @@ 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 -``` - -如果配置文件中还有其他条目,请确保你所翻译的新条目和它们之间的顺序与英文版本完全相同。 - -打开浏览器,现在你将看到文档展示了你所加入的新章节。 🎉 - -现在,你可以将它全部翻译完并在保存文件后进行预览。 +现在,你可以翻译这些内容并在保存文件后进行预览。 #### 新语言 @@ -354,7 +347,7 @@ nav: 假设你想要添加克里奥尔语翻译,而且文档中还没有该语言的翻译。 -点击上面提到的链接,可以查到"克里奥尔语"的代码为 `ht`。 +点击上面提到的“ISO 639-1 代码列表”链接,可以查到“克里奥尔语”的代码为 `ht`。 下一步是运行脚本以生成新的翻译目录: @@ -365,55 +358,32 @@ nav: $ python ./scripts/docs.py new-lang ht Successfully initialized: docs/ht -Updating ht -Updating en ``` </div> 现在,你可以在编辑器中查看新创建的目录 `docs/ht/`。 -!!! tip - 在添加实际的翻译之前,仅以此创建首个 pull request 来设定新语言的配置。 - - 这样当你在翻译第一个页面时,其他人可以帮助翻译其他页面。🚀 - -首先翻译文档主页 `docs/ht/index.md`。 - -然后,你可以根据上面的"已有语言"的指引继续进行翻译。 +这条命令会生成一个从 `en` 版本继承了所有属性的配置文件 `docs/ht/mkdocs.yml`: -##### 不支持的新语言 - -如果在运行实时服务器脚本时收到关于不支持该语言的错误,类似于: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html +```yaml +INHERIT: ../en/mkdocs.yml ``` -这意味着文档的主题不支持该语言(在这种例子中,编造的语言代码是 `xx`)。 - -但是别担心,你可以将主题语言设置为英语,然后翻译文档的内容。 - -如果你需要这么做,编辑新语言目录下的 `mkdocs.yml`,它将有类似下面的内容: +!!! tip + 你也可以自己手动创建包含这些内容的文件。 -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` +这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。 -将其中的 language 项从 `xx`(你的语言代码)更改为 `en`。 +然后,你可以根据上面的"已有语言"的指引继续进行翻译。 -然后,你就可以再次启动实时服务器了。 +翻译完成后,你就可以用 `docs/ht/mkdocs.yml` 和 `docs/ht/index.md` 发起 PR 了。🎉 #### 预览结果 -当你通过 `live` 命令使用 `./scripts/docs.py` 中的脚本时,该脚本仅展示当前语言已有的文件和翻译。 +你可以执行 `./scripts/docs.py live` 命令来预览结果(或者 `mkdocs serve`)。 -但是当你完成翻译后,你可以像在线上展示一样测试所有内容。 +但是当你完成翻译后,你可以像在线上展示一样测试所有内容,包括所有其他语言。 为此,首先构建所有文档: @@ -423,19 +393,16 @@ theme: // 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 ``` </div> -这将在 `./docs_build/` 目录中为每一种语言生成全部的文档。还包括添加所有缺少翻译的文件,并带有一条"此文件还没有翻译"的提醒。但是你不需要对该目录执行任何操作。 +这样会对每一种语言构建一个独立的文档站点,并最终把这些站点全部打包输出到 `./site/` 目录。 + -然后,它针对每种语言构建独立的 MkDocs 站点,将它们组合在一起,并在 `./site/` 目录中生成最终的输出。 然后你可以使用命令 `serve` 来运行生成的站点: From 176a93f47695b2af4f75d0fc56c6f92c41c5a31f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 13 Mar 2024 11:57:47 +0000 Subject: [PATCH 037/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index fd61dca37..ca3b71e96 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/contributing.md`. PR [#10887](https://github.com/tiangolo/fastapi/pull/10887) by [@Aruelius](https://github.com/Aruelius). * 🌐 Add Azerbaijani translation for `docs/az/docs/fastapi-people.md`. PR [#11195](https://github.com/tiangolo/fastapi/pull/11195) by [@vusallyv](https://github.com/vusallyv). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/index.md`. PR [#11223](https://github.com/tiangolo/fastapi/pull/11223) by [@kohiry](https://github.com/kohiry). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11242](https://github.com/tiangolo/fastapi/pull/11242) by [@jackleeio](https://github.com/jackleeio). From 0e2f2d6d3a206d29087c9b34646b32d76bdcf1c8 Mon Sep 17 00:00:00 2001 From: Joshua Hanson <52810749+joshjhans@users.noreply.github.com> Date: Wed, 13 Mar 2024 13:02:19 -0600 Subject: [PATCH 038/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20`python-multipa?= =?UTF-8?q?rt`=20GitHub=20link=20in=20all=20docs=20from=20`https://andrew-?= =?UTF-8?q?d.github.io/python-multipart/`=20to=20`https://github.com/Klude?= =?UTF-8?q?x/python-multipart`=20(#11239)?= 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/em/docs/index.md | 2 +- docs/em/docs/tutorial/request-files.md | 2 +- docs/em/docs/tutorial/request-forms-and-files.md | 2 +- docs/em/docs/tutorial/request-forms.md | 2 +- docs/em/docs/tutorial/security/first-steps.md | 2 +- docs/en/docs/index.md | 2 +- docs/en/docs/tutorial/request-files.md | 2 +- docs/en/docs/tutorial/request-forms-and-files.md | 2 +- docs/en/docs/tutorial/request-forms.md | 2 +- docs/en/docs/tutorial/security/first-steps.md | 2 +- docs/es/docs/index.md | 2 +- docs/fa/docs/index.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/ja/docs/tutorial/request-forms.md | 2 +- docs/ja/docs/tutorial/security/first-steps.md | 2 +- docs/ko/docs/index.md | 2 +- docs/ko/docs/tutorial/request-files.md | 2 +- docs/ko/docs/tutorial/request-forms-and-files.md | 2 +- docs/pl/docs/index.md | 2 +- docs/pt/docs/index.md | 2 +- docs/pt/docs/tutorial/request-forms-and-files.md | 2 +- docs/pt/docs/tutorial/request-forms.md | 2 +- docs/pt/docs/tutorial/security/first-steps.md | 2 +- docs/ru/docs/index.md | 2 +- docs/ru/docs/tutorial/request-files.md | 2 +- docs/ru/docs/tutorial/request-forms-and-files.md | 2 +- docs/ru/docs/tutorial/request-forms.md | 2 +- docs/ru/docs/tutorial/security/first-steps.md | 2 +- docs/tr/docs/index.md | 2 +- docs/uk/docs/index.md | 2 +- docs/vi/docs/index.md | 2 +- docs/yo/docs/index.md | 2 +- docs/zh-hant/docs/index.md | 2 +- docs/zh/docs/index.md | 2 +- docs/zh/docs/tutorial/request-files.md | 2 +- docs/zh/docs/tutorial/request-forms-and-files.md | 2 +- docs/zh/docs/tutorial/request-forms.md | 2 +- docs/zh/docs/tutorial/security/first-steps.md | 2 +- 45 files changed, 45 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 8d3e4c68d..a60d8775c 100644 --- a/README.md +++ b/README.md @@ -459,7 +459,7 @@ Used by Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Required if you want to use the `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index a22706512..fb82bea1b 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -452,7 +452,7 @@ Starlette tərəfindən istifadə olunanlar: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Əgər `TestClient` strukturundan istifadə edəcəksinizsə, tələb olunur. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Standart <abbr title="Şablon: Template">şablon</abbr> konfiqurasiyasından istifadə etmək istəyirsinizsə, tələb olunur. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - `request.form()` ilə forma <abbr title="HTTP sorğusu ilə alınan string məlumatın Python obyektinə çevrilməsi">"çevirmə"</abbr> dəstəyindən istifadə etmək istəyirsinizsə, tələb olunur. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - `request.form()` ilə forma <abbr title="HTTP sorğusu ilə alınan string məlumatın Python obyektinə çevrilməsi">"çevirmə"</abbr> dəstəyindən istifadə etmək istəyirsinizsə, tələb olunur. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` dəstəyi üçün tələb olunur. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - `SchemaGenerator` dəstəyi üçün tələb olunur (Çox güman ki, FastAPI istifadə edərkən buna ehtiyacınız olmayacaq). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse` istifadə etmək istəyirsinizsə, tələb olunur. diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 4f778e873..28ef5d6d1 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -446,7 +446,7 @@ Pydantic দ্বারা ব্যবহৃত: - <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - আপনি যদি `TestClient` ব্যবহার করতে চান তাহলে আবশ্যক। - <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - আপনি যদি প্রদত্ত টেমপ্লেট রূপরেখা ব্যবহার করতে চান তাহলে প্রয়োজন। -- <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, `request.form()` সহ। +- <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, `request.form()` সহ। - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` সহায়তার জন্য প্রয়োজন। - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)। - <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` সহায়তার জন্য প্রয়োজন। diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index c7df28160..3c461b6ed 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -452,7 +452,7 @@ item: Item * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - ✔ 🚥 👆 💚 ⚙️ `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - ✔ 🚥 👆 💚 ⚙️ 🔢 📄 📳. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - ✔ 🚥 👆 💚 🐕🦺 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>, ⏮️ `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - ✔ 🚥 👆 💚 🐕🦺 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>, ⏮️ `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - ✔ `SessionMiddleware` 🐕🦺. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - ✔ 💃 `SchemaGenerator` 🐕🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 26631823f..be2218f89 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -3,7 +3,7 @@ 👆 💪 🔬 📁 📂 👩💻 ⚙️ `File`. !!! info - 📨 📂 📁, 🥇 ❎ <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + 📨 📂 📁, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 99aeca000..0415dbf01 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ 👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`. !!! info - 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index fa74adae5..f12d6e650 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ 🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`. !!! info - ⚙️ 📨, 🥇 ❎ <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + ⚙️ 📨, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 6dec6f2c3..8c2c95cfd 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -27,7 +27,7 @@ ## 🏃 ⚫️ !!! info - 🥇 ❎ <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. 🤶 Ⓜ. `pip install python-multipart`. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 3660e74e3..10430f723 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -462,7 +462,7 @@ Used by Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Required if you want to use the `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 8eb8ace64..17ac3b25d 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -3,7 +3,7 @@ You can define files to be uploaded by the client using `File`. !!! info - To receive uploaded files, first install <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + To receive uploaded files, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. E.g. `pip install python-multipart`. diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index a58291dc8..676ed35ad 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ You can define files and form fields at the same time using `File` and `Form`. !!! info - To receive uploaded files and/or form data, first install <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + To receive uploaded files and/or form data, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. E.g. `pip install python-multipart`. diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 0e8ac5f4f..5f8f7b148 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ When you need to receive form fields instead of JSON, you can use `Form`. !!! info - To use forms, first install <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + To use forms, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. E.g. `pip install python-multipart`. diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 2f39f1ec2..7d86e453e 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -45,7 +45,7 @@ Copy the example in a file `main.py`: ## Run it !!! info - First install <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + First install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. E.g. `pip install python-multipart`. diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index df8342357..28b7f4d1b 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -439,7 +439,7 @@ Usados por Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Requerido si quieres usar el `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Requerido si quieres usar la configuración por defecto de templates. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Requerido si quieres dar soporte a <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> de formularios, con `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Requerido si quieres dar soporte a <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> de formularios, con `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Requerido para dar soporte a `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Requerido para dar soporte a `GraphQLApp`. diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index cc211848b..b267eef23 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -443,7 +443,7 @@ item: Item * <a href="https://www.python-httpx.org" target="_blank"><code>HTTPX</code></a> - در صورتی که میخواهید از `TestClient` استفاده کنید. * <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - در صورتی که میخواهید از `FileResponse` و `StaticFiles` استفاده کنید. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - در صورتی که بخواهید از پیکربندی پیشفرض برای قالبها استفاده کنید. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت <abbr title="تبدیل رشته متنی موجود در درخواست HTTP به انواع داده پایتون">"تجزیه (parse)"</abbr> فرم استفاده کنید. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت <abbr title="تبدیل رشته متنی موجود در درخواست HTTP به انواع داده پایتون">"تجزیه (parse)"</abbr> فرم استفاده کنید. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - در صورتی که از `GraphQLApp` پشتیبانی میکنید. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index f732fc74c..3a757409f 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -451,7 +451,7 @@ Utilisées par Starlette : * <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Obligatoire si vous souhaitez utiliser `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Obligatoire si vous souhaitez utiliser la configuration de template par défaut. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Obligatoire si vous souhaitez supporter le <abbr title="convertit la chaine de caractère d'une requête HTTP en donnée Python">"décodage"</abbr> de formulaire avec `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Obligatoire si vous souhaitez supporter le <abbr title="convertit la chaine de caractère d'une requête HTTP en donnée Python">"décodage"</abbr> de formulaire avec `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Obligatoire pour la prise en charge de `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Obligatoire si vous souhaitez utiliser `UJSONResponse`. diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 802dbe8b5..e404baa59 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -446,7 +446,7 @@ item: Item - <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - דרוש אם ברצונכם להשתמש ב - `TestClient`. - <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים. -- <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - דרוש אם ברצונכם לתמוך ב <abbr title="המרת המחרוזת שמגיעה מבקשת HTTP למידע פייתון">"פרסור"</abbr> טפסים, באצמעות <code dir="ltr">request.form()</code>. +- <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - דרוש אם ברצונכם לתמוך ב <abbr title="המרת המחרוזת שמגיעה מבקשת HTTP למידע פייתון">"פרסור"</abbr> טפסים, באצמעות <code dir="ltr">request.form()</code>. - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`. - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI). - <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 29c3c05ac..3bc3724e2 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -453,7 +453,7 @@ Starlette által használt: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Követelmény ha a `TestClient`-et akarod használni. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Követelmény ha az alap template konfigurációt akarod használni. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Követelmény ha <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>-ot akarsz támogatni, `request.form()`-al. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Követelmény ha <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>-ot akarsz támogatni, `request.form()`-al. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Követelmény `SessionMiddleware` támogatáshoz. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szükség FastAPI használása esetén). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Követelmény ha `UJSONResponse`-t akarsz használni. diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 6190eb6aa..0b7a896e1 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -446,7 +446,7 @@ Usate da Starlette: * <a href="http://docs.python-requests.org" target="_blank"><code>requests</code></a> - Richiesto se vuoi usare il `TestClient`. * <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Richiesto se vuoi usare `FileResponse` o `StaticFiles`. * <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - Richiesto se vuoi usare la configurazione template di default. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Richiesto se vuoi supportare il <abbr title="convertire la stringa che proviene da una richiesta HTTP in dati Python">"parsing"</abbr> con `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Richiesto se vuoi supportare il <abbr title="convertire la stringa che proviene da una richiesta HTTP in dati Python">"parsing"</abbr> con `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Richiesto per usare `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Richiesto per il supporto di `GraphQLApp`. diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 22c31e7ca..84cb48308 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -437,7 +437,7 @@ Starlette によって使用されるもの: - <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - `TestClient`を使用するために必要です。 - <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - デフォルトのテンプレート設定を使用する場合は必要です。 -- <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>`request.form()`からの変換をサポートしたい場合は必要です。 +- <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>`request.form()`からの変換をサポートしたい場合は必要です。 - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` サポートのためには必要です。 - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。) - <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` サポートのためには必要です。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index bce6e8d9a..f90c49746 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 !!! info "情報" - フォームを使うためには、まず<a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 + フォームを使うためには、まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 たとえば、`pip install python-multipart`のように。 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index f83b59cfd..f1c43b7b4 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -27,7 +27,7 @@ ## 実行 !!! info "情報" - まず<a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 + まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 例えば、`pip install python-multipart`。 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 594b092f7..d3d5d4e84 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -443,7 +443,7 @@ Starlette이 사용하는: * <a href="https://www.python-httpx.org" target="_blank"><code>HTTPX</code></a> - `TestClient`를 사용하려면 필요. * <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - 기본 템플릿 설정을 사용하려면 필요. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - `request.form()`과 함께 <abbr title="HTTP 요청에서 파이썬 데이터로 가는 문자열 변환">"parsing"</abbr>의 지원을 원하면 필요. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - `request.form()`과 함께 <abbr title="HTTP 요청에서 파이썬 데이터로 가는 문자열 변환">"parsing"</abbr>의 지원을 원하면 필요. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` 지원을 위해 필요. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` 지원을 위해 필요. diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index 03a6d593a..468c46283 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -3,7 +3,7 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. !!! info "정보" - 업로드된 파일을 전달받기 위해 먼저 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. + 업로드된 파일을 전달받기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. 예시) `pip install python-multipart`. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index fdf8dbad0..bd5f41918 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. !!! info "정보" - 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. + 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. 예 ) `pip install python-multipart`. diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 49f5c2b01..828b13a05 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -442,7 +442,7 @@ Używane przez Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Wymagane jeżeli chcesz korzystać z `TestClient`. * <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Wymagane jeżeli chcesz korzystać z `FileResponse` albo `StaticFiles`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Wymagane jeżeli chcesz używać domyślnej konfiguracji szablonów. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Wymagane jeżelich chcesz wsparcie <abbr title="przetwarzania stringa którzy przychodzi z żądaniem HTTP na dane używane przez Pythona">"parsowania"</abbr> formularzy, używając `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Wymagane jeżelich chcesz wsparcie <abbr title="przetwarzania stringa którzy przychodzi z żądaniem HTTP na dane używane przez Pythona">"parsowania"</abbr> formularzy, używając `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Wymagany dla wsparcia `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Wymagane dla wsparcia `GraphQLApp`. diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index d1e64b3b9..390247ec9 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -436,7 +436,7 @@ Usados por Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Necessário se você quiser utilizar o `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Necessário se você quiser utilizar a configuração padrão de templates. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Necessário se você quiser suporte com <abbr title="converte uma string que chega de uma requisição HTTP para dados Python">"parsing"</abbr> de formulário, com `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Necessário se você quiser suporte com <abbr title="converte uma string que chega de uma requisição HTTP para dados Python">"parsing"</abbr> de formulário, com `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Necessário para suporte a `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Necessário para suporte a `GraphQLApp`. diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 259f262f4..22954761b 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. !!! info "Informação" - Para receber arquivos carregados e/ou dados de formulário, primeiro instale <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + Para receber arquivos carregados e/ou dados de formulário, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Por exemplo: `pip install python-multipart`. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index b6c1b0e75..0eb67391b 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. !!! info "Informação" - Para usar formulários, primeiro instale <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + Para usar formulários, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Ex: `pip install python-multipart`. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index ed07d1c96..395621d3b 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -26,7 +26,7 @@ Copie o exemplo em um arquivo `main.py`: ## Execute-o !!! informação - Primeiro, instale <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + Primeiro, instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Ex: `pip install python-multipart`. diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 6c99f623d..6e88b496f 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -445,7 +445,7 @@ item: Item * <a href="https://www.python-httpx.org" target="_blank"><code>HTTPX</code></a> - Обязательно, если вы хотите использовать `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Обязательно, если вы хотите использовать конфигурацию шаблона по умолчанию. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Обязательно, если вы хотите поддерживать форму <abbr title="преобразование строки, полученной из HTTP-запроса, в данные Python">"парсинга"</abbr> с помощью `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Обязательно, если вы хотите поддерживать форму <abbr title="преобразование строки, полученной из HTTP-запроса, в данные Python">"парсинга"</abbr> с помощью `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Обязательно, для поддержки `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Обязательно, если вы хотите использовать `UJSONResponse`. diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 00f8c8377..79b3bd067 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -3,7 +3,7 @@ Используя класс `File`, мы можем позволить клиентам загружать файлы. !!! info "Дополнительная информация" - Чтобы получать загруженные файлы, сначала установите <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + Чтобы получать загруженные файлы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Например: `pip install python-multipart`. diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index 3f587c38a..a08232ca7 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -3,7 +3,7 @@ Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. !!! info "Дополнительная информация" - Чтобы получать загруженные файлы и/или данные форм, сначала установите <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + Чтобы получать загруженные файлы и/или данные форм, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Например: `pip install python-multipart`. diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index 0fc9e4eda..fa2bcb7cb 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -3,7 +3,7 @@ Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. !!! info "Дополнительная информация" - Чтобы использовать формы, сначала установите <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + Чтобы использовать формы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Например, выполните команду `pip install python-multipart`. diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index b70a60a38..fdeccc01a 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -45,7 +45,7 @@ ## Запуск !!! info "Дополнительная информация" - Вначале, установите библиотеку <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + Вначале, установите библиотеку <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. А именно: `pip install python-multipart`. diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index ac8830880..fbde3637a 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -453,7 +453,7 @@ Starlette tarafında kullanılan: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Eğer `TestClient` yapısını kullanacaksanız gereklidir. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Eğer varsayılan template konfigürasyonunu kullanacaksanız gereklidir. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Eğer `request.form()` ile form <abbr title="HTTP isteği ile gelen string veriyi Python nesnesine çevirme.">dönüşümü</abbr> desteğini kullanacaksanız gereklidir. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Eğer `request.form()` ile form <abbr title="HTTP isteği ile gelen string veriyi Python nesnesine çevirme.">dönüşümü</abbr> desteğini kullanacaksanız gereklidir. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` desteği için gerekli. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse` kullanacaksanız gerekli. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index fad693f79..afcaa8918 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -448,7 +448,7 @@ Starlette використовує: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Необхідно, якщо Ви хочете використовувати `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Необхідно, якщо Ви хочете використовувати шаблони як конфігурацію за замовчуванням. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Необхідно, якщо Ви хочете підтримувати <abbr title="перетворення рядка, який надходить із запиту HTTP, на дані Python">"розбір"</abbr> форми за допомогою `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Необхідно, якщо Ви хочете підтримувати <abbr title="перетворення рядка, який надходить із запиту HTTP, на дані Python">"розбір"</abbr> форми за допомогою `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Необхідно для підтримки `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 3f416dbec..a3dec4be7 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -455,7 +455,7 @@ Sử dụng Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Bắt buộc nếu bạn muốn sử dụng `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Bắt buộc nếu bạn muốn sử dụng cấu hình template engine mặc định. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Bắt buộc nếu bạn muốn hỗ trợ <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, form với `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Bắt buộc nếu bạn muốn hỗ trợ <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, form với `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Bắt buộc để hỗ trợ `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Bắt buộc để hỗ trợ `SchemaGenerator` cho Starlette (bạn có thể không cần nó trong FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 101e13b6b..9e844d44e 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -453,7 +453,7 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn <a href="https://fastapi.tian * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Nílò tí ó bá fẹ́ láti lọ `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Nílò tí ó bá fẹ́ láti lọ iṣeto awoṣe aiyipada. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún <abbr title="tí ó se ìyípadà ọ̀rọ̀-ìyọ̀/òkun-ọ̀rọ̀ tí ó wà láti ìbéèrè HTTP sí inú àkójọf'áyẹ̀wò Python">"àyẹ̀wò"</abbr> fọọmu, pẹ̀lú `request.form()`. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún <abbr title="tí ó se ìyípadà ọ̀rọ̀-ìyọ̀/òkun-ọ̀rọ̀ tí ó wà láti ìbéèrè HTTP sí inú àkójọf'áyẹ̀wò Python">"àyẹ̀wò"</abbr> fọọmu, pẹ̀lú `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Nílò fún àtìlẹ́yìn `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index e7a2efec9..eec12dfae 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -453,7 +453,7 @@ item: Item - <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - 使用 `TestClient`時必須安裝。 - <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - 使用預設的模板配置時必須安裝。 -- <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - 需要使用 `request.form()` 對表單進行<abbr title="轉換來自表單的 HTTP 請求到 Python 資料型別"> "解析" </abbr>時安裝。 +- <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - 需要使用 `request.form()` 對表單進行<abbr title="轉換來自表單的 HTTP 請求到 Python 資料型別"> "解析" </abbr>時安裝。 - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - 需要使用 `SessionMiddleware` 支援時安裝。 - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。 - <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 使用 `UJSONResponse` 時必須安裝。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index d776e5813..7451d1072 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -443,7 +443,7 @@ item: Item * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - 使用 `TestClient` 时安装。 * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - 使用默认模板配置时安装。 -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - 需要通过 `request.form()` 对表单进行<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">「解析」</abbr>时安装。 +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - 需要通过 `request.form()` 对表单进行<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">「解析」</abbr>时安装。 * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - 需要 `SessionMiddleware` 支持时安装。 * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。 * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - 需要 `GraphQLApp` 支持时安装。 diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 2c48f33ca..1cd3518cf 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -6,7 +6,7 @@ 因为上传文件以「表单数据」形式发送。 - 所以接收上传文件,要预先安装 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>。 + 所以接收上传文件,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 例如: `pip install python-multipart`。 diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md index 70cd70f98..f58593669 100644 --- a/docs/zh/docs/tutorial/request-forms-and-files.md +++ b/docs/zh/docs/tutorial/request-forms-and-files.md @@ -4,7 +4,7 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 !!! info "说明" - 接收上传文件或表单数据,要预先安装 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>。 + 接收上传文件或表单数据,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 例如,`pip install python-multipart`。 diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md index 6436ffbcd..e4fcd88ff 100644 --- a/docs/zh/docs/tutorial/request-forms.md +++ b/docs/zh/docs/tutorial/request-forms.md @@ -4,7 +4,7 @@ !!! info "说明" - 要使用表单,需预先安装 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>。 + 要使用表单,需预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 例如,`pip install python-multipart`。 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index dda956417..f28cc24f8 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -45,7 +45,7 @@ !!! info "说明" - 先安装 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>。 + 先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 安装命令: `pip install python-multipart`。 From 72e07c4f44b0b4e8bb844df6ddbb0a2355459ff9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 13 Mar 2024 19:02:42 +0000 Subject: [PATCH 039/846] =?UTF-8?q?=F0=9F=93=9D=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 ca3b71e96..d9aca2d01 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update `python-multipart` GitHub link in all docs from `https://andrew-d.github.io/python-multipart/` to `https://github.com/Kludex/python-multipart`. PR [#11239](https://github.com/tiangolo/fastapi/pull/11239) by [@joshjhans](https://github.com/joshjhans). + ### Translations * 🌐 Update Chinese translation for `docs/zh/docs/contributing.md`. PR [#10887](https://github.com/tiangolo/fastapi/pull/10887) by [@Aruelius](https://github.com/Aruelius). From 478288700ab6a9be3cacb97e9f74eb5e4c01fe0c Mon Sep 17 00:00:00 2001 From: bebop <andy.clapson@gmail.com> Date: Wed, 13 Mar 2024 15:07:10 -0400 Subject: [PATCH 040/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20examples=20for?= =?UTF-8?q?=20tests=20to=20replace=20"inexistent"=20for=20"nonexistent"=20?= =?UTF-8?q?(#11220)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs_src/app_testing/app_b/test_main.py | 2 +- docs_src/app_testing/app_b_an/test_main.py | 2 +- docs_src/app_testing/app_b_an_py310/test_main.py | 2 +- docs_src/app_testing/app_b_an_py39/test_main.py | 2 +- docs_src/app_testing/app_b_py310/test_main.py | 2 +- tests/test_tutorial/test_security/test_tutorial005.py | 2 +- tests/test_tutorial/test_security/test_tutorial005_an.py | 2 +- tests/test_tutorial/test_security/test_tutorial005_an_py310.py | 2 +- tests/test_tutorial/test_security/test_tutorial005_an_py39.py | 2 +- tests/test_tutorial/test_security/test_tutorial005_py310.py | 2 +- tests/test_tutorial/test_security/test_tutorial005_py39.py | 2 +- tests/test_tutorial/test_sql_databases/test_sql_databases.py | 2 +- .../test_sql_databases/test_sql_databases_middleware.py | 2 +- .../test_sql_databases/test_sql_databases_middleware_py310.py | 2 +- .../test_sql_databases/test_sql_databases_middleware_py39.py | 2 +- .../test_sql_databases/test_sql_databases_py310.py | 2 +- .../test_tutorial/test_sql_databases/test_sql_databases_py39.py | 2 +- tests/test_tutorial/test_testing/test_main_b.py | 2 +- tests/test_tutorial/test_testing/test_main_b_an.py | 2 +- tests/test_tutorial/test_testing/test_main_b_an_py310.py | 2 +- tests/test_tutorial/test_testing/test_main_b_an_py39.py | 2 +- tests/test_tutorial/test_testing/test_main_b_py310.py | 2 +- 22 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs_src/app_testing/app_b/test_main.py b/docs_src/app_testing/app_b/test_main.py index 4e2b98e23..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b/test_main.py +++ b/docs_src/app_testing/app_b/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py index d186b8ecb..e2eda449d 100644 --- a/docs_src/app_testing/app_b_an/test_main.py +++ b/docs_src/app_testing/app_b_an/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_an_py310/test_main.py b/docs_src/app_testing/app_b_an_py310/test_main.py index d186b8ecb..e2eda449d 100644 --- a/docs_src/app_testing/app_b_an_py310/test_main.py +++ b/docs_src/app_testing/app_b_an_py310/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py index d186b8ecb..e2eda449d 100644 --- a/docs_src/app_testing/app_b_an_py39/test_main.py +++ b/docs_src/app_testing/app_b_an_py39/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_py310/test_main.py b/docs_src/app_testing/app_b_py310/test_main.py index 4e2b98e23..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_py310/test_main.py +++ b/docs_src/app_testing/app_b_py310/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py index c669c306d..2e580dbb3 100644 --- a/tests/test_tutorial/test_security/test_tutorial005.py +++ b/tests/test_tutorial/test_security/test_tutorial005.py @@ -128,7 +128,7 @@ def test_token_no_scope(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inexistent_user(): +def test_token_nonexistent_user(): response = client.get( "/users/me", headers={ diff --git a/tests/test_tutorial/test_security/test_tutorial005_an.py b/tests/test_tutorial/test_security/test_tutorial005_an.py index aaab04f78..04c7d60bc 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_an.py +++ b/tests/test_tutorial/test_security/test_tutorial005_an.py @@ -128,7 +128,7 @@ def test_token_no_scope(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inexistent_user(): +def test_token_nonexistent_user(): response = client.get( "/users/me", headers={ diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py b/tests/test_tutorial/test_security/test_tutorial005_an_py310.py index 243d0773c..9c7f83ed2 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py +++ b/tests/test_tutorial/test_security/test_tutorial005_an_py310.py @@ -151,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py310 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py b/tests/test_tutorial/test_security/test_tutorial005_an_py39.py index 17a3f9aa2..04cc1b014 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py +++ b/tests/test_tutorial/test_security/test_tutorial005_an_py39.py @@ -151,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py39 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ diff --git a/tests/test_tutorial/test_security/test_tutorial005_py310.py b/tests/test_tutorial/test_security/test_tutorial005_py310.py index 06455cd63..98c60c1c2 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_py310.py +++ b/tests/test_tutorial/test_security/test_tutorial005_py310.py @@ -151,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py310 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ diff --git a/tests/test_tutorial/test_security/test_tutorial005_py39.py b/tests/test_tutorial/test_security/test_tutorial005_py39.py index 9455bfb4e..cd2157d54 100644 --- a/tests/test_tutorial/test_security/test_tutorial005_py39.py +++ b/tests/test_tutorial/test_security/test_tutorial005_py39.py @@ -151,7 +151,7 @@ def test_token_no_scope(client: TestClient): @needs_py39 -def test_token_inexistent_user(client: TestClient): +def test_token_nonexistent_user(client: TestClient): response = client.get( "/users/me", headers={ diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases.py b/tests/test_tutorial/test_sql_databases/test_sql_databases.py index 03e747433..e3e2b36a8 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases.py @@ -54,7 +54,7 @@ def test_get_user(client): # TODO: pv2 add version with Pydantic v2 @needs_pydanticv1 -def test_inexistent_user(client): +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py index a503ef2a6..73b97e09d 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py @@ -50,7 +50,7 @@ def test_get_user(client): # TODO: pv2 add version with Pydantic v2 @needs_pydanticv1 -def test_inexistent_user(client): +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py index d54cc6552..a078f012a 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py @@ -58,7 +58,7 @@ def test_get_user(client): @needs_py310 # TODO: pv2 add version with Pydantic v2 @needs_pydanticv1 -def test_inexistent_user(client): +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py index 4e43995e6..a5da07ac6 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py @@ -58,7 +58,7 @@ def test_get_user(client): @needs_py39 # TODO: pv2 add version with Pydantic v2 @needs_pydanticv1 -def test_inexistent_user(client): +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py index b89b8b031..5a9106598 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py @@ -57,7 +57,7 @@ def test_get_user(client): @needs_py310 # TODO: pv2 add version with Pydantic v2 @needs_pydanticv1 -def test_inexistent_user(client): +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py index 13351bc81..a354ba905 100644 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py +++ b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py @@ -57,7 +57,7 @@ def test_get_user(client): @needs_py39 # TODO: pv2 add version with Pydantic v2 @needs_pydanticv1 -def test_inexistent_user(client): +def test_nonexistent_user(client): response = client.get("/users/999") assert response.status_code == 404, response.text diff --git a/tests/test_tutorial/test_testing/test_main_b.py b/tests/test_tutorial/test_testing/test_main_b.py index fc1a832f9..1e1836f5b 100644 --- a/tests/test_tutorial/test_testing/test_main_b.py +++ b/tests/test_tutorial/test_testing/test_main_b.py @@ -5,6 +5,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an.py b/tests/test_tutorial/test_testing/test_main_b_an.py index b64c5f710..e53fc3224 100644 --- a/tests/test_tutorial/test_testing/test_main_b_an.py +++ b/tests/test_tutorial/test_testing/test_main_b_an.py @@ -5,6 +5,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py310.py b/tests/test_tutorial/test_testing/test_main_b_an_py310.py index 194700b6d..c974e5dc1 100644 --- a/tests/test_tutorial/test_testing/test_main_b_an_py310.py +++ b/tests/test_tutorial/test_testing/test_main_b_an_py310.py @@ -8,6 +8,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py39.py b/tests/test_tutorial/test_testing/test_main_b_an_py39.py index 2f8a13623..71f99726c 100644 --- a/tests/test_tutorial/test_testing/test_main_b_an_py39.py +++ b/tests/test_tutorial/test_testing/test_main_b_an_py39.py @@ -8,6 +8,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_py310.py b/tests/test_tutorial/test_testing/test_main_b_py310.py index a504ed234..e30cdc073 100644 --- a/tests/test_tutorial/test_testing/test_main_b_py310.py +++ b/tests/test_tutorial/test_testing/test_main_b_py310.py @@ -8,6 +8,6 @@ def test_app(): test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() From 9c2b6d09f15b65cb17053609058bb350925d0095 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 13 Mar 2024 19:07:36 +0000 Subject: [PATCH 041/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d9aca2d01..143f743f7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update examples for tests to replace "inexistent" for "nonexistent". PR [#11220](https://github.com/tiangolo/fastapi/pull/11220) by [@Homesteady](https://github.com/Homesteady). * 📝 Update `python-multipart` GitHub link in all docs from `https://andrew-d.github.io/python-multipart/` to `https://github.com/Kludex/python-multipart`. PR [#11239](https://github.com/tiangolo/fastapi/pull/11239) by [@joshjhans](https://github.com/joshjhans). ### Translations From 50597af7851e7b2d876be5f423eb4e57c102b8df Mon Sep 17 00:00:00 2001 From: Nan Wang <nan.wang@jina.ai> Date: Thu, 14 Mar 2024 03:21:21 +0800 Subject: [PATCH 042/846] =?UTF-8?q?=F0=9F=94=A5=20Remove=20Jina=20AI=20QA?= =?UTF-8?q?=20Bot=20from=20the=20docs=20(#11268)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/overrides/main.html | 32 -------------------------------- 1 file changed, 32 deletions(-) diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index eaab6b630..bc863d61a 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -73,35 +73,3 @@ </div> </div> {% endblock %} -{%- block scripts %} -{{ super() }} -<!-- DocsQA integration start --> -<script src="https://cdn.jsdelivr.net/npm/qabot@0.4"></script> -<script> - // This prevents the global search from interfering with qa-bot's internal text input. - document.addEventListener('DOMContentLoaded', () => { - document.querySelectorAll('qa-bot').forEach((x) => { - x.addEventListener('keydown', (event) => { - event.stopPropagation(); - }); - }); - }); -</script> -<qa-bot - server="https://tiangolo-fastapi.docsqa.jina.ai" - theme="infer" - title="FastAPI Bot" - description="FastAPI framework, high performance, easy to learn, fast to code, ready for production" - style="font-size: 0.8rem" -> - <template> - <dl> - <dt>You can ask questions about FastAPI. Try:</dt> - <dd>How do you deploy FastAPI?</dd> - <dd>What are type hints?</dd> - <dd>What is OpenAPI?</dd> - </dl> - </template> -</qa-bot> -<!-- DocsQA integration end --> -{%- endblock %} From 365c9382f6ba9c2f754099d1e14366adaf3e26d8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 13 Mar 2024 19:21:40 +0000 Subject: [PATCH 043/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 143f743f7..884e1e2b0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Internal +* 🔥 Remove Jina AI QA Bot from the docs. PR [#11268](https://github.com/tiangolo/fastapi/pull/11268) by [@nan-wang](https://github.com/nan-wang). * 🔧 Update sponsors, remove Jina, remove Powens, move TestDriven.io. PR [#11213](https://github.com/tiangolo/fastapi/pull/11213) by [@tiangolo](https://github.com/tiangolo). ## 0.110.0 From aff139ee90f50321fe90c2bf62814abcde3e9573 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 14 Mar 2024 12:40:05 +0100 Subject: [PATCH 044/846] =?UTF-8?q?=F0=9F=9B=A0=EF=B8=8F=20Improve=20Node.?= =?UTF-8?q?js=20script=20in=20docs=20to=20generate=20TypeScript=20clients?= =?UTF-8?q?=20(#11293)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs_src/generate_clients/tutorial004.js | 57 +++++++++++++----------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/docs_src/generate_clients/tutorial004.js b/docs_src/generate_clients/tutorial004.js index 18dc38267..fa222ba6c 100644 --- a/docs_src/generate_clients/tutorial004.js +++ b/docs_src/generate_clients/tutorial004.js @@ -1,29 +1,36 @@ -import * as fs from "fs"; +import * as fs from 'fs' -const filePath = "./openapi.json"; +async function modifyOpenAPIFile(filePath) { + try { + const data = await fs.promises.readFile(filePath) + const openapiContent = JSON.parse(data) -fs.readFile(filePath, (err, data) => { - const openapiContent = JSON.parse(data); - if (err) throw err; - - const paths = openapiContent.paths; - - Object.keys(paths).forEach((pathKey) => { - const pathData = paths[pathKey]; - Object.keys(pathData).forEach((method) => { - const operation = pathData[method]; - if (operation.tags && operation.tags.length > 0) { - const tag = operation.tags[0]; - const operationId = operation.operationId; - const toRemove = `${tag}-`; - if (operationId.startsWith(toRemove)) { - const newOperationId = operationId.substring(toRemove.length); - operation.operationId = newOperationId; + const paths = openapiContent.paths + for (const pathKey of Object.keys(paths)) { + const pathData = paths[pathKey] + for (const method of Object.keys(pathData)) { + const operation = pathData[method] + if (operation.tags && operation.tags.length > 0) { + const tag = operation.tags[0] + const operationId = operation.operationId + const toRemove = `${tag}-` + if (operationId.startsWith(toRemove)) { + const newOperationId = operationId.substring(toRemove.length) + operation.operationId = newOperationId + } } } - }); - }); - fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => { - if (err) throw err; - }); -}); + } + + await fs.promises.writeFile( + filePath, + JSON.stringify(openapiContent, null, 2), + ) + console.log('File successfully modified') + } catch (err) { + console.error('Error:', err) + } +} + +const filePath = './openapi.json' +modifyOpenAPIFile(filePath) From 1b105cb000dbf14157c38467ecc728447de49c8d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 14 Mar 2024 11:40:25 +0000 Subject: [PATCH 045/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 884e1e2b0..26927fc17 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🛠️ Improve Node.js script in docs to generate TypeScript clients. PR [#11293](https://github.com/tiangolo/fastapi/pull/11293) by [@alejsdev](https://github.com/alejsdev). * 📝 Update examples for tests to replace "inexistent" for "nonexistent". PR [#11220](https://github.com/tiangolo/fastapi/pull/11220) by [@Homesteady](https://github.com/Homesteady). * 📝 Update `python-multipart` GitHub link in all docs from `https://andrew-d.github.io/python-multipart/` to `https://github.com/Kludex/python-multipart`. PR [#11239](https://github.com/tiangolo/fastapi/pull/11239) by [@joshjhans](https://github.com/joshjhans). From 3c70b55042beff82d70d0ff8acc9dabbd95253b4 Mon Sep 17 00:00:00 2001 From: David Huser <david.huser@hslu.ch> Date: Thu, 14 Mar 2024 17:38:24 +0100 Subject: [PATCH 046/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20in?= =?UTF-8?q?=20docstrings=20(#11295)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/security/oauth2.py | 4 ++-- fastapi/security/open_id_connect_url.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index be3e18cd8..0606291b8 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -441,7 +441,7 @@ class OAuth2PasswordBearer(OAuth2): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. @@ -543,7 +543,7 @@ class OAuth2AuthorizationCodeBearer(OAuth2): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. diff --git a/fastapi/security/open_id_connect_url.py b/fastapi/security/open_id_connect_url.py index c612b475d..1d255877d 100644 --- a/fastapi/security/open_id_connect_url.py +++ b/fastapi/security/open_id_connect_url.py @@ -49,7 +49,7 @@ class OpenIdConnect(SecurityBase): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OpenID Connect authentication, it will automatically cancel the request and send the client an error. From 5e427ba9727e5855f66da6a929855a35606b62f2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 14 Mar 2024 16:38:46 +0000 Subject: [PATCH 047/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 26927fc17..6e5ebaabc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix typos in docstrings. PR [#11295](https://github.com/tiangolo/fastapi/pull/11295) by [@davidhuser](https://github.com/davidhuser). * 🛠️ Improve Node.js script in docs to generate TypeScript clients. PR [#11293](https://github.com/tiangolo/fastapi/pull/11293) by [@alejsdev](https://github.com/alejsdev). * 📝 Update examples for tests to replace "inexistent" for "nonexistent". PR [#11220](https://github.com/tiangolo/fastapi/pull/11220) by [@Homesteady](https://github.com/Homesteady). * 📝 Update `python-multipart` GitHub link in all docs from `https://andrew-d.github.io/python-multipart/` to `https://github.com/Kludex/python-multipart`. PR [#11239](https://github.com/tiangolo/fastapi/pull/11239) by [@joshjhans](https://github.com/joshjhans). From 7b21e027b3c9fc29ceedb46e6eff74edc3ebd50a Mon Sep 17 00:00:00 2001 From: Jack Lee <280147597@qq.com> Date: Fri, 15 Mar 2024 00:41:51 +0800 Subject: [PATCH 048/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/metadata.md`=20(#11286)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/metadata.md | 37 +++++++++++++------------------ 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 3e669bc72..09b106273 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -1,40 +1,35 @@ # 元数据和文档 URL +你可以在 FastAPI 应用程序中自定义多个元数据配置。 -你可以在 **FastAPI** 应用中自定义几个元数据配置。 +## API 元数据 -## 标题、描述和版本 +你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: -你可以设定: +| 参数 | 类型 | 描述 | +|------------|------|-------------| +| `title` | `str` | API 的标题。 | +| `summary` | `str` | API 的简短摘要。 <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。.</small> | +| `description` | `str` | API 的简短描述。可以使用Markdown。 | +| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | +| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | +| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。<details><summary><code>contact</code> 字段</summary><table><thead><tr><th>参数</th><th>Type</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>联系人/组织的识别名称。</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>指向联系信息的 URL。必须采用 URL 格式。</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。</td></tr></tbody></table></details> | +| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。<details><summary><code>license_info</code> 字段</summary><table><thead><tr><th>参数</th><th>类型</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>必须的</strong> (如果设置了<code>license_info</code>). 用于 API 的许可证名称。</td></tr><tr><td><code>identifier</code></td><td><code>str</code></td><td>一个API的<a href="https://spdx.org/licenses/" class="external-link" target="_blank">SPDX</a>许可证表达。 The <code>identifier</code> field is mutually exclusive of the <code>url</code> field. <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。</small></td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>用于 API 的许可证的 URL。必须采用 URL 格式。</td></tr></tbody></table></details> | -* **Title**:在 OpenAPI 和自动 API 文档用户界面中作为 API 的标题/名称使用。 -* **Description**:在 OpenAPI 和自动 API 文档用户界面中用作 API 的描述。 -* **Version**:API 版本,例如 `v2` 或者 `2.5.0`。 - * 如果你之前的应用程序版本也使用 OpenAPI 会很有用。 - -使用 `title`、`description` 和 `version` 来设置它们: +你可以按如下方式设置它们: ```Python hl_lines="4-6" {!../../../docs_src/metadata/tutorial001.py!} ``` +!!! tip + 您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 + 通过这样设置,自动 API 文档看起来会像: <img src="/img/tutorial/metadata/image01.png"> ## 标签元数据 -你也可以使用参数 `openapi_tags`,为用于分组路径操作的不同标签添加额外的元数据。 - -它接受一个列表,这个列表包含每个标签对应的一个字典。 - -每个字典可以包含: - -* `name`(**必要**):一个 `str`,它与*路径操作*和 `APIRouter` 中使用的 `tags` 参数有相同的标签名。 -* `description`:一个用于简短描述标签的 `str`。它支持 Markdown 并且会在文档用户界面中显示。 -* `externalDocs`:一个描述外部文档的 `dict`: - * `description`:用于简短描述外部文档的 `str`。 - * `url`(**必要**):外部文档的 URL `str`。 - ### 创建标签元数据 让我们在带有标签的示例中为 `users` 和 `items` 试一下。 From d928140cde8a31a9376733de8281a2c27af40276 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 14 Mar 2024 16:42:14 +0000 Subject: [PATCH 049/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6e5ebaabc..b57aa0dab 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/metadata.md`. PR [#11286](https://github.com/tiangolo/fastapi/pull/11286) by [@jackleeio](https://github.com/jackleeio). * 🌐 Update Chinese translation for `docs/zh/docs/contributing.md`. PR [#10887](https://github.com/tiangolo/fastapi/pull/10887) by [@Aruelius](https://github.com/Aruelius). * 🌐 Add Azerbaijani translation for `docs/az/docs/fastapi-people.md`. PR [#11195](https://github.com/tiangolo/fastapi/pull/11195) by [@vusallyv](https://github.com/vusallyv). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/index.md`. PR [#11223](https://github.com/tiangolo/fastapi/pull/11223) by [@kohiry](https://github.com/kohiry). From 5df9f30b933fed50d1616e7f8b9d56b76bb0e9ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 14 Mar 2024 17:43:24 +0100 Subject: [PATCH 050/846] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20(#11228)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions <github-actions@github.com> --- docs/en/data/github_sponsors.yml | 109 ++++++++++------------ docs/en/data/people.yml | 154 +++++++++++++++++-------------- 2 files changed, 133 insertions(+), 130 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 259a67f8f..fb690708f 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -26,18 +26,12 @@ sponsors: - - login: ObliviousAI avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI - - login: nihpo - avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 - url: https://github.com/nihpo - - login: databento avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 url: https://github.com/databento - login: svix avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4 url: https://github.com/svix - - login: VincentParedes - avatarUrl: https://avatars.githubusercontent.com/u/103889729?v=4 - url: https://github.com/VincentParedes - login: deepset-ai avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4 url: https://github.com/deepset-ai @@ -59,16 +53,10 @@ sponsors: - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 url: https://github.com/BoostryJP - - login: jina-ai - avatarUrl: https://avatars.githubusercontent.com/u/60539444?v=4 - url: https://github.com/jina-ai - login: acsone avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4 url: https://github.com/acsone -- - login: FOSS-Community - avatarUrl: https://avatars.githubusercontent.com/u/103304813?v=4 - url: https://github.com/FOSS-Community - - login: Trivie +- - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie - - login: americanair @@ -89,6 +77,9 @@ sponsors: - login: AccentDesign avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4 url: https://github.com/AccentDesign + - login: mangualero + avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4 + url: https://github.com/mangualero - login: birkjernstrom avatarUrl: https://avatars.githubusercontent.com/u/281715?u=4be14b43f76b4bd497b1941309bb390250b405e6&v=4 url: https://github.com/birkjernstrom @@ -110,12 +101,18 @@ sponsors: - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder - login: ehaca avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 url: https://github.com/ehaca - login: timlrx avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 url: https://github.com/timlrx + - login: mattmalcher + avatarUrl: https://avatars.githubusercontent.com/u/31312775?v=4 + url: https://github.com/mattmalcher - login: Leay15 avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 url: https://github.com/Leay15 @@ -125,12 +122,6 @@ sponsors: - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure - - login: RafaelWO - avatarUrl: https://avatars.githubusercontent.com/u/38643099?u=56c676f024667ee416dc8b1cdf0c2611b9dc994f&v=4 - url: https://github.com/RafaelWO - - login: drcat101 - avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 - url: https://github.com/drcat101 - login: jsoques avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 url: https://github.com/jsoques @@ -155,6 +146,12 @@ sponsors: - login: Filimoa avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 url: https://github.com/Filimoa + - login: b-rad-c + avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 + url: https://github.com/b-rad-c + - login: patsatsia + avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 + url: https://github.com/patsatsia - login: anthonycepeda avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 url: https://github.com/anthonycepeda @@ -188,18 +185,18 @@ sponsors: - login: yakkonaut avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 url: https://github.com/yakkonaut - - login: patsatsia - avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 - url: https://github.com/patsatsia - - login: koconder - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 - url: https://github.com/koconder + - login: tcsmith + avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 + url: https://github.com/tcsmith - login: mickaelandrieu avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 url: https://github.com/mickaelandrieu - login: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 + - login: nihpo + avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 + url: https://github.com/nihpo - login: knallgelb avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 url: https://github.com/knallgelb @@ -212,12 +209,6 @@ sponsors: - login: dblackrun avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 url: https://github.com/dblackrun - - login: zsinx6 - avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 - url: https://github.com/zsinx6 - - login: kennywakeland - avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 - url: https://github.com/kennywakeland - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden @@ -242,12 +233,9 @@ sponsors: - login: mintuhouse avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 url: https://github.com/mintuhouse - - login: tcsmith - avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 - url: https://github.com/tcsmith - - login: aacayaco - avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 - url: https://github.com/aacayaco + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw - login: Rehket avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 url: https://github.com/Rehket @@ -257,12 +245,21 @@ sponsors: - login: TrevorBenson avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=afdd1766fdb79e04e59094cc6a54cd011ee7f686&v=4 url: https://github.com/TrevorBenson - - login: pkwarts - avatarUrl: https://avatars.githubusercontent.com/u/10128250?u=151b92c2be8baff34f366cfc7ecf2800867f5e9f&v=4 - url: https://github.com/pkwarts - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow + - login: drcat101 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 + url: https://github.com/drcat101 + - login: zsinx6 + avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 + url: https://github.com/zsinx6 + - login: kennywakeland + avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 + url: https://github.com/kennywakeland + - login: aacayaco + avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 + url: https://github.com/aacayaco - login: anomaly avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly @@ -287,15 +284,9 @@ sponsors: - login: Yaleesa avatarUrl: https://avatars.githubusercontent.com/u/6135475?v=4 url: https://github.com/Yaleesa - - login: iwpnd - avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=f4ef76a069858f0f37c8737cada5c2cfa9c538b9&v=4 - url: https://github.com/iwpnd - login: FernandoCelmer avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - - login: getsentry avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 url: https://github.com/getsentry @@ -347,9 +338,6 @@ sponsors: - login: pers0n4 avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 url: https://github.com/pers0n4 - - login: kxzk - avatarUrl: https://avatars.githubusercontent.com/u/25046261?u=e185e58080090f9e678192cd214a14b14a2b232b&v=4 - url: https://github.com/kxzk - login: SebTota avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 url: https://github.com/SebTota @@ -377,6 +365,9 @@ sponsors: - login: tahmarrrr23 avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 url: https://github.com/tahmarrrr23 + - login: lukzmu + avatarUrl: https://avatars.githubusercontent.com/u/155924127?u=2e52e40b3134bef370b52bf2e40a524f307c2a05&v=4 + url: https://github.com/lukzmu - login: kristiangronberg avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 url: https://github.com/kristiangronberg @@ -386,6 +377,12 @@ sponsors: - login: arrrrrmin avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=36a3880a6eb29309c19e6cadbb173bafbe91deb1&v=4 url: https://github.com/arrrrrmin + - login: rbtrsv + avatarUrl: https://avatars.githubusercontent.com/u/43938206?u=09955f324da271485a7edaf9241f449e88a1388a&v=4 + url: https://github.com/rbtrsv + - login: mobyw + avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 + url: https://github.com/mobyw - login: ArtyomVancyan avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan @@ -434,6 +431,9 @@ sponsors: - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 url: https://github.com/securancy + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke @@ -452,9 +452,6 @@ sponsors: - login: moonape1226 avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 url: https://github.com/moonape1226 - - login: albertkun - avatarUrl: https://avatars.githubusercontent.com/u/8574425?u=aad2a9674273c9275fe414d99269b7418d144089&v=4 - url: https://github.com/albertkun - login: xncbf avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 url: https://github.com/xncbf @@ -482,9 +479,6 @@ sponsors: - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa - - login: gowikel - avatarUrl: https://avatars.githubusercontent.com/u/4339072?u=0e325ffcc539c38f89d9aa876bd87f9ec06ce0ee&v=4 - url: https://github.com/gowikel - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -506,9 +500,6 @@ sponsors: - - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline - - login: Cxx-mlr - avatarUrl: https://avatars.githubusercontent.com/u/37257545?u=7f6296d7bfd4c58e2918576d79e7d2250987e6a4&v=4 - url: https://github.com/Cxx-mlr - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu @@ -519,7 +510,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 url: https://github.com/Patechoc - login: ssbarnea - avatarUrl: https://avatars.githubusercontent.com/u/102495?u=b4bf6818deefe59952ac22fec6ed8c76de1b8f7c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c2efbf6fea2737e21dfc6b1113c4edc9644e9eaa&v=4 url: https://github.com/ssbarnea - login: yuawn avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index b21d989f2..5e371739b 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,18 +1,22 @@ maintainers: - login: tiangolo - answers: 1874 - prs: 544 + answers: 1875 + prs: 549 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 572 + count: 589 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu count: 241 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu +- login: jgould22 + count: 227 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: Mause count: 220 avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4 @@ -21,10 +25,6 @@ experts: count: 217 avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 url: https://github.com/ycd -- login: jgould22 - count: 212 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: JarroVGIT count: 193 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 @@ -54,9 +54,13 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik - login: falkben - count: 57 + count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben +- login: n8sty + count: 51 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: sm-Fifteen count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 @@ -69,10 +73,10 @@ experts: count: 46 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: insomnes +- login: JavierSanchezCastro count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 - url: https://github.com/insomnes + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: adriangb count: 45 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 @@ -81,14 +85,14 @@ experts: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 url: https://github.com/Dustyposa +- login: insomnes + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 + url: https://github.com/insomnes - login: odiseo0 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 url: https://github.com/odiseo0 -- login: n8sty - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 @@ -97,10 +101,6 @@ experts: count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin -- login: JavierSanchezCastro - count: 39 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: chbndrhnns count: 38 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 @@ -145,6 +145,14 @@ experts: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf +- login: ebottos94 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 +- login: chrisK824 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: chris-allnutt count: 20 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 @@ -153,16 +161,8 @@ experts: count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 url: https://github.com/nsidnev -- login: chrisK824 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: ebottos94 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 - login: hasansezertasan - count: 18 + count: 19 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: retnikt @@ -198,19 +198,35 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 url: https://github.com/jonatasoli last_month_active: +- login: jgould22 + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: Kludex - count: 20 + count: 14 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex +- login: n8sty + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: JavierSanchezCastro - count: 6 + count: 5 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: jgould22 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 +- login: ahmedabdou14 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: GodMoonGoodman + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman top_contributors: +- login: nilslindemann + count: 29 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann - login: jaystone776 count: 27 avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 @@ -227,10 +243,6 @@ top_contributors: count: 22 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: nilslindemann - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 - url: https://github.com/nilslindemann - login: SwftAlpc count: 21 avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 @@ -251,6 +263,10 @@ top_contributors: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 url: https://github.com/mariacamilagl +- login: hasansezertasan + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: Smlep count: 11 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 @@ -263,10 +279,10 @@ top_contributors: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders -- login: hasansezertasan +- login: KaniKim count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=3e00ea6ceb45d252b93b2ec515e73c63baa06ff4&v=4 + url: https://github.com/KaniKim - login: xzmeng count: 9 avatarUrl: https://avatars.githubusercontent.com/u/40202897?v=4 @@ -279,6 +295,10 @@ top_contributors: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 url: https://github.com/rjNemo +- login: pablocm83 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 + url: https://github.com/pablocm83 - login: RunningIkkyu count: 7 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 @@ -295,10 +315,6 @@ top_contributors: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 url: https://github.com/batlopes -- login: pablocm83 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 - url: https://github.com/pablocm83 - login: wshayes count: 5 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 @@ -323,10 +339,10 @@ top_contributors: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 url: https://github.com/tamtam-fitness -- login: KaniKim +- login: alejsdev count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=4368c4286cc0a122b746f34d4484cef3eed0611f&v=4 - url: https://github.com/KaniKim + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + url: https://github.com/alejsdev - login: jekirl count: 4 avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 @@ -375,13 +391,9 @@ top_contributors: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 url: https://github.com/ivan-abc -- login: alejsdev - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 - url: https://github.com/alejsdev top_reviewers: - login: Kludex - count: 147 + count: 154 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan @@ -389,7 +401,7 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 url: https://github.com/BilalAlpaslan - login: yezz123 - count: 82 + count: 84 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 - login: iudeen @@ -421,9 +433,13 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4 url: https://github.com/cikay - login: hasansezertasan - count: 37 + count: 41 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan +- login: alejsdev + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + url: https://github.com/alejsdev - login: JarroVGIT count: 34 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 @@ -432,10 +448,6 @@ top_reviewers: count: 33 avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=b2ea249c6b41ddf98679c8d110d0f67d4a3ebf93&v=4 url: https://github.com/AdrianDeAnda -- login: alejsdev - count: 32 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 - url: https://github.com/alejsdev - login: ArcLightSlavik count: 31 avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 @@ -464,14 +476,14 @@ top_reviewers: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu +- login: nilslindemann + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann - login: hard-coders count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders -- login: nilslindemann - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 - url: https://github.com/nilslindemann - login: rjNemo count: 21 avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 @@ -524,6 +536,10 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 +- login: YuriiMotov + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 @@ -560,6 +576,10 @@ top_reviewers: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv +- login: dpinezich + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 + url: https://github.com/dpinezich - login: mariacamilagl count: 10 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 @@ -568,11 +588,3 @@ top_reviewers: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv -- login: Attsun1031 - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 - url: https://github.com/Attsun1031 -- login: maoyibo - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 - url: https://github.com/maoyibo From d0ac56694e449af8a5196dc7ba7745f148371cf8 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Thu, 14 Mar 2024 17:44:05 +0100 Subject: [PATCH 051/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/extending-openapi.md`=20(#10794?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/extending-openapi.md | 87 ++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 docs/de/docs/how-to/extending-openapi.md diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md new file mode 100644 index 000000000..2fbfa13e5 --- /dev/null +++ b/docs/de/docs/how-to/extending-openapi.md @@ -0,0 +1,87 @@ +# OpenAPI erweitern + +In einigen Fällen müssen Sie möglicherweise das generierte OpenAPI-Schema ändern. + +In diesem Abschnitt erfahren Sie, wie. + +## Der normale Vorgang + +Der normale (Standard-)Prozess ist wie folgt. + +Eine `FastAPI`-Anwendung (-Instanz) verfügt über eine `.openapi()`-Methode, von der erwartet wird, dass sie das OpenAPI-Schema zurückgibt. + +Als Teil der Erstellung des Anwendungsobjekts wird eine *Pfadoperation* für `/openapi.json` (oder welcher Wert für den Parameter `openapi_url` gesetzt wurde) registriert. + +Diese gibt lediglich eine JSON-Response zurück, mit dem Ergebnis der Methode `.openapi()` der Anwendung. + +Standardmäßig überprüft die Methode `.openapi()` die Eigenschaft `.openapi_schema`, um zu sehen, ob diese Inhalt hat, und gibt diesen zurück. + +Ist das nicht der Fall, wird der Inhalt mithilfe der Hilfsfunktion unter `fastapi.openapi.utils.get_openapi` generiert. + +Und diese Funktion `get_openapi()` erhält als Parameter: + +* `title`: Der OpenAPI-Titel, der in der Dokumentation angezeigt wird. +* `version`: Die Version Ihrer API, z. B. `2.5.0`. +* `openapi_version`: Die Version der verwendeten OpenAPI-Spezifikation. Standardmäßig die neueste Version: `3.1.0`. +* `summary`: Eine kurze Zusammenfassung der API. +* `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt. +* `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`. + +!!! info + Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. + +## Überschreiben der Standardeinstellungen + +Mithilfe der oben genannten Informationen können Sie dieselbe Hilfsfunktion verwenden, um das OpenAPI-Schema zu generieren und jeden benötigten Teil zu überschreiben. + +Fügen wir beispielsweise <a href="https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo" class="external-link" target="_blank">ReDocs OpenAPI-Erweiterung</a> zum Einbinden eines benutzerdefinierten Logos hinzu. + +### Normales **FastAPI** + +Schreiben Sie zunächst wie gewohnt Ihre ganze **FastAPI**-Anwendung: + +```Python hl_lines="1 4 7-9" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Das OpenAPI-Schema generieren + +Verwenden Sie dann dieselbe Hilfsfunktion, um das OpenAPI-Schema innerhalb einer `custom_openapi()`-Funktion zu generieren: + +```Python hl_lines="2 15-21" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Das OpenAPI-Schema ändern + +Jetzt können Sie die ReDoc-Erweiterung hinzufügen und dem `info`-„Objekt“ im OpenAPI-Schema ein benutzerdefiniertes `x-logo` hinzufügen: + +```Python hl_lines="22-24" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Zwischenspeichern des OpenAPI-Schemas + +Sie können die Eigenschaft `.openapi_schema` als „Cache“ verwenden, um Ihr generiertes Schema zu speichern. + +Auf diese Weise muss Ihre Anwendung das Schema nicht jedes Mal generieren, wenn ein Benutzer Ihre API-Dokumentation öffnet. + +Es wird nur einmal generiert und dann wird dasselbe zwischengespeicherte Schema für die nächsten Requests verwendet. + +```Python hl_lines="13-14 25-26" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Die Methode überschreiben + +Jetzt können Sie die Methode `.openapi()` durch Ihre neue Funktion ersetzen. + +```Python hl_lines="29" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Testen + +Sobald Sie auf <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a> gehen, werden Sie sehen, dass Ihr benutzerdefiniertes Logo verwendet wird (in diesem Beispiel das Logo von **FastAPI**): + +<img src="/img/tutorial/extending-openapi/image01.png"> From b56a7802f9cafee49c01c4e1775db13aa310de14 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 14 Mar 2024 16:44:31 +0000 Subject: [PATCH 052/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b57aa0dab..349c7de3c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -25,6 +25,7 @@ hide: ### Internal +* 👥 Update FastAPI People. PR [#11228](https://github.com/tiangolo/fastapi/pull/11228) by [@tiangolo](https://github.com/tiangolo). * 🔥 Remove Jina AI QA Bot from the docs. PR [#11268](https://github.com/tiangolo/fastapi/pull/11268) by [@nan-wang](https://github.com/nan-wang). * 🔧 Update sponsors, remove Jina, remove Powens, move TestDriven.io. PR [#11213](https://github.com/tiangolo/fastapi/pull/11213) by [@tiangolo](https://github.com/tiangolo). From 870d50ac65dd7e64f69f5e9a99e394eef5d908b7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 14 Mar 2024 16:45:24 +0000 Subject: [PATCH 053/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 349c7de3c..0df156dcc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/extending-openapi.md`. PR [#10794](https://github.com/tiangolo/fastapi/pull/10794) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/metadata.md`. PR [#11286](https://github.com/tiangolo/fastapi/pull/11286) by [@jackleeio](https://github.com/jackleeio). * 🌐 Update Chinese translation for `docs/zh/docs/contributing.md`. PR [#10887](https://github.com/tiangolo/fastapi/pull/10887) by [@Aruelius](https://github.com/Aruelius). * 🌐 Add Azerbaijani translation for `docs/az/docs/fastapi-people.md`. PR [#11195](https://github.com/tiangolo/fastapi/pull/11195) by [@vusallyv](https://github.com/vusallyv). From e11e5d20e74f1556866c5bd627d5cc158a9018db Mon Sep 17 00:00:00 2001 From: Elliott Larsen <86161304+ElliottLarsen@users.noreply.github.com> Date: Thu, 14 Mar 2024 11:04:00 -0600 Subject: [PATCH 054/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/index.md`=20(#9613)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/index.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 docs/ko/docs/advanced/index.md diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md new file mode 100644 index 000000000..5e23e2809 --- /dev/null +++ b/docs/ko/docs/advanced/index.md @@ -0,0 +1,24 @@ +# 심화 사용자 안내서 - 도입부 + +## 추가 기능 + +메인 [자습서 - 사용자 안내서](../tutorial/){.internal-link target=_blank}는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다. + +이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. + +!!! tip "팁" + 다음 장들이 **반드시 "심화"**인 것은 아닙니다. + + 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. + +## 자습서를 먼저 읽으십시오 + +여러분은 메인 [자습서 - 사용자 안내서](../tutorial/){.internal-link target=_blank}의 지식으로 **FastAPI**의 대부분의 기능을 사용하실 수 있습니다. + +이어지는 장들은 여러분이 메인 자습서 - 사용자 안내서를 이미 읽으셨으며 주요 아이디어를 알고 계신다고 가정합니다. + +## TestDriven.io 강좌 + +여러분이 문서의 이 부분을 보완하시기 위해 심화-기초 강좌 수강을 희망하신다면 다음을 참고 하시기를 바랍니다: **TestDriven.io**의 <a href="https://testdriven.io/courses/tdd-fastapi/" class="external-link" target="_blank">FastAPI와 Docker를 사용한 테스트 주도 개발</a>. + +그들은 현재 전체 수익의 10퍼센트를 **FastAPI** 개발에 기부하고 있습니다. 🎉 😄 From 7fa85d5ebd150222f2bf43ca154420c81de88f41 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 14 Mar 2024 17:04:25 +0000 Subject: [PATCH 055/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0df156dcc..c81289de8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/index.md`. PR [#9613](https://github.com/tiangolo/fastapi/pull/9613) by [@ElliottLarsen](https://github.com/ElliottLarsen). * 🌐 Add German translation for `docs/de/docs/how-to/extending-openapi.md`. PR [#10794](https://github.com/tiangolo/fastapi/pull/10794) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/metadata.md`. PR [#11286](https://github.com/tiangolo/fastapi/pull/11286) by [@jackleeio](https://github.com/jackleeio). * 🌐 Update Chinese translation for `docs/zh/docs/contributing.md`. PR [#10887](https://github.com/tiangolo/fastapi/pull/10887) by [@Aruelius](https://github.com/Aruelius). From f0becc4452905e3ae7ac7aed925e5e14d1af4ec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 16 Mar 2024 18:54:24 -0500 Subject: [PATCH 056/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20computi?= =?UTF-8?q?ng=20FastAPI=20People,=20include=203=20months,=206=20months,=20?= =?UTF-8?q?1=20year,=20based=20on=20comment=20date,=20not=20discussion=20d?= =?UTF-8?q?ate=20(#11304)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/people/app/main.py | 297 ++++------ docs/az/docs/fastapi-people.md | 8 +- docs/em/docs/fastapi-people.md | 8 +- docs/en/data/people.yml | 912 +++++++++++++++++++++++++++-- docs/en/docs/fastapi-people.md | 93 ++- docs/fr/docs/fastapi-people.md | 8 +- docs/ja/docs/fastapi-people.md | 8 +- docs/pt/docs/fastapi-people.md | 8 +- docs/ru/docs/fastapi-people.md | 8 +- docs/tr/docs/fastapi-people.md | 8 +- docs/uk/docs/fastapi-people.md | 8 +- docs/zh/docs/fastapi-people.md | 8 +- 12 files changed, 1093 insertions(+), 281 deletions(-) diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index cb6b229e8..657f2bf5e 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -58,38 +58,6 @@ query Q($after: String, $category_id: ID) { } """ -issues_query = """ -query Q($after: String) { - repository(name: "fastapi", owner: "tiangolo") { - issues(first: 100, after: $after) { - edges { - cursor - node { - number - author { - login - avatarUrl - url - } - title - createdAt - state - comments(first: 100) { - nodes { - createdAt - author { - login - avatarUrl - url - } - } - } - } - } - } - } -} -""" prs_query = """ query Q($after: String) { @@ -176,7 +144,7 @@ class Author(BaseModel): url: str -# Issues and Discussions +# Discussions class CommentsNode(BaseModel): @@ -200,15 +168,6 @@ class DiscussionsComments(BaseModel): nodes: List[DiscussionsCommentsNode] -class IssuesNode(BaseModel): - number: int - author: Union[Author, None] = None - title: str - createdAt: datetime - state: str - comments: Comments - - class DiscussionsNode(BaseModel): number: int author: Union[Author, None] = None @@ -217,44 +176,23 @@ class DiscussionsNode(BaseModel): comments: DiscussionsComments -class IssuesEdge(BaseModel): - cursor: str - node: IssuesNode - - class DiscussionsEdge(BaseModel): cursor: str node: DiscussionsNode -class Issues(BaseModel): - edges: List[IssuesEdge] - - class Discussions(BaseModel): edges: List[DiscussionsEdge] -class IssuesRepository(BaseModel): - issues: Issues - - class DiscussionsRepository(BaseModel): discussions: Discussions -class IssuesResponseData(BaseModel): - repository: IssuesRepository - - class DiscussionsResponseData(BaseModel): repository: DiscussionsRepository -class IssuesResponse(BaseModel): - data: IssuesResponseData - - class DiscussionsResponse(BaseModel): data: DiscussionsResponseData @@ -389,12 +327,6 @@ def get_graphql_response( return data -def get_graphql_issue_edges(*, settings: Settings, after: Union[str, None] = None): - data = get_graphql_response(settings=settings, query=issues_query, after=after) - graphql_response = IssuesResponse.model_validate(data) - return graphql_response.data.repository.issues.edges - - def get_graphql_question_discussion_edges( *, settings: Settings, @@ -422,43 +354,16 @@ def get_graphql_sponsor_edges(*, settings: Settings, after: Union[str, None] = N return graphql_response.data.user.sponsorshipsAsMaintainer.edges -def get_issues_experts(settings: Settings): - issue_nodes: List[IssuesNode] = [] - issue_edges = get_graphql_issue_edges(settings=settings) +class DiscussionExpertsResults(BaseModel): + commenters: Counter + last_month_commenters: Counter + three_months_commenters: Counter + six_months_commenters: Counter + one_year_commenters: Counter + authors: Dict[str, Author] - while issue_edges: - for edge in issue_edges: - issue_nodes.append(edge.node) - last_edge = issue_edges[-1] - issue_edges = get_graphql_issue_edges(settings=settings, after=last_edge.cursor) - commentors = Counter() - last_month_commentors = Counter() - authors: Dict[str, Author] = {} - - now = datetime.now(tz=timezone.utc) - one_month_ago = now - timedelta(days=30) - - for issue in issue_nodes: - issue_author_name = None - if issue.author: - authors[issue.author.login] = issue.author - issue_author_name = issue.author.login - issue_commentors = set() - for comment in issue.comments.nodes: - if comment.author: - authors[comment.author.login] = comment.author - if comment.author.login != issue_author_name: - issue_commentors.add(comment.author.login) - for author_name in issue_commentors: - commentors[author_name] += 1 - if issue.createdAt > one_month_ago: - last_month_commentors[author_name] += 1 - - return commentors, last_month_commentors, authors - - -def get_discussions_experts(settings: Settings): +def get_discussion_nodes(settings: Settings) -> List[DiscussionsNode]: discussion_nodes: List[DiscussionsNode] = [] discussion_edges = get_graphql_question_discussion_edges(settings=settings) @@ -469,61 +374,73 @@ def get_discussions_experts(settings: Settings): discussion_edges = get_graphql_question_discussion_edges( settings=settings, after=last_edge.cursor ) + return discussion_nodes + - commentors = Counter() - last_month_commentors = Counter() +def get_discussions_experts( + discussion_nodes: List[DiscussionsNode] +) -> DiscussionExpertsResults: + commenters = Counter() + last_month_commenters = Counter() + three_months_commenters = Counter() + six_months_commenters = Counter() + one_year_commenters = Counter() authors: Dict[str, Author] = {} now = datetime.now(tz=timezone.utc) one_month_ago = now - timedelta(days=30) + three_months_ago = now - timedelta(days=90) + six_months_ago = now - timedelta(days=180) + one_year_ago = now - timedelta(days=365) for discussion in discussion_nodes: discussion_author_name = None if discussion.author: authors[discussion.author.login] = discussion.author discussion_author_name = discussion.author.login - discussion_commentors = set() + discussion_commentors: dict[str, datetime] = {} for comment in discussion.comments.nodes: if comment.author: authors[comment.author.login] = comment.author if comment.author.login != discussion_author_name: - discussion_commentors.add(comment.author.login) + author_time = discussion_commentors.get( + comment.author.login, comment.createdAt + ) + discussion_commentors[comment.author.login] = max( + author_time, comment.createdAt + ) for reply in comment.replies.nodes: if reply.author: authors[reply.author.login] = reply.author if reply.author.login != discussion_author_name: - discussion_commentors.add(reply.author.login) - for author_name in discussion_commentors: - commentors[author_name] += 1 - if discussion.createdAt > one_month_ago: - last_month_commentors[author_name] += 1 - return commentors, last_month_commentors, authors - - -def get_experts(settings: Settings): - # Migrated to only use GitHub Discussions - # ( - # issues_commentors, - # issues_last_month_commentors, - # issues_authors, - # ) = get_issues_experts(settings=settings) - ( - discussions_commentors, - discussions_last_month_commentors, - discussions_authors, - ) = get_discussions_experts(settings=settings) - # commentors = issues_commentors + discussions_commentors - commentors = discussions_commentors - # last_month_commentors = ( - # issues_last_month_commentors + discussions_last_month_commentors - # ) - last_month_commentors = discussions_last_month_commentors - # authors = {**issues_authors, **discussions_authors} - authors = {**discussions_authors} - return commentors, last_month_commentors, authors - - -def get_contributors(settings: Settings): + author_time = discussion_commentors.get( + reply.author.login, reply.createdAt + ) + discussion_commentors[reply.author.login] = max( + author_time, reply.createdAt + ) + for author_name, author_time in discussion_commentors.items(): + commenters[author_name] += 1 + if author_time > one_month_ago: + last_month_commenters[author_name] += 1 + if author_time > three_months_ago: + three_months_commenters[author_name] += 1 + if author_time > six_months_ago: + six_months_commenters[author_name] += 1 + if author_time > one_year_ago: + one_year_commenters[author_name] += 1 + discussion_experts_results = DiscussionExpertsResults( + authors=authors, + commenters=commenters, + last_month_commenters=last_month_commenters, + three_months_commenters=three_months_commenters, + six_months_commenters=six_months_commenters, + one_year_commenters=one_year_commenters, + ) + return discussion_experts_results + + +def get_pr_nodes(settings: Settings) -> List[PullRequestNode]: pr_nodes: List[PullRequestNode] = [] pr_edges = get_graphql_pr_edges(settings=settings) @@ -532,10 +449,22 @@ def get_contributors(settings: Settings): pr_nodes.append(edge.node) last_edge = pr_edges[-1] pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor) + return pr_nodes + +class ContributorsResults(BaseModel): + contributors: Counter + commenters: Counter + reviewers: Counter + translation_reviewers: Counter + authors: Dict[str, Author] + + +def get_contributors(pr_nodes: List[PullRequestNode]) -> ContributorsResults: contributors = Counter() - commentors = Counter() + commenters = Counter() reviewers = Counter() + translation_reviewers = Counter() authors: Dict[str, Author] = {} for pr in pr_nodes: @@ -552,16 +481,26 @@ def get_contributors(settings: Settings): continue pr_commentors.add(comment.author.login) for author_name in pr_commentors: - commentors[author_name] += 1 + commenters[author_name] += 1 for review in pr.reviews.nodes: if review.author: authors[review.author.login] = review.author pr_reviewers.add(review.author.login) + for label in pr.labels.nodes: + if label.name == "lang-all": + translation_reviewers[review.author.login] += 1 + break for reviewer in pr_reviewers: reviewers[reviewer] += 1 if pr.state == "MERGED" and pr.author: contributors[pr.author.login] += 1 - return contributors, commentors, reviewers, authors + return ContributorsResults( + contributors=contributors, + commenters=commenters, + reviewers=reviewers, + translation_reviewers=translation_reviewers, + authors=authors, + ) def get_individual_sponsors(settings: Settings): @@ -585,19 +524,19 @@ def get_individual_sponsors(settings: Settings): def get_top_users( *, counter: Counter, - min_count: int, authors: Dict[str, Author], skip_users: Container[str], + min_count: int = 2, ): users = [] - for commentor, count in counter.most_common(50): - if commentor in skip_users: + for commenter, count in counter.most_common(50): + if commenter in skip_users: continue if count >= min_count: - author = authors[commentor] + author = authors[commenter] users.append( { - "login": commentor, + "login": commenter, "count": count, "avatarUrl": author.avatarUrl, "url": author.url, @@ -612,13 +551,11 @@ if __name__ == "__main__": logging.info(f"Using config: {settings.model_dump_json()}") g = Github(settings.input_token.get_secret_value()) repo = g.get_repo(settings.github_repository) - question_commentors, question_last_month_commentors, question_authors = get_experts( - settings=settings - ) - contributors, pr_commentors, reviewers, pr_authors = get_contributors( - settings=settings - ) - authors = {**question_authors, **pr_authors} + discussion_nodes = get_discussion_nodes(settings=settings) + experts_results = get_discussions_experts(discussion_nodes=discussion_nodes) + pr_nodes = get_pr_nodes(settings=settings) + contributors_results = get_contributors(pr_nodes=pr_nodes) + authors = {**experts_results.authors, **contributors_results.authors} maintainers_logins = {"tiangolo"} bot_names = {"codecov", "github-actions", "pre-commit-ci", "dependabot"} maintainers = [] @@ -627,39 +564,51 @@ if __name__ == "__main__": maintainers.append( { "login": login, - "answers": question_commentors[login], - "prs": contributors[login], + "answers": experts_results.commenters[login], + "prs": contributors_results.contributors[login], "avatarUrl": user.avatarUrl, "url": user.url, } ) - min_count_expert = 10 - min_count_last_month = 3 - min_count_contributor = 4 - min_count_reviewer = 4 skip_users = maintainers_logins | bot_names experts = get_top_users( - counter=question_commentors, - min_count=min_count_expert, + counter=experts_results.commenters, authors=authors, skip_users=skip_users, ) - last_month_active = get_top_users( - counter=question_last_month_commentors, - min_count=min_count_last_month, + last_month_experts = get_top_users( + counter=experts_results.last_month_commenters, + authors=authors, + skip_users=skip_users, + ) + three_months_experts = get_top_users( + counter=experts_results.three_months_commenters, + authors=authors, + skip_users=skip_users, + ) + six_months_experts = get_top_users( + counter=experts_results.six_months_commenters, + authors=authors, + skip_users=skip_users, + ) + one_year_experts = get_top_users( + counter=experts_results.one_year_commenters, authors=authors, skip_users=skip_users, ) top_contributors = get_top_users( - counter=contributors, - min_count=min_count_contributor, + counter=contributors_results.contributors, authors=authors, skip_users=skip_users, ) top_reviewers = get_top_users( - counter=reviewers, - min_count=min_count_reviewer, + counter=contributors_results.reviewers, + authors=authors, + skip_users=skip_users, + ) + top_translations_reviewers = get_top_users( + counter=contributors_results.translation_reviewers, authors=authors, skip_users=skip_users, ) @@ -679,13 +628,19 @@ if __name__ == "__main__": people = { "maintainers": maintainers, "experts": experts, - "last_month_active": last_month_active, + "last_month_experts": last_month_experts, + "three_months_experts": three_months_experts, + "six_months_experts": six_months_experts, + "one_year_experts": one_year_experts, "top_contributors": top_contributors, "top_reviewers": top_reviewers, + "top_translations_reviewers": top_translations_reviewers, } github_sponsors = { "sponsors": sponsors, } + # For local development + # people_path = Path("../../../../docs/en/data/people.yml") people_path = Path("./docs/en/data/people.yml") github_sponsors_path = Path("./docs/en/data/github_sponsors.yml") people_old_content = people_path.read_text(encoding="utf-8") diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md index 5df183888..2ca8e109e 100644 --- a/docs/az/docs/fastapi-people.md +++ b/docs/az/docs/fastapi-people.md @@ -47,7 +47,7 @@ Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fast {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div> {% endfor %} @@ -65,7 +65,7 @@ Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut edi {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div> {% endfor %} @@ -83,7 +83,7 @@ Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstə {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Request-lər: {{ user.count }}</div></div> {% endfor %} @@ -107,7 +107,7 @@ Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Rəylər: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md index dc94d80da..ec1d4c47c 100644 --- a/docs/em/docs/fastapi-people.md +++ b/docs/em/docs/fastapi-people.md @@ -40,7 +40,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔ 📨: {{ user.count }}</div></div> {% endfor %} @@ -58,7 +58,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔ 📨: {{ user.count }}</div></div> {% endfor %} @@ -76,7 +76,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">🚲 📨: {{ user.count }}</div></div> {% endfor %} @@ -100,7 +100,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">📄: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 5e371739b..710c650fd 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo - answers: 1875 - prs: 549 + answers: 1878 + prs: 550 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 589 + count: 596 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -14,7 +14,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: jgould22 - count: 227 + count: 232 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: Mause @@ -57,8 +57,12 @@ experts: count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben +- login: JavierSanchezCastro + count: 52 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: n8sty - count: 51 + count: 52 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: sm-Fifteen @@ -70,33 +74,29 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 url: https://github.com/yinziyan1206 - login: acidjunk - count: 46 + count: 47 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: JavierSanchezCastro +- login: Dustyposa count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa - login: adriangb count: 45 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb -- login: Dustyposa - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 - url: https://github.com/Dustyposa - login: insomnes count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 url: https://github.com/insomnes -- login: odiseo0 - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 - url: https://github.com/odiseo0 - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 url: https://github.com/frankie567 +- login: odiseo0 + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 + url: https://github.com/odiseo0 - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 @@ -129,6 +129,10 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: acnebs count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 @@ -137,6 +141,10 @@ experts: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 url: https://github.com/SirTelemak +- login: chrisK824 + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: nymous count: 21 avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 @@ -145,22 +153,18 @@ experts: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf +- login: nsidnev + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 + url: https://github.com/nsidnev - login: ebottos94 count: 20 avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 url: https://github.com/ebottos94 -- login: chrisK824 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 - login: chris-allnutt count: 20 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt -- login: nsidnev - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 - url: https://github.com/nsidnev - login: hasansezertasan count: 19 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 @@ -189,42 +193,629 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 url: https://github.com/caeser1996 -- login: dstlny - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 - url: https://github.com/dstlny - login: jonatasoli count: 16 avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 url: https://github.com/jonatasoli -last_month_active: +last_month_experts: +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: Kludex + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: JavierSanchezCastro + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: jgould22 - count: 15 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: n8sty + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: ahmedabdou14 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: chrisK824 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: ThirVondukr + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: hussein-awala + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 + url: https://github.com/hussein-awala +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +three_months_experts: - login: Kludex - count: 14 + count: 90 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex +- login: JavierSanchezCastro + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: jgould22 + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: n8sty - count: 7 + count: 12 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: JavierSanchezCastro +- login: hasansezertasan + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: dolfinus + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 + url: https://github.com/dolfinus +- login: aanchlia + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: Ventura94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: shashstormer count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 + url: https://github.com/shashstormer +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: ahmedabdou14 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: chrisK824 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: fmelihh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + url: https://github.com/fmelihh +- login: acidjunk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: agn-7 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 + url: https://github.com/agn-7 +- login: ThirVondukr + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: hussein-awala + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 + url: https://github.com/hussein-awala +- login: JoshYuJump + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: bhumkong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 + url: https://github.com/bhumkong +- login: falkben + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 + url: https://github.com/falkben +- login: mielvds + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 + url: https://github.com/mielvds +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +- login: pbasista + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 + url: https://github.com/pbasista +- login: bogdan-coman-uv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv +- login: leonidktoto + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +- login: DJoepie + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4 + url: https://github.com/DJoepie +- login: alex-pobeditel-2004 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 + url: https://github.com/alex-pobeditel-2004 +- login: binbjz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: JonnyBootsNpants + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 + url: https://github.com/JonnyBootsNpants +- login: TarasKuzyo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7178184?v=4 + url: https://github.com/TarasKuzyo +- login: kiraware + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/117554978?v=4 + url: https://github.com/kiraware +- login: iudeen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: msehnout + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 + url: https://github.com/msehnout +- login: rafalkrupinski + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3732079?u=929e95d40d524301cb481da05208a25ed059400d&v=4 + url: https://github.com/rafalkrupinski +- login: morian + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1735308?u=8ef15491399b040bd95e2675bb8c8f2462e977b0&v=4 + url: https://github.com/morian +- login: garg10may + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 + url: https://github.com/garg10may +- login: taegyunum + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16094650?v=4 + url: https://github.com/taegyunum +six_months_experts: +- login: Kludex + count: 112 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: jgould22 + count: 66 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: JavierSanchezCastro + count: 32 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: n8sty + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: hasansezertasan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: WilliamStam + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 + url: https://github.com/WilliamStam +- login: iudeen + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: dolfinus + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 + url: https://github.com/dolfinus +- login: aanchlia + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: Ventura94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: nymous + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: White-Mask + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 + url: https://github.com/White-Mask +- login: chrisK824 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: alex-pobeditel-2004 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 + url: https://github.com/alex-pobeditel-2004 +- login: shashstormer + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 + url: https://github.com/shashstormer +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: JoshYuJump + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: ebottos94 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: pythonweb2 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 - login: ahmedabdou14 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 url: https://github.com/ahmedabdou14 -- login: GodMoonGoodman +- login: fmelihh count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + url: https://github.com/fmelihh +- login: binbjz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: theobouwman + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 + url: https://github.com/theobouwman +- login: Ryandaydev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 + url: https://github.com/Ryandaydev +- login: sriram-kondakindi + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32274323?v=4 + url: https://github.com/sriram-kondakindi +- login: NeilBotelho + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 + url: https://github.com/NeilBotelho +- login: yinziyan1206 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: pcorvoh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/48502122?u=89fe3e55f3cfd15d34ffac239b32af358cca6481&v=4 + url: https://github.com/pcorvoh +- login: acidjunk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: shashiwtt + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/87797476?v=4 + url: https://github.com/shashiwtt +- login: yavuzakyazici + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/148442912?u=1d2d150172c53daf82020b950c6483a6c6a77b7e&v=4 + url: https://github.com/yavuzakyazici +- login: AntonioBarral + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22151181?u=64416447a37a420e6dfd16e675cf74f66c9f204d&v=4 + url: https://github.com/AntonioBarral +- login: agn-7 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 + url: https://github.com/agn-7 +- login: ThirVondukr + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: hussein-awala + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 + url: https://github.com/hussein-awala +- login: jcphlux + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/996689?v=4 + url: https://github.com/jcphlux +- login: Matthieu-LAURENT39 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/91389613?v=4 + url: https://github.com/Matthieu-LAURENT39 +- login: bhumkong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 + url: https://github.com/bhumkong +- login: falkben + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 + url: https://github.com/falkben +- login: mielvds + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 + url: https://github.com/mielvds +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +- login: pbasista + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 + url: https://github.com/pbasista +- login: osangu + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 + url: https://github.com/osangu +- login: bogdan-coman-uv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv +- login: leonidktoto + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +one_year_experts: +- login: Kludex + count: 231 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: jgould22 + count: 132 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: JavierSanchezCastro + count: 52 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: n8sty + count: 39 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: chrisK824 + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: hasansezertasan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: abhint + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint +- login: ahmedabdou14 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: nymous + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: iudeen + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: arjwilliams + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 + url: https://github.com/arjwilliams +- login: ebottos94 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 +- login: Viicos + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4 + url: https://github.com/Viicos +- login: WilliamStam + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 + url: https://github.com/WilliamStam +- login: yinziyan1206 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: mateoradman + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/48420316?u=066f36b8e8e263b0d90798113b0f291d3266db7c&v=4 + url: https://github.com/mateoradman +- login: dolfinus + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 + url: https://github.com/dolfinus +- login: aanchlia + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: romabozhanovgithub + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 + url: https://github.com/romabozhanovgithub +- login: Ventura94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: White-Mask + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 + url: https://github.com/White-Mask +- login: mikeedjones + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 + url: https://github.com/mikeedjones +- login: ThirVondukr + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: dmontagu + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu +- login: alex-pobeditel-2004 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 + url: https://github.com/alex-pobeditel-2004 +- login: shashstormer + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 + url: https://github.com/shashstormer +- login: nzig + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 + url: https://github.com/nzig +- login: wu-clan + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 + url: https://github.com/wu-clan +- login: adriangb + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb +- login: 8thgencore + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/30128845?u=a747e840f751a1d196d70d0ecf6d07a530d412a1&v=4 + url: https://github.com/8thgencore +- login: acidjunk + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: GodMoonGoodman + count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 url: https://github.com/GodMoonGoodman +- login: JoshYuJump + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: commonism + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4 + url: https://github.com/commonism +- login: estebanx64 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: djimontyp + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/53098395?u=583bade70950b277c322d35f1be2b75c7b0f189c&v=4 + url: https://github.com/djimontyp +- login: sanzoghenzo + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/977953?u=d94445b7b87b7096a92a2d4b652ca6c560f34039&v=4 + url: https://github.com/sanzoghenzo +- login: hochstibe + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/48712216?u=1862e0265e06be7ff710f7dc12094250c0616313&v=4 + url: https://github.com/hochstibe +- login: pythonweb2 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: nameer + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer +- login: anthonycepeda + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda +- login: 9en9i + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/44907258?u=297d0f31ea99c22b718118c1deec82001690cadb&v=4 + url: https://github.com/9en9i +- login: AlexanderPodorov + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/54511144?v=4 + url: https://github.com/AlexanderPodorov +- login: sharonyogev + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/31185192?u=b13ea64b3cdaf3903390c555793aba4aff45c5e6&v=4 + url: https://github.com/sharonyogev +- login: fmelihh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + url: https://github.com/fmelihh +- login: jinluyang + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15670327?v=4 + url: https://github.com/jinluyang +- login: mht2953658596 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4 + url: https://github.com/mht2953658596 top_contributors: - login: nilslindemann - count: 29 + count: 30 avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 url: https://github.com/nilslindemann - login: jaystone776 @@ -281,7 +872,7 @@ top_contributors: url: https://github.com/hard-coders - login: KaniKim count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=3e00ea6ceb45d252b93b2ec515e73c63baa06ff4&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=d8ff6fca8542d22f94388cd2c4292e76e3898584&v=4 url: https://github.com/KaniKim - login: xzmeng count: 9 @@ -315,6 +906,10 @@ top_contributors: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 url: https://github.com/batlopes +- login: alejsdev + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + url: https://github.com/alejsdev - login: wshayes count: 5 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 @@ -339,10 +934,6 @@ top_contributors: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 url: https://github.com/tamtam-fitness -- login: alejsdev - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 - url: https://github.com/alejsdev - login: jekirl count: 4 avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 @@ -391,9 +982,25 @@ top_contributors: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 url: https://github.com/ivan-abc +- login: divums + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1397556?v=4 + url: https://github.com/divums +- login: prostomarkeloff + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 + url: https://github.com/prostomarkeloff +- login: nsidnev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 + url: https://github.com/nsidnev +- login: pawamoy + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 + url: https://github.com/pawamoy top_reviewers: - login: Kludex - count: 154 + count: 155 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan @@ -454,7 +1061,7 @@ top_reviewers: url: https://github.com/ArcLightSlavik - login: cassiobotaro count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 url: https://github.com/cassiobotaro - login: lsglucas count: 27 @@ -484,6 +1091,10 @@ top_reviewers: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders +- login: YuriiMotov + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: rjNemo count: 21 avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 @@ -536,10 +1147,10 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 -- login: YuriiMotov - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov +- login: Aruelius + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 + url: https://github.com/Aruelius - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 @@ -552,10 +1163,10 @@ top_reviewers: count: 13 avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 url: https://github.com/r0b2g1t -- login: Aruelius +- login: JavierSanchezCastro count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 - url: https://github.com/Aruelius + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: RunningIkkyu count: 12 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 @@ -568,10 +1179,6 @@ top_reviewers: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 url: https://github.com/AlertRED -- login: JavierSanchezCastro - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: solomein-sv count: 11 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 @@ -588,3 +1195,200 @@ top_reviewers: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv +top_translations_reviewers: +- login: Xewus + count: 128 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus +- login: s111d + count: 122 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d +- login: tokusumi + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 + url: https://github.com/tokusumi +- login: hasansezertasan + count: 84 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: AlertRED + count: 70 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED +- login: Alexandrhub + count: 68 + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub +- login: waynerv + count: 63 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +- login: hard-coders + count: 53 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +- login: Laineyzhang55 + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 + url: https://github.com/Laineyzhang55 +- login: Kludex + count: 46 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: komtaki + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 + url: https://github.com/komtaki +- login: Winand + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 + url: https://github.com/Winand +- login: solomein-sv + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 + url: https://github.com/solomein-sv +- login: alperiox + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=0688c1dc00988150a82d299106062c062ed1ba13&v=4 + url: https://github.com/alperiox +- login: lsglucas + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 + url: https://github.com/lsglucas +- login: SwftAlpc + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc +- login: nilslindemann + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +- login: rjNemo + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 + url: https://github.com/rjNemo +- login: akarev0 + count: 33 + avatarUrl: https://avatars.githubusercontent.com/u/53393089?u=6e528bb4789d56af887ce6fe237bea4010885406&v=4 + url: https://github.com/akarev0 +- login: romashevchenko + count: 32 + avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 + url: https://github.com/romashevchenko +- login: LorhanSohaky + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky +- login: cassiobotaro + count: 29 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 + url: https://github.com/cassiobotaro +- login: wdh99 + count: 29 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 +- login: pedabraham + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 + url: https://github.com/pedabraham +- login: Smlep + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 + url: https://github.com/Smlep +- login: dedkot01 + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 + url: https://github.com/dedkot01 +- login: dpinezich + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 + url: https://github.com/dpinezich +- login: maoyibo + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 + url: https://github.com/maoyibo +- login: 0417taehyun + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 + url: https://github.com/0417taehyun +- login: BilalAlpaslan + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan +- login: zy7y + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 + url: https://github.com/zy7y +- login: mycaule + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/6161385?u=e3cec75bd6d938a0d73fae0dc5534d1ab2ed1b0e&v=4 + url: https://github.com/mycaule +- login: sh0nk + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 + url: https://github.com/sh0nk +- login: axel584 + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 + url: https://github.com/axel584 +- login: AGolicyn + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 + url: https://github.com/AGolicyn +- login: Attsun1031 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 + url: https://github.com/Attsun1031 +- login: ycd + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + url: https://github.com/ycd +- login: delhi09 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 + url: https://github.com/delhi09 +- login: rogerbrinkmann + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/5690226?v=4 + url: https://github.com/rogerbrinkmann +- login: DevDae + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 + url: https://github.com/DevDae +- login: sattosan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 + url: https://github.com/sattosan +- login: ComicShrimp + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 + url: https://github.com/ComicShrimp +- login: simatheone + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 + url: https://github.com/simatheone +- login: ivan-abc + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc +- login: bezaca + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 + url: https://github.com/bezaca +- login: lbmendes + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 + url: https://github.com/lbmendes +- login: rostik1410 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +- login: spacesphere + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 + url: https://github.com/spacesphere +- login: panko + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/1569515?u=a84a5d255621ed82f8e1ca052f5f2eeb75997da2&v=4 + url: https://github.com/panko diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index 7e26358d8..2bd01ba43 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -7,7 +7,7 @@ hide: FastAPI has an amazing community that welcomes people from all backgrounds. -## Creator - Maintainer +## Creator Hey! 👋 @@ -23,7 +23,7 @@ This is me: </div> {% endif %} -I'm the creator and maintainer of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. ...But here I want to show you the community. @@ -39,13 +39,32 @@ These are the people that: A round of applause to them. 👏 🙇 -## Most active users last month +## FastAPI Experts -These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last month. ☕ +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🙇 + +They have proven to be **FastAPI Experts** by helping many others. ✨ + +!!! tip + You could become an official FastAPI Expert too! + + Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 + +You can see the **FastAPI Experts** for: + +* [Last Month](#fastapi-experts-last-month) 🤓 +* [3 Months](#fastapi-experts-3-months) 😎 +* [6 Months](#fastapi-experts-6-months) 🧐 +* [1 Year](#fastapi-experts-1-year) 🧑🔬 +* [**All Time**](#fastapi-experts-all-time) 🧙 + +### FastAPI Experts - Last Month + +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last month. 🤓 {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div> {% endfor %} @@ -53,17 +72,57 @@ These are the users that have been [helping others the most with questions in Gi </div> {% endif %} -## Experts +### FastAPI Experts - 3 Months + +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 3 months. 😎 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.three_months_experts[:10] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div> +{% endfor %} -Here are the **FastAPI Experts**. 🤓 +</div> +{% endif %} -These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} through *all time*. +### FastAPI Experts - 6 Months -They have proven to be experts by helping many others. ✨ +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 6 months. 🧐 {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.six_months_experts[:10] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI Experts - 1 Year + +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last year. 🧑🔬 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.one_year_experts[:20] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI Experts - All Time + +Here are the all time **FastAPI Experts**. 🤓🤯 + +These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} through *all time*. 🧙 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div> {% endfor %} @@ -81,7 +140,7 @@ They have contributed source code, documentation, translations, etc. 📦 {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> {% endfor %} @@ -91,21 +150,15 @@ They have contributed source code, documentation, translations, etc. 📦 There are many other contributors (more than a hundred), you can see them all in the <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors page</a>. 👷 -## Top Reviewers - -These users are the **Top Reviewers**. 🕵️ +## Top Translation Reviewers -### Reviews for Translations +These users are the **Top Translation Reviewers**. 🕵️ I only speak a few languages (and not very well 😅). So, the reviewers are the ones that have the [**power to approve translations**](contributing.md#translations){.internal-link target=_blank} of the documentation. Without them, there wouldn't be documentation in several other languages. ---- - -The **Top Reviewers** 🕵️ have reviewed the most Pull Requests from others, ensuring the quality of the code, documentation, and especially, the **translations**. - {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md index 945f0794e..275a9bd37 100644 --- a/docs/fr/docs/fastapi-people.md +++ b/docs/fr/docs/fastapi-people.md @@ -40,7 +40,7 @@ Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes ( {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions répondues: {{ user.count }}</div></div> {% endfor %} @@ -58,7 +58,7 @@ Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personne {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions répondues: {{ user.count }}</div></div> {% endfor %} @@ -76,7 +76,7 @@ Ils ont contribué au code source, à la documentation, aux traductions, etc. {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> {% endfor %} @@ -100,7 +100,7 @@ Les **Principaux Reviewers** 🕵️ ont examiné le plus grand nombre de demand {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md index 11dd656ea..ff75dcbce 100644 --- a/docs/ja/docs/fastapi-people.md +++ b/docs/ja/docs/fastapi-people.md @@ -41,7 +41,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -59,7 +59,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -77,7 +77,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> {% endfor %} @@ -101,7 +101,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md index 964cac68f..20061bfd9 100644 --- a/docs/pt/docs/fastapi-people.md +++ b/docs/pt/docs/fastapi-people.md @@ -40,7 +40,7 @@ Estes são os usuários que estão [helping others the most with issues (questio {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues respondidas: {{ user.count }}</div></div> {% endfor %} @@ -59,7 +59,7 @@ Eles provaram ser especialistas ajudando muitos outros. ✨ {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues respondidas: {{ user.count }}</div></div> {% endfor %} @@ -77,7 +77,7 @@ Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> {% endfor %} @@ -101,7 +101,7 @@ Os **Top Revisores** 🕵️ revisaram a maior parte de Pull Requests de outros, {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Revisões: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md index 6778cceab..0e42aab69 100644 --- a/docs/ru/docs/fastapi-people.md +++ b/docs/ru/docs/fastapi-people.md @@ -41,7 +41,7 @@ {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -59,7 +59,7 @@ {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -77,7 +77,7 @@ {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> {% endfor %} @@ -102,7 +102,7 @@ {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md index 4ab43ac00..6dd4ec061 100644 --- a/docs/tr/docs/fastapi-people.md +++ b/docs/tr/docs/fastapi-people.md @@ -45,7 +45,7 @@ Geçtiğimiz ay boyunca [GitHub'da diğerlerine en çok yardımcı olan](help-fa {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cevaplanan soru sayısı: {{ user.count }}</div></div> {% endfor %} @@ -63,7 +63,7 @@ Bir çok kullanıcıya yardım ederek uzman olduklarını kanıtladılar! ✨ {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cevaplanan soru sayısı: {{ user.count }}</div></div> {% endfor %} @@ -81,7 +81,7 @@ Kaynak koduna, dökümantasyona, çevirilere ve bir sürü şeye katkıda bulund {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Request sayısı: {{ user.count }}</div></div> {% endfor %} @@ -105,7 +105,7 @@ Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzde {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Değerlendirme sayısı: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md index b32f0e5ce..f7d0220b5 100644 --- a/docs/uk/docs/fastapi-people.md +++ b/docs/uk/docs/fastapi-people.md @@ -40,7 +40,7 @@ FastAPI має дивовижну спільноту, яка вітає люде {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -58,7 +58,7 @@ FastAPI має дивовижну спільноту, яка вітає люде {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -76,7 +76,7 @@ FastAPI має дивовижну спільноту, яка вітає люде {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> {% endfor %} @@ -100,7 +100,7 @@ FastAPI має дивовижну спільноту, яка вітає люде {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> {% endfor %} diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md index 5d7b0923f..7ef3f3c1a 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -40,7 +40,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %} <div class="user-list user-list-center"> -{% for user in people.last_month_active %} +{% for user in people.last_month_experts[:10] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -58,7 +58,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %} <div class="user-list user-list-center"> -{% for user in people.experts %} +{% for user in people.experts[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> {% endfor %} @@ -76,7 +76,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_contributors %} +{% for user in people.top_contributors[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> {% endfor %} @@ -100,7 +100,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 {% if people %} <div class="user-list user-list-center"> -{% for user in people.top_reviewers %} +{% for user in people.top_translations_reviewers[:50] %} <div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> {% endfor %} From ffb4f77a11f83132b521ba0aac6c95792c19e797 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 16 Mar 2024 23:54:48 +0000 Subject: [PATCH 057/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c81289de8..00ebbf2d7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Internal +* ♻️ Refactor computing FastAPI People, include 3 months, 6 months, 1 year, based on comment date, not discussion date. PR [#11304](https://github.com/tiangolo/fastapi/pull/11304) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11228](https://github.com/tiangolo/fastapi/pull/11228) by [@tiangolo](https://github.com/tiangolo). * 🔥 Remove Jina AI QA Bot from the docs. PR [#11268](https://github.com/tiangolo/fastapi/pull/11268) by [@nan-wang](https://github.com/nan-wang). * 🔧 Update sponsors, remove Jina, remove Powens, move TestDriven.io. PR [#11213](https://github.com/tiangolo/fastapi/pull/11213) by [@tiangolo](https://github.com/tiangolo). From ff4c4e0c42432586f31467087f06bff3f7a11f28 Mon Sep 17 00:00:00 2001 From: choi-haram <62204475+choi-haram@users.noreply.github.com> Date: Tue, 19 Mar 2024 01:25:02 +0900 Subject: [PATCH 058/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/about/index.md`=20(#11299)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🌐 Add Korean translation for docs/ko/docs/about/index.md --- docs/ko/docs/about/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/ko/docs/about/index.md diff --git a/docs/ko/docs/about/index.md b/docs/ko/docs/about/index.md new file mode 100644 index 000000000..ee7804d32 --- /dev/null +++ b/docs/ko/docs/about/index.md @@ -0,0 +1,3 @@ +# 소개 + +FastAPI에 대한 디자인, 영감 등에 대해 🤓 From 2189ce9e6a5ec20e4ea7629d05db4c15952d24ba Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 18 Mar 2024 16:25:27 +0000 Subject: [PATCH 059/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 00ebbf2d7..18b9c6cdd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/about/index.md`. PR [#11299](https://github.com/tiangolo/fastapi/pull/11299) by [@choi-haram](https://github.com/choi-haram). * 🌐 Add Korean translation for `docs/ko/docs/advanced/index.md`. PR [#9613](https://github.com/tiangolo/fastapi/pull/9613) by [@ElliottLarsen](https://github.com/ElliottLarsen). * 🌐 Add German translation for `docs/de/docs/how-to/extending-openapi.md`. PR [#10794](https://github.com/tiangolo/fastapi/pull/10794) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/metadata.md`. PR [#11286](https://github.com/tiangolo/fastapi/pull/11286) by [@jackleeio](https://github.com/jackleeio). From 6297c8a0bd149527a233efbf11260e5f612e8176 Mon Sep 17 00:00:00 2001 From: choi-haram <62204475+choi-haram@users.noreply.github.com> Date: Tue, 19 Mar 2024 01:26:07 +0900 Subject: [PATCH 060/846] =?UTF-8?q?=F0=9F=8C=90=20Fix=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/index.md`=20(#11296)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index d3d5d4e84..09f368ce9 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -386,7 +386,7 @@ item: Item --- -우리는 그저 수박 겉핡기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다. +우리는 그저 수박 겉 핥기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다. 다음 줄을 바꿔보십시오: From e75260110797f229e3c83596b995571ca8c8a560 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 18 Mar 2024 16:26:42 +0000 Subject: [PATCH 061/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 18b9c6cdd..f364971b8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Translations +* 🌐 Fix Korean translation for `docs/ko/docs/index.md`. PR [#11296](https://github.com/tiangolo/fastapi/pull/11296) by [@choi-haram](https://github.com/choi-haram). * 🌐 Add Korean translation for `docs/ko/docs/about/index.md`. PR [#11299](https://github.com/tiangolo/fastapi/pull/11299) by [@choi-haram](https://github.com/choi-haram). * 🌐 Add Korean translation for `docs/ko/docs/advanced/index.md`. PR [#9613](https://github.com/tiangolo/fastapi/pull/9613) by [@ElliottLarsen](https://github.com/ElliottLarsen). * 🌐 Add German translation for `docs/de/docs/how-to/extending-openapi.md`. PR [#10794](https://github.com/tiangolo/fastapi/pull/10794) by [@nilslindemann](https://github.com/nilslindemann). From cbbfd22aa094fa8dd82061d2b8dd68565171e73c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Mar 2024 20:33:28 -0500 Subject: [PATCH 062/846] =?UTF-8?q?=E2=AC=86=20Bump=20dawidd6/action-downl?= =?UTF-8?q?oad-artifact=20from=203.0.0=20to=203.1.4=20(#11310)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 3.0.0 to 3.1.4. - [Release notes](https://github.com/dawidd6/action-download-artifact/releases) - [Commits](https://github.com/dawidd6/action-download-artifact/compare/v3.0.0...v3.1.4) --- updated-dependencies: - dependency-name: dawidd6/action-download-artifact dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 2 +- .github/workflows/smokeshow.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 2bec6682c..b8dbb7dc5 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -21,7 +21,7 @@ jobs: mkdir ./site - name: Download Artifact Docs id: download - uses: dawidd6/action-download-artifact@v3.0.0 + uses: dawidd6/action-download-artifact@v3.1.4 with: if_no_artifact_found: ignore github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 10bff67ae..c4043cc6a 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -24,7 +24,7 @@ jobs: - run: pip install smokeshow - - uses: dawidd6/action-download-artifact@v3.0.0 + - uses: dawidd6/action-download-artifact@v3.1.4 with: github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} workflow: test.yml From 29254a76c472168c18cc24032587a4e42268efa6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 19 Mar 2024 01:33:53 +0000 Subject: [PATCH 063/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f364971b8..a03effdb4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump dawidd6/action-download-artifact from 3.0.0 to 3.1.4. PR [#11310](https://github.com/tiangolo/fastapi/pull/11310) by [@dependabot[bot]](https://github.com/apps/dependabot). * ♻️ Refactor computing FastAPI People, include 3 months, 6 months, 1 year, based on comment date, not discussion date. PR [#11304](https://github.com/tiangolo/fastapi/pull/11304) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11228](https://github.com/tiangolo/fastapi/pull/11228) by [@tiangolo](https://github.com/tiangolo). * 🔥 Remove Jina AI QA Bot from the docs. PR [#11268](https://github.com/tiangolo/fastapi/pull/11268) by [@nan-wang](https://github.com/nan-wang). From fb71a5d75bc41e041b008075962d5469365376c6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Mar 2024 20:35:22 -0500 Subject: [PATCH 064/846] =?UTF-8?q?=E2=AC=86=20Bump=20dorny/paths-filter?= =?UTF-8?q?=20from=202=20to=203=20(#11028)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [dorny/paths-filter](https://github.com/dorny/paths-filter) from 2 to 3. - [Release notes](https://github.com/dorny/paths-filter/releases) - [Changelog](https://github.com/dorny/paths-filter/blob/master/CHANGELOG.md) - [Commits](https://github.com/dorny/paths-filter/compare/v2...v3) --- updated-dependencies: - dependency-name: dorny/paths-filter dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 7783161b9..a4667b61e 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -19,7 +19,7 @@ jobs: steps: - uses: actions/checkout@v4 # For pull requests it's not necessary to checkout the code but for master it is - - uses: dorny/paths-filter@v2 + - uses: dorny/paths-filter@v3 id: filter with: filters: | From 957845d9673e63288afe226fe230a15787a45ab8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 19 Mar 2024 01:36:05 +0000 Subject: [PATCH 065/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a03effdb4..0d167ca47 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump dorny/paths-filter from 2 to 3. PR [#11028](https://github.com/tiangolo/fastapi/pull/11028) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 3.0.0 to 3.1.4. PR [#11310](https://github.com/tiangolo/fastapi/pull/11310) by [@dependabot[bot]](https://github.com/apps/dependabot). * ♻️ Refactor computing FastAPI People, include 3 months, 6 months, 1 year, based on comment date, not discussion date. PR [#11304](https://github.com/tiangolo/fastapi/pull/11304) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11228](https://github.com/tiangolo/fastapi/pull/11228) by [@tiangolo](https://github.com/tiangolo). From f29b30b78497b652cad5f69ad245bde9ff712361 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B0=B4=E4=B8=8A=20=E7=9A=93=E7=99=BB?= <nainaistar@gmail.com> Date: Thu, 21 Mar 2024 10:10:47 +0900 Subject: [PATCH 066/846] =?UTF-8?q?=F0=9F=94=A5=20Remove=20link=20to=20Pyd?= =?UTF-8?q?antic's=20benchmark,=20on=20other=20i18n=20pages.=20(#11224)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/features.md | 2 -- docs/em/docs/features.md | 2 -- docs/fr/docs/features.md | 2 -- docs/ja/docs/features.md | 2 -- docs/pl/docs/features.md | 2 -- docs/pt/docs/features.md | 2 -- docs/ru/docs/features.md | 2 -- docs/tr/docs/features.md | 2 -- docs/zh/docs/features.md | 2 -- 9 files changed, 18 deletions(-) diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index 64fa8092d..7b0e0587c 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -192,8 +192,6 @@ Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für d * Wenn Sie mit Python's Typisierung arbeiten können, können Sie auch mit Pydantic arbeiten. * Gutes Zusammenspiel mit Ihrer/Ihrem **<abbr title="Integrierten Entwicklungsumgebung, ähnlich zu (Quellcode-)Editor">IDE</abbr>/<abbr title="Ein Programm, was Fehler im Quellcode sucht">linter</abbr>/Gehirn**: * Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren. -* **Schnell**: - * In <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">Vergleichen</a> ist Pydantic schneller als jede andere getestete Bibliothek. * Validierung von **komplexen Strukturen**: * Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc. * Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema. diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index 19193da07..be787d85b 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -189,8 +189,6 @@ FastAPI 🔌 📶 ⏩ ⚙️, ✋️ 📶 🏋️ <abbr title='also known as "co * 🚥 👆 💭 🐍 🆎 👆 💭 ❔ ⚙️ Pydantic. * 🤾 🎆 ⏮️ 👆 **<abbr title="Integrated Development Environment, similar to a code editor">💾</abbr>/<abbr title="A program that checks for code errors">🧶</abbr>/🧠**: * ↩️ Pydantic 📊 📊 👐 🎓 👆 🔬; 🚘-🛠️, 🧽, ✍ & 👆 🤔 🔜 🌐 👷 ☑ ⏮️ 👆 ✔ 💽. -* **⏩**: - * <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">📇</a> Pydantic ⏩ 🌘 🌐 🎏 💯 🗃. * ✔ **🏗 📊**: * ⚙️ 🔗 Pydantic 🏷, 🐍 `typing`'Ⓜ `List` & `Dict`, ♒️. * & 💳 ✔ 🏗 💽 🔗 🎯 & 💪 🔬, ✅ & 📄 🎻 🔗. diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index 0c1f6269a..ce7508d27 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -189,8 +189,6 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Pydantic** (comme * Si vous connaissez le typage en python vous savez comment utiliser Pydantic. * Aide votre **<abbr title="Integrated Development Environment, il s'agit de votre éditeur de code">IDE</abbr>/<abbr title="Programme qui analyse le code à la recherche d'erreurs">linter</abbr>/cerveau**: * Parce que les structures de données de pydantic consistent seulement en une instance de classe que vous définissez; l'auto-complétion, le linting, mypy et votre intuition devrait être largement suffisante pour valider vos données. -* **Rapide**: - * Dans les <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">benchmarks</a> Pydantic est plus rapide que toutes les autres librairies testées. * Valide les **structures complexes**: * Utilise les modèles hiérarchique de Pydantic, le `typage` Python pour les `Lists`, `Dict`, etc. * Et les validateurs permettent aux schémas de données complexes d'être clairement et facilement définis, validés et documentés sous forme d'un schéma JSON. diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 853364f11..854c0764c 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -192,8 +192,6 @@ FastAPIには非常に使いやすく、非常に強力な<abbr title='also know * Pythonの型を知っている場合は、既にPydanticの使用方法を知っているに等しいです。 * ユーザーの **<abbr title = "コードエディターに似た統合開発環境">IDE</abbr>/<abbr title = "コードエラーをチェックするプログラム">リンター</abbr>/思考 とうまく連携します**: * Pydanticのデータ構造は、ユーザーが定義するクラスの単なるインスタンスであるため、オートコンプリート、リンティング、mypy、およびユーザーの直感はすべて、検証済みのデータで適切に機能するはずです。 -* **高速**: - * <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">ベンチマーク</a>では、Pydanticは他のすべてのテスト済みライブラリよりも高速です。 * **複雑な構造**を検証: * 階層的なPydanticモデルや、Pythonの「`typing`」の「`list`」と「`dict`」などの利用。 * バリデーターにより、複雑なデータスキーマを明確かつ簡単に定義、チェックし、JSONスキーマとして文書化できます。 diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index ed10af9bc..13f6d2ad7 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -189,8 +189,6 @@ Dzięki **FastAPI** otrzymujesz wszystkie funkcje **Pydantic** (ponieważ FastAP * Jeśli znasz adnotacje typów Pythona to wiesz jak używać Pydantic. * Dobrze współpracuje z Twoim **<abbr title='Skrót od "Integrated Development Environment", podobne do edytora kodu'>IDE</abbr>/<abbr title="Program, który sprawdza Twój kod pod kątem błędów">linterem</abbr>/mózgiem**: * Ponieważ struktury danych Pydantic to po prostu instancje klas, które definiujesz; autouzupełnianie, linting, mypy i twoja intuicja powinny działać poprawnie z Twoimi zwalidowanymi danymi. -* **Szybkość**: - * w <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">benchmarkach</a> Pydantic jest szybszy niż wszystkie inne testowane biblioteki. * Walidacja **złożonych struktur**: * Wykorzystanie hierarchicznych modeli Pydantic, Pythonowego modułu `typing` zawierającego `List`, `Dict`, itp. * Walidatory umożliwiają jasne i łatwe definiowanie, sprawdzanie złożonych struktur danych oraz dokumentowanie ich jako JSON Schema. diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index 822992c5b..83bd0ea92 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -190,8 +190,6 @@ Com **FastAPI** você terá todos os recursos do **Pydantic** (já que FastAPI u * Se você conhece os tipos do Python, você sabe como usar o Pydantic. * Vai bem com o/a seu/sua **<abbr title="Ambiente de Desenvolvimento Integrado, similar a um editor de código">IDE</abbr>/<abbr title="Um programa que confere erros de código">linter</abbr>/cérebro**: * Como as estruturas de dados do Pydantic são apenas instâncias de classes que você define, a auto completação, _linting_, _mypy_ e a sua intuição devem funcionar corretamente com seus dados validados. -* **Rápido**: - * em <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">_benchmarks_</a>, o Pydantic é mais rápido que todas as outras bibliotecas testadas. * Valida **estruturas complexas**: * Use modelos hierárquicos do Pydantic, `List` e `Dict` do `typing` do Python, etc. * Validadores permitem que esquemas de dados complexos sejam limpos e facilmente definidos, conferidos e documentados como JSON Schema. diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index 97841cc83..d67a9654b 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -192,8 +192,6 @@ FastAPI включает в себя чрезвычайно простую в и * Если вы знаете аннотации типов в Python, вы знаете, как использовать Pydantic. * Прекрасно сочетается с вашими **<abbr title="Интегрированное окружение для разработки, похожее на текстовый редактор">IDE</abbr>/<abbr title="программа проверяющая ошибки в коде">linter</abbr>/мозгом**: * Потому что структуры данных pydantic - это всего лишь экземпляры классов, определённых вами. Автодополнение, проверка кода, mypy и ваша интуиция - всё будет работать с вашими проверенными данными. -* **Быстродействие**: - * В <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">тестовых замерах</a> Pydantic быстрее, чем все другие проверенные библиотеки. * Проверка **сложных структур**: * Использование иерархических моделей Pydantic; `List`, `Dict` и т.п. из модуля `typing` (входит в стандартную библиотеку Python). * Валидаторы позволяют четко и легко определять, проверять и документировать сложные схемы данных в виде JSON Schema. diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index 8b143ffe7..ef4975c59 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -197,8 +197,6 @@ Aynı şekilde, databaseden gelen objeyi de **direkt olarak isteğe** de tamamiy * Eğer Python typelarını nasıl kullanacağını biliyorsan Pydantic kullanmayı da biliyorsundur. * Kullandığın geliştirme araçları ile iyi çalışır **<abbr title="Integrated Development Environment, kod editörüne benzer">IDE</abbr>/<abbr title="Code errorlarınızı inceleyen program">linter</abbr>/brain**: * Pydantic'in veri yapıları aslında sadece senin tanımladığın classlar; Bu yüzden doğrulanmış dataların ile otomatik tamamlama, linting ve mypy'ı kullanarak sorunsuz bir şekilde çalışabilirsin -* **Hızlı**: - * <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">Benchmarklarda</a>, Pydantic'in diğer bütün test edilmiş bütün kütüphanelerden daha hızlı. * **En kompleks** yapıları bile doğrula: * Hiyerarşik Pydantic modellerinin kullanımı ile beraber, Python `typing`’s `List` and `Dict`, vs gibi şeyleri doğrula. * Doğrulayıcılar en kompleks data şemalarının bile temiz ve kolay bir şekilde tanımlanmasına izin veriyor, ve hepsi JSON şeması olarak dokümante ediliyor diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index 2db7f852a..9fba24814 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -194,8 +194,6 @@ FastAPI 有一个使用非常简单,但是非常强大的<abbr title='也叫 * 如果你知道 Python types,你就知道如何使用 Pydantic。 * 和你 **<abbr title="集成开发环境,和代码编辑器类似">IDE</abbr>/<abbr title="一个检查代码错误的程序">linter</abbr>/brain** 适配: * 因为 pydantic 数据结构仅仅是你定义的类的实例;自动补全,linting,mypy 以及你的直觉应该可以和你验证的数据一起正常工作。 -* **更快**: - * 在 <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">基准测试</a> 中,Pydantic 比其他被测试的库都要快。 * 验证**复杂结构**: * 使用分层的 Pydantic 模型, Python `typing`的 `List` 和 `Dict` 等等。 * 验证器使我们能够简单清楚的将复杂的数据模式定义、检查并记录为 JSON Schema。 From 06e534404d8fd41b19ea070ddc6365761709ef62 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 21 Mar 2024 01:11:12 +0000 Subject: [PATCH 067/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0d167ca47..4b662f7a8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔥 Remove link to Pydantic's benchmark, on other i18n pages.. PR [#11224](https://github.com/tiangolo/fastapi/pull/11224) by [@hirotoKirimaru](https://github.com/hirotoKirimaru). * ✏️ Fix typos in docstrings. PR [#11295](https://github.com/tiangolo/fastapi/pull/11295) by [@davidhuser](https://github.com/davidhuser). * 🛠️ Improve Node.js script in docs to generate TypeScript clients. PR [#11293](https://github.com/tiangolo/fastapi/pull/11293) by [@alejsdev](https://github.com/alejsdev). * 📝 Update examples for tests to replace "inexistent" for "nonexistent". PR [#11220](https://github.com/tiangolo/fastapi/pull/11220) by [@Homesteady](https://github.com/Homesteady). From 887ac7054b0c270b6afa60f62113cd11651fa4b7 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 21 Mar 2024 15:57:27 -0500 Subject: [PATCH 068/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20External=20Link?= =?UTF-8?q?s=20(#11327)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 58e7acefe..827581de5 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,14 @@ Articles: English: + - author: Kurtis Pykes - NVIDIA + link: https://developer.nvidia.com/blog/building-a-machine-learning-microservice-with-fastapi/ + title: Building a Machine Learning Microservice with FastAPI + - author: Ravgeet Dhillon - Twilio + link: https://www.twilio.com/en-us/blog/booking-appointments-twilio-notion-fastapi + title: Booking Appointments with Twilio, Notion, and FastAPI + - author: Abhinav Tripathi - Microsoft Blogs + link: https://devblogs.microsoft.com/cosmosdb/azure-cosmos-db-python-and-fastapi/ + title: Write a Python data layer with Azure Cosmos DB and FastAPI - author: Donny Peeters author_link: https://github.com/Donnype link: https://bitestreams.com/blog/fastapi-sqlalchemy/ @@ -340,6 +349,14 @@ Articles: title: 'Tortoise ORM / FastAPI 整合快速筆記' Podcasts: English: + - author: Real Python + author_link: https://realpython.com/ + link: https://realpython.com/podcasts/rpp/72/ + title: Starting With FastAPI and Examining Python's Import System - Episode 72 + - author: Python Bytes FM + author_link: https://pythonbytes.fm/ + link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/ + title: 'Do you dare to press "."? - Episode 247 - Dan #6: SQLModel - use the same models for SQL and FastAPI' - author: Podcast.`__init__` author_link: https://www.pythonpodcast.com/ link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/ From 517d0a95de08282b4246dff4c57e71c721333510 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 21 Mar 2024 20:57:53 +0000 Subject: [PATCH 069/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4b662f7a8..334339af0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update External Links. PR [#11327](https://github.com/tiangolo/fastapi/pull/11327) by [@alejsdev](https://github.com/alejsdev). * 🔥 Remove link to Pydantic's benchmark, on other i18n pages.. PR [#11224](https://github.com/tiangolo/fastapi/pull/11224) by [@hirotoKirimaru](https://github.com/hirotoKirimaru). * ✏️ Fix typos in docstrings. PR [#11295](https://github.com/tiangolo/fastapi/pull/11295) by [@davidhuser](https://github.com/davidhuser). * 🛠️ Improve Node.js script in docs to generate TypeScript clients. PR [#11293](https://github.com/tiangolo/fastapi/pull/11293) by [@alejsdev](https://github.com/alejsdev). From 0021acd4de35c43105e942833a810403a957a9a8 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 21 Mar 2024 16:12:21 -0500 Subject: [PATCH 070/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20`project-genera?= =?UTF-8?q?tion.md`=20(#11326)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/en/docs/project-generation.md | 111 +++++++---------------------- 1 file changed, 27 insertions(+), 84 deletions(-) diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md index 8ba34fa11..d142862ee 100644 --- a/docs/en/docs/project-generation.md +++ b/docs/en/docs/project-generation.md @@ -1,84 +1,27 @@ -# Project Generation - Template - -You can use a project generator to get started, as it includes a lot of the initial set up, security, database and some API endpoints already done for you. - -A project generator will always have a very opinionated setup that you should update and adapt for your own needs, but it might be a good starting point for your project. - -## Full Stack FastAPI PostgreSQL - -GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> - -### Full Stack FastAPI PostgreSQL - Features - -* Full **Docker** integration (Docker based). -* Docker Swarm Mode deployment. -* **Docker Compose** integration and optimization for local development. -* **Production ready** Python web server using Uvicorn and Gunicorn. -* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> backend: - * **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). - * **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. - * **Easy**: Designed to be easy to use and learn. Less time reading docs. - * **Short**: Minimize code duplication. Multiple features from each parameter declaration. - * **Robust**: Get production-ready code. With automatic interactive documentation. - * **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> and <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>. - * <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">**Many other features**</a> including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc. -* **Secure password** hashing by default. -* **JWT token** authentication. -* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly). -* Basic starting models for users (modify and remove as you need). -* **Alembic** migrations. -* **CORS** (Cross Origin Resource Sharing). -* **Celery** worker that can import and use models and code from the rest of the backend selectively. -* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works). -* Easy Python integration with **Jupyter Kernels** for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter. -* **Vue** frontend: - * Generated with Vue CLI. - * **JWT Authentication** handling. - * Login view. - * After login, main dashboard view. - * Main dashboard with user creation and edition. - * Self user edition. - * **Vuex**. - * **Vue-router**. - * **Vuetify** for beautiful material design components. - * **TypeScript**. - * Docker server based on **Nginx** (configured to play nicely with Vue-router). - * Docker multi-stage building, so you don't need to save or commit compiled code. - * Frontend tests ran at build time (can be disabled too). - * Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want. -* **PGAdmin** for PostgreSQL database, you can modify it to use PHPMyAdmin and MySQL easily. -* **Flower** for Celery jobs monitoring. -* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers. -* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation. -* GitLab **CI** (continuous integration), including frontend and backend testing. - -## Full Stack FastAPI Couchbase - -GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a> - -⚠️ **WARNING** ⚠️ - -If you are starting a new project from scratch, check the alternatives here. - -For example, the project generator <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">Full Stack FastAPI PostgreSQL</a> might be a better alternative, as it is actively maintained and used. And it includes all the new features and improvements. - -You are still free to use the Couchbase-based generator if you want to, it should probably still work fine, and if you already have a project generated with it that's fine as well (and you probably already updated it to suit your needs). - -You can read more about it in the docs for the repo. - -## Full Stack FastAPI MongoDB - -...might come later, depending on my time availability and other factors. 😅 🎉 - -## Machine Learning models with spaCy and FastAPI - -GitHub: <a href="https://github.com/microsoft/cookiecutter-spacy-fastapi" class="external-link" target="_blank">https://github.com/microsoft/cookiecutter-spacy-fastapi</a> - -### Machine Learning models with spaCy and FastAPI - Features - -* **spaCy** NER model integration. -* **Azure Cognitive Search** request format built in. -* **Production ready** Python web server using Uvicorn and Gunicorn. -* **Azure DevOps** Kubernetes (AKS) CI/CD deployment built in. -* **Multilingual** Easily choose one of spaCy's built in languages during project setup. -* **Easily extensible** to other model frameworks (Pytorch, Tensorflow), not just spaCy. +# Full Stack FastAPI Template + +Templates, while typically come with a specific setup, are designed to be flexible and customizable. This allows you to modify and adapt them to your project's requirements, making them an excellent starting point. 🏁 + +You can use this template to get started, as it includes a lot of the initial set up, security, database and some API endpoints already done for you. + +GitHub Repository: <a href="https://github.com/tiangolo/full-stack-fastapi-template" class="external-link" target="_blank">Full Stack FastAPI Template</a> + +## Full Stack FastAPI Template - Technology Stack and Features + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management. + - 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database. +- 🚀 [React](https://react.dev) for the frontend. + - 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack. + - 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components. + - 🤖 An automatically generated frontend client. + - 🦇 Dark mode support. +- 🐋 [Docker Compose](https://www.docker.com) for development and production. +- 🔒 Secure password hashing by default. +- 🔑 JWT token authentication. +- 📫 Email based password recovery. +- ✅ Tests with [Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer. +- 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates. +- 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions. From 96b14d9f33988c96edb271c02151792a49a70658 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 21 Mar 2024 21:12:48 +0000 Subject: [PATCH 071/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 334339af0..c91f9edbb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update `project-generation.md`. PR [#11326](https://github.com/tiangolo/fastapi/pull/11326) by [@alejsdev](https://github.com/alejsdev). * 📝 Update External Links. PR [#11327](https://github.com/tiangolo/fastapi/pull/11327) by [@alejsdev](https://github.com/alejsdev). * 🔥 Remove link to Pydantic's benchmark, on other i18n pages.. PR [#11224](https://github.com/tiangolo/fastapi/pull/11224) by [@hirotoKirimaru](https://github.com/hirotoKirimaru). * ✏️ Fix typos in docstrings. PR [#11295](https://github.com/tiangolo/fastapi/pull/11295) by [@davidhuser](https://github.com/davidhuser). From 7b1da59b28b5ad7a2a9621b530e85da2cb2449e0 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 21 Mar 2024 16:54:22 -0500 Subject: [PATCH 072/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`docs/en/docs/tutorial/extra-models.md`=20(#11329)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/extra-models.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index d83b6bc85..ad253a336 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -120,7 +120,7 @@ would be equivalent to: UserInDB(**user_in.dict()) ``` -...because `user_in.dict()` is a `dict`, and then we make Python "unwrap" it by passing it to `UserInDB` prepended with `**`. +...because `user_in.dict()` is a `dict`, and then we make Python "unwrap" it by passing it to `UserInDB` prefixed with `**`. So, we get a Pydantic model from the data in another Pydantic model. From 03b1e93456aa3736b9ea2359b918d22885a1aa98 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 21 Mar 2024 21:54:43 +0000 Subject: [PATCH 073/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c91f9edbb..99d36bae9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix typo in `docs/en/docs/tutorial/extra-models.md`. PR [#11329](https://github.com/tiangolo/fastapi/pull/11329) by [@alejsdev](https://github.com/alejsdev). * 📝 Update `project-generation.md`. PR [#11326](https://github.com/tiangolo/fastapi/pull/11326) by [@alejsdev](https://github.com/alejsdev). * 📝 Update External Links. PR [#11327](https://github.com/tiangolo/fastapi/pull/11327) by [@alejsdev](https://github.com/alejsdev). * 🔥 Remove link to Pydantic's benchmark, on other i18n pages.. PR [#11224](https://github.com/tiangolo/fastapi/pull/11224) by [@hirotoKirimaru](https://github.com/hirotoKirimaru). From 93034fea48a85d5e7ac336b8ec455d2e26f0e364 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 21 Mar 2024 20:42:11 -0500 Subject: [PATCH 074/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20links=20to=20Py?= =?UTF-8?q?dantic=20docs=20to=20point=20to=20new=20website=20(#11328)?= 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/features.md | 2 +- docs/de/docs/tutorial/body-nested-models.md | 2 +- docs/de/docs/tutorial/body.md | 2 +- docs/em/docs/advanced/dataclasses.md | 4 ++-- docs/em/docs/advanced/openapi-callbacks.md | 2 +- docs/em/docs/advanced/settings.md | 4 ++-- docs/em/docs/alternatives.md | 2 +- docs/em/docs/features.md | 2 +- docs/em/docs/history-design-future.md | 2 +- docs/em/docs/index.md | 2 +- docs/em/docs/python-types.md | 6 +++--- docs/em/docs/tutorial/body-nested-models.md | 2 +- docs/em/docs/tutorial/body.md | 2 +- docs/em/docs/tutorial/extra-data-types.md | 4 ++-- docs/em/docs/tutorial/extra-models.md | 2 +- docs/em/docs/tutorial/handling-errors.md | 2 +- docs/em/docs/tutorial/path-params.md | 2 +- docs/em/docs/tutorial/query-params-str-validations.md | 2 +- docs/em/docs/tutorial/response-model.md | 4 ++-- docs/em/docs/tutorial/schema-extra-example.md | 2 +- docs/em/docs/tutorial/sql-databases.md | 2 +- docs/en/docs/advanced/dataclasses.md | 4 ++-- docs/en/docs/advanced/openapi-callbacks.md | 2 +- docs/en/docs/alternatives.md | 2 +- docs/en/docs/features.md | 2 +- docs/en/docs/history-design-future.md | 2 +- docs/en/docs/index.md | 2 +- docs/en/docs/python-types.md | 6 +++--- docs/en/docs/release-notes.md | 2 +- docs/en/docs/tutorial/body-nested-models.md | 2 +- docs/en/docs/tutorial/body.md | 2 +- docs/en/docs/tutorial/extra-data-types.md | 2 +- docs/en/docs/tutorial/extra-models.md | 2 +- docs/en/docs/tutorial/handling-errors.md | 2 +- docs/en/docs/tutorial/path-params.md | 2 +- docs/en/docs/tutorial/query-params-str-validations.md | 2 +- docs/en/docs/tutorial/response-model.md | 4 ++-- docs/en/docs/tutorial/sql-databases.md | 2 +- docs/es/docs/features.md | 2 +- docs/es/docs/index.md | 2 +- docs/es/docs/python-types.md | 4 ++-- docs/es/docs/tutorial/path-params.md | 2 +- docs/fa/docs/features.md | 2 +- docs/fa/docs/index.md | 2 +- docs/fr/docs/alternatives.md | 2 +- docs/fr/docs/features.md | 2 +- docs/fr/docs/history-design-future.md | 2 +- docs/fr/docs/index.md | 2 +- docs/fr/docs/python-types.md | 4 ++-- docs/fr/docs/tutorial/body.md | 2 +- docs/fr/docs/tutorial/path-params.md | 2 +- docs/he/docs/index.md | 2 +- docs/hu/docs/index.md | 2 +- docs/it/docs/index.md | 2 +- docs/ja/docs/alternatives.md | 2 +- docs/ja/docs/features.md | 2 +- docs/ja/docs/history-design-future.md | 2 +- docs/ja/docs/index.md | 2 +- docs/ja/docs/python-types.md | 4 ++-- docs/ja/docs/tutorial/body-nested-models.md | 2 +- docs/ja/docs/tutorial/body.md | 2 +- docs/ja/docs/tutorial/extra-data-types.md | 4 ++-- docs/ja/docs/tutorial/handling-errors.md | 2 +- docs/ja/docs/tutorial/path-params.md | 2 +- docs/ja/docs/tutorial/response-model.md | 4 ++-- docs/ja/docs/tutorial/schema-extra-example.md | 2 +- docs/ko/docs/features.md | 2 +- docs/ko/docs/index.md | 2 +- docs/ko/docs/python-types.md | 4 ++-- docs/ko/docs/tutorial/body-nested-models.md | 2 +- docs/ko/docs/tutorial/body.md | 2 +- docs/ko/docs/tutorial/path-params.md | 2 +- docs/ko/docs/tutorial/response-model.md | 4 ++-- docs/pl/docs/features.md | 2 +- docs/pl/docs/index.md | 2 +- docs/pt/docs/alternatives.md | 2 +- docs/pt/docs/features.md | 2 +- docs/pt/docs/history-design-future.md | 2 +- docs/pt/docs/index.md | 2 +- docs/pt/docs/python-types.md | 4 ++-- docs/pt/docs/tutorial/body-nested-models.md | 2 +- docs/pt/docs/tutorial/body.md | 2 +- docs/pt/docs/tutorial/extra-data-types.md | 4 ++-- docs/pt/docs/tutorial/extra-models.md | 2 +- docs/pt/docs/tutorial/handling-errors.md | 2 +- docs/pt/docs/tutorial/path-params.md | 2 +- docs/pt/docs/tutorial/schema-extra-example.md | 2 +- docs/ru/docs/alternatives.md | 2 +- docs/ru/docs/features.md | 2 +- docs/ru/docs/history-design-future.md | 2 +- docs/ru/docs/index.md | 2 +- docs/ru/docs/python-types.md | 4 ++-- docs/ru/docs/tutorial/body-nested-models.md | 2 +- docs/ru/docs/tutorial/body.md | 2 +- docs/ru/docs/tutorial/extra-data-types.md | 4 ++-- docs/ru/docs/tutorial/extra-models.md | 2 +- docs/ru/docs/tutorial/handling-errors.md | 2 +- docs/ru/docs/tutorial/path-params.md | 2 +- docs/ru/docs/tutorial/query-params-str-validations.md | 2 +- docs/ru/docs/tutorial/response-model.md | 4 ++-- docs/ru/docs/tutorial/schema-extra-example.md | 2 +- docs/tr/docs/alternatives.md | 2 +- docs/tr/docs/features.md | 2 +- docs/tr/docs/history-design-future.md | 2 +- docs/tr/docs/index.md | 2 +- docs/tr/docs/python-types.md | 4 ++-- docs/tr/docs/tutorial/path-params.md | 2 +- docs/uk/docs/alternatives.md | 2 +- docs/uk/docs/index.md | 2 +- docs/uk/docs/python-types.md | 4 ++-- docs/uk/docs/tutorial/body.md | 2 +- docs/uk/docs/tutorial/extra-data-types.md | 4 ++-- docs/vi/docs/features.md | 2 +- docs/vi/docs/index.md | 2 +- docs/vi/docs/python-types.md | 6 +++--- docs/yo/docs/index.md | 2 +- docs/zh-hant/docs/index.md | 2 +- docs/zh/docs/advanced/settings.md | 4 ++-- docs/zh/docs/features.md | 2 +- docs/zh/docs/history-design-future.md | 2 +- docs/zh/docs/index.md | 2 +- docs/zh/docs/python-types.md | 4 ++-- docs/zh/docs/tutorial/body-nested-models.md | 2 +- docs/zh/docs/tutorial/body.md | 2 +- docs/zh/docs/tutorial/extra-data-types.md | 4 ++-- docs/zh/docs/tutorial/extra-models.md | 2 +- docs/zh/docs/tutorial/handling-errors.md | 2 +- docs/zh/docs/tutorial/path-params.md | 2 +- docs/zh/docs/tutorial/query-params-str-validations.md | 2 +- docs/zh/docs/tutorial/response-model.md | 4 ++-- docs/zh/docs/tutorial/schema-extra-example.md | 2 +- docs/zh/docs/tutorial/sql-databases.md | 2 +- docs_src/custom_response/tutorial006c.py | 2 +- .../test_tutorial/test_custom_response/test_tutorial006c.py | 2 +- 137 files changed, 168 insertions(+), 168 deletions(-) diff --git a/README.md b/README.md index a60d8775c..0c05687ce 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ Python 3.8+ FastAPI stands on the shoulders of giants: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> for the data parts. ## Installation diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index fb82bea1b..33bcc1556 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -120,7 +120,7 @@ Python 3.8+ FastAPI nəhənglərin çiyinlərində dayanır: * Web tərəfi üçün <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. -* Data tərəfi üçün <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>. +* Data tərəfi üçün <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>. ## Quraşdırma diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 28ef5d6d1..688f3f95a 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -112,7 +112,7 @@ Python 3.7+ FastAPI কিছু দানবেদের কাঁধে দাঁড়িয়ে আছে: - <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> ওয়েব অংশের জন্য. -- <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> ডেটা অংশগুলির জন্য. +- <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> ডেটা অংশগুলির জন্য. ## ইনস্টলেশন প্রক্রিয়া diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index 7b0e0587c..fee4b158e 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -177,7 +177,7 @@ Mit **FastAPI** bekommen Sie viele von **Starlette**'s Funktionen (da FastAPI nu ## Pydantic's Merkmale -**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Das bedeutet, auch jeder zusätzliche Pydantic Quellcode funktioniert. +**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Das bedeutet, auch jeder zusätzliche Pydantic Quellcode funktioniert. Verfügbar sind ebenso externe auf Pydantic basierende Bibliotheken, wie <abbr title="Object-Relational Mapper (Abbildung von Objekten auf relationale Strukturen)">ORM</abbr>s, <abbr title="Object-Document Mapper (Abbildung von Objekten auf nicht-relationale Strukturen)">ODM</abbr>s für Datenbanken. diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index 976f3f924..a7a15a6c2 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -192,7 +192,7 @@ Wiederum, nur mit dieser Deklaration erhalten Sie von **FastAPI**: Abgesehen von normalen einfachen Typen, wie `str`, `int`, `float`, usw. können Sie komplexere einfache Typen verwenden, die von `str` erben. -Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich <a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">Pydantics Typübersicht</a> an. Sie werden im nächsten Kapitel ein paar Beispiele kennenlernen. +Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantics Typübersicht</a> an. Sie werden im nächsten Kapitel ein paar Beispiele kennenlernen. Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarieren, dass das eine Instanz von Pydantics `HttpUrl` sein soll, anstelle eines `str`: diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 97215a780..6611cb51a 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -6,7 +6,7 @@ Ein **Request**body sind Daten, die vom Client zu Ihrer API gesendet werden. Ein Ihre API sendet fast immer einen **Response**body. Aber Clients senden nicht unbedingt immer **Request**bodys (sondern nur Metadaten). -Um einen **Request**body zu deklarieren, verwenden Sie <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>-Modelle mit allen deren Fähigkeiten und Vorzügen. +Um einen **Request**body zu deklarieren, verwenden Sie <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>-Modelle mit allen deren Fähigkeiten und Vorzügen. !!! info Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden. diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index a4c287106..e8c4b99a2 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -8,7 +8,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda {!../../../docs_src/dataclasses/tutorial001.py!} ``` -👉 🐕🦺 👏 **Pydantic**, ⚫️ ✔️ <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">🔗 🐕🦺 `dataclasses`</a>. +👉 🐕🦺 👏 **Pydantic**, ⚫️ ✔️ <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">🔗 🐕🦺 `dataclasses`</a>. , ⏮️ 📟 🔛 👈 🚫 ⚙️ Pydantic 🎯, FastAPI ⚙️ Pydantic 🗜 📚 🐩 🎻 Pydantic 👍 🍛 🎻. @@ -91,7 +91,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 🌀 `dataclasses` ⏮️ 🎏 Pydantic 🏷, 😖 ⚪️➡️ 👫, 🔌 👫 👆 👍 🏷, ♒️. -💡 🌅, ✅ <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/" class="external-link" target="_blank">Pydantic 🩺 🔃 🎻</a>. +💡 🌅, ✅ <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/" class="external-link" target="_blank">Pydantic 🩺 🔃 🎻</a>. ## ⏬ diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index 630b75ed2..3355d6071 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -36,7 +36,7 @@ ``` !!! tip - `callback_url` 🔢 🔢 ⚙️ Pydantic <a href="https://pydantic-docs.helpmanual.io/usage/types/#urls" class="external-link" target="_blank">📛</a> 🆎. + `callback_url` 🔢 🔢 ⚙️ Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">📛</a> 🆎. 🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭. diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index 2ebe8ffcb..c17212023 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -125,7 +125,7 @@ Hello World from Python ## Pydantic `Settings` -👐, Pydantic 🚚 👑 🚙 🍵 👫 ⚒ 👟 ⚪️➡️ 🌐 🔢 ⏮️ <a href="https://pydantic-docs.helpmanual.io/usage/settings/" class="external-link" target="_blank">Pydantic: ⚒ 🧾</a>. +👐, Pydantic 🚚 👑 🚙 🍵 👫 ⚒ 👟 ⚪️➡️ 🌐 🔢 ⏮️ <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/" class="external-link" target="_blank">Pydantic: ⚒ 🧾</a>. ### ✍ `Settings` 🎚 @@ -279,7 +279,7 @@ APP_NAME="ChimichangApp" 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. !!! tip - `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 <a href="https://pydantic-docs.helpmanual.io/usage/model_config/" class="external-link" target="_blank">Pydantic 🏷 📁</a> + `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic 🏷 📁</a> ### 🏗 `Settings` 🕴 🕐 ⏮️ `lru_cache` diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 6169aa52d..5890b3b13 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -342,7 +342,7 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ## ⚙️ **FastAPI** -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 🐍 🆎 🔑. diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index be787d85b..3693f4c54 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -174,7 +174,7 @@ FastAPI 🔌 📶 ⏩ ⚙️, ✋️ 📶 🏋️ <abbr title='also known as "co ## Pydantic ⚒ -**FastAPI** 🍕 🔗 ⏮️ (& ⚓️ 🔛) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. , 🙆 🌖 Pydantic 📟 👆 ✔️, 🔜 👷. +**FastAPI** 🍕 🔗 ⏮️ (& ⚓️ 🔛) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. , 🙆 🌖 Pydantic 📟 👆 ✔️, 🔜 👷. ✅ 🔢 🗃 ⚓️ 🔛 Pydantic, <abbr title="Object-Relational Mapper">🐜</abbr>Ⓜ, <abbr title="Object-Document Mapper">🏭</abbr>Ⓜ 💽. diff --git a/docs/em/docs/history-design-future.md b/docs/em/docs/history-design-future.md index 7e39972de..7a45fe14b 100644 --- a/docs/em/docs/history-design-future.md +++ b/docs/em/docs/history-design-future.md @@ -54,7 +54,7 @@ ## 📄 -⏮️ 🔬 📚 🎛, 👤 💭 👈 👤 🔜 ⚙️ <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a> 🚮 📈. +⏮️ 🔬 📚 🎛, 👤 💭 👈 👤 🔜 ⚙️ <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a> 🚮 📈. ⤴️ 👤 📉 ⚫️, ⚒ ⚫️ 🍕 🛠️ ⏮️ 🎻 🔗, 🐕🦺 🎏 🌌 🔬 ⚛ 📄, & 📉 👨🎨 🐕🦺 (🆎 ✅, ✍) ⚓️ 🔛 💯 📚 👨🎨. diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index 3c461b6ed..a0ccfafb8 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -120,7 +120,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ FastAPI 🧍 🔛 ⌚ 🐘: * <a href="https://www.starlette.io/" class="external-link" target="_blank">💃</a> 🕸 🍕. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 📊 🍕. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 📊 🍕. ## 👷♂ diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index e079d9039..b8f61a113 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -424,7 +424,7 @@ say_hi(name=None) # This works, None is valid 🎉 ## Pydantic 🏷 -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 🐍 🗃 🎭 📊 🔬. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 🐍 🗃 🎭 📊 🔬. 👆 📣 "💠" 💽 🎓 ⏮️ 🔢. @@ -455,14 +455,14 @@ say_hi(name=None) # This works, None is valid 🎉 ``` !!! info - 💡 🌖 🔃 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, ✅ 🚮 🩺</a>. + 💡 🌖 🔃 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, ✅ 🚮 🩺</a>. **FastAPI** 🌐 ⚓️ 🔛 Pydantic. 👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}. !!! tip - Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. + Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. ## 🆎 🔑 **FastAPI** diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index f4bd50f5c..c941fa08a 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -192,7 +192,7 @@ my_list: List[str] ↖️ ⚪️➡️ 😐 ⭐ 🆎 💖 `str`, `int`, `float`, ♒️. 👆 💪 ⚙️ 🌅 🏗 ⭐ 🆎 👈 😖 ⚪️➡️ `str`. -👀 🌐 🎛 👆 ✔️, 🛒 🩺 <a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">Pydantic 😍 🆎</a>. 👆 🔜 👀 🖼 ⏭ 📃. +👀 🌐 🎛 👆 ✔️, 🛒 🩺 <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic 😍 🆎</a>. 👆 🔜 👀 🖼 ⏭ 📃. 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index ca2f113bf..db850162a 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -6,7 +6,7 @@ 👆 🛠️ 🌖 🕧 ✔️ 📨 **📨** 💪. ✋️ 👩💻 🚫 🎯 💪 📨 **📨** 💪 🌐 🕰. -📣 **📨** 💪, 👆 ⚙️ <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 🏷 ⏮️ 🌐 👫 🏋️ & 💰. +📣 **📨** 💪, 👆 ⚙️ <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 🏷 ⏮️ 🌐 👫 🏋️ & 💰. !!! info 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index dfdf6141b..54a186f12 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * 🐍 `datetime.timedelta`. * 📨 & 📨 🔜 🎨 `float` 🌐 🥈. - * Pydantic ✔ 🎦 ⚫️ "💾 8️⃣6️⃣0️⃣1️⃣ 🕰 ➕ 🔢", <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders" class="external-link" target="_blank">👀 🩺 🌅 ℹ</a>. + * Pydantic ✔ 🎦 ⚫️ "💾 8️⃣6️⃣0️⃣1️⃣ 🕰 ➕ 🔢", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">👀 🩺 🌅 ℹ</a>. * `frozenset`: * 📨 & 📨, 😥 🎏 `set`: * 📨, 📇 🔜 ✍, ❎ ❎ & 🏭 ⚫️ `set`. @@ -49,7 +49,7 @@ * `Decimal`: * 🐩 🐍 `Decimal`. * 📨 & 📨, 🍵 🎏 `float`. -* 👆 💪 ✅ 🌐 ☑ Pydantic 📊 🆎 📥: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">Pydantic 📊 🆎</a>. +* 👆 💪 ✅ 🌐 ☑ Pydantic 📊 🆎 📥: <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic 📊 🆎</a>. ## 🖼 diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 06c36285d..7cb54a963 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -179,7 +179,7 @@ UserInDB( 👈, ⚙️ 🐩 🐍 🆎 🔑 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: !!! note - 🕐❔ ⚖ <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a>, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. + 🕐❔ ⚖ <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. === "🐍 3️⃣.6️⃣ & 🔛" diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index ef7bbfa65..36d58e2af 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -163,7 +163,7 @@ path -> item_id !!! warning 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. -`RequestValidationError` 🎧-🎓 Pydantic <a href="https://pydantic-docs.helpmanual.io/usage/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. +`RequestValidationError` 🎧-🎓 Pydantic <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. **FastAPI** ⚙️ ⚫️ 👈, 🚥 👆 ⚙️ Pydantic 🏷 `response_model`, & 👆 💽 ✔️ ❌, 👆 🔜 👀 ❌ 👆 🕹. diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index ea939b458..ac64d2ebb 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ ## Pydantic -🌐 💽 🔬 🎭 🔽 🚘 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, 👆 🤚 🌐 💰 ⚪️➡️ ⚫️. & 👆 💭 👆 👍 ✋. +🌐 💽 🔬 🎭 🔽 🚘 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, 👆 🤚 🌐 💰 ⚪️➡️ ⚫️. & 👆 💭 👆 👍 ✋. 👆 💪 ⚙️ 🎏 🆎 📄 ⏮️ `str`, `float`, `bool` & 📚 🎏 🏗 📊 🆎. diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index f0e455abe..1268c0d6e 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -227,7 +227,7 @@ q: Union[str, None] = Query(default=None, min_length=3) ``` !!! tip - Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. + Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. ### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 6ea4413f8..7103e9176 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -378,7 +378,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 ``` !!! info - FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">🚮 `exclude_unset` 🔢</a> 🏆 👉. + FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">🚮 `exclude_unset` 🔢</a> 🏆 👉. !!! info 👆 💪 ⚙️: @@ -386,7 +386,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - 🔬 <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic 🩺</a> `exclude_defaults` & `exclude_none`. + 🔬 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 🩺</a> `exclude_defaults` & `exclude_none`. #### 📊 ⏮️ 💲 🏑 ⏮️ 🔢 diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index d5bf8810a..114d5a84a 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -6,7 +6,7 @@ ## Pydantic `schema_extra` -👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 <a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic 🩺: 🔗 🛃</a>: +👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 <a href="https://docs.pydantic.dev/latest/concepts/json_schema/#customizing-json-schema" class="external-link" target="_blank">Pydantic 🩺: 🔗 🛃</a>: === "🐍 3️⃣.6️⃣ & 🔛" diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index e3ced7ef4..ef08fcf4b 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -331,7 +331,7 @@ name: str 🔜, Pydantic *🏷* 👂, `Item` & `User`, 🚮 🔗 `Config` 🎓. -👉 <a href="https://pydantic-docs.helpmanual.io/usage/model_config/" class="external-link" target="_blank">`Config`</a> 🎓 ⚙️ 🚚 📳 Pydantic. +👉 <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">`Config`</a> 🎓 ⚙️ 🚚 📳 Pydantic. `Config` 🎓, ⚒ 🔢 `orm_mode = True`. diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index ed1d5610f..481bf5e69 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -8,7 +8,7 @@ But FastAPI also supports using <a href="https://docs.python.org/3/library/datac {!../../../docs_src/dataclasses/tutorial001.py!} ``` -This is still supported thanks to **Pydantic**, as it has <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">internal support for `dataclasses`</a>. +This is still supported thanks to **Pydantic**, as it has <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">internal support for `dataclasses`</a>. So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses. @@ -91,7 +91,7 @@ Check the in-code annotation tips above to see more specific details. You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc. -To learn more, check the <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/" class="external-link" target="_blank">Pydantic docs about dataclasses</a>. +To learn more, check the <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/" class="external-link" target="_blank">Pydantic docs about dataclasses</a>. ## Version diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 03429b187..fb7a6d917 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -36,7 +36,7 @@ This part is pretty normal, most of the code is probably already familiar to you ``` !!! tip - The `callback_url` query parameter uses a Pydantic <a href="https://pydantic-docs.helpmanual.io/usage/types/#urls" class="external-link" target="_blank">URL</a> type. + The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">URL</a> type. The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 70bbcac91..d351c4e0b 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -342,7 +342,7 @@ Now APIStar is a set of tools to validate OpenAPI specifications, not a web fram ## Used by **FastAPI** -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints. diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 6f13b03bb..6f0e74b3d 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -179,7 +179,7 @@ With **FastAPI** you get all of **Starlette**'s features (as FastAPI is just Sta ## Pydantic features -**FastAPI** is fully compatible with (and based on) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. So, any additional Pydantic code you have, will also work. +**FastAPI** is fully compatible with (and based on) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. So, any additional Pydantic code you have, will also work. Including external libraries also based on Pydantic, as <abbr title="Object-Relational Mapper">ORM</abbr>s, <abbr title="Object-Document Mapper">ODM</abbr>s for databases. diff --git a/docs/en/docs/history-design-future.md b/docs/en/docs/history-design-future.md index 9db1027c2..7824fb080 100644 --- a/docs/en/docs/history-design-future.md +++ b/docs/en/docs/history-design-future.md @@ -54,7 +54,7 @@ All in a way that provided the best development experience for all the developer ## Requirements -After testing several alternatives, I decided that I was going to use <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a> for its advantages. +After testing several alternatives, I decided that I was going to use <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a> for its advantages. Then I contributed to it, to make it fully compliant with JSON Schema, to support different ways to define constraint declarations, and to improve editor support (type checks, autocompletion) based on the tests in several editors. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 10430f723..86b0c699b 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -129,7 +129,7 @@ Python 3.8+ FastAPI stands on the shoulders of giants: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> for the data parts. ## Installation diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index cdd22ea4a..51db744ff 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -434,7 +434,7 @@ It doesn't mean "`one_person` is the **class** called `Person`". ## Pydantic models -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> is a Python library to perform data validation. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> is a Python library to perform data validation. You declare the "shape" of the data as classes with attributes. @@ -465,14 +465,14 @@ An example from the official Pydantic docs: ``` !!! info - To learn more about <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, check its docs</a>. + To learn more about <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, check its docs</a>. **FastAPI** is all based on Pydantic. You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. !!! tip - Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. + Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. ## Type Hints with Metadata Annotations diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 99d36bae9..279356f24 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -3486,7 +3486,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * Upgrade Pydantic supported version to `0.29.0`. * New supported version range is `"pydantic >=0.28,<=0.29.0"`. - * This adds support for Pydantic [Generic Models](https://pydantic-docs.helpmanual.io/#generic-models), kudos to [@dmontagu](https://github.com/dmontagu). + * This adds support for Pydantic [Generic Models](https://docs.pydantic.dev/latest/#generic-models), kudos to [@dmontagu](https://github.com/dmontagu). * PR [#344](https://github.com/tiangolo/fastapi/pull/344). ## 0.30.1 diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 7058d4ad0..4c199f028 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -192,7 +192,7 @@ Again, doing just that declaration, with **FastAPI** you get: Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`. -To see all the options you have, checkout the docs for <a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">Pydantic's exotic types</a>. You will see some examples in the next chapter. +To see all the options you have, checkout the docs for <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic's exotic types</a>. You will see some examples in the next chapter. For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`: diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 67ba48f1e..f9af42938 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -6,7 +6,7 @@ A **request** body is data sent by the client to your API. A **response** body i Your API almost always has to send a **response** body. But clients don't necessarily need to send **request** bodies all the time. -To declare a **request** body, you use <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> models with all their power and benefits. +To declare a **request** body, you use <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> models with all their power and benefits. !!! info To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`. diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index fd7a99af3..e705a18e4 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ Here are some of the additional data types you can use: * `datetime.timedelta`: * A Python `datetime.timedelta`. * In requests and responses will be represented as a `float` of total seconds. - * Pydantic also allows representing it as a "ISO 8601 time diff encoding", <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders" class="external-link" target="_blank">see the docs for more info</a>. + * Pydantic also allows representing it as a "ISO 8601 time diff encoding", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">see the docs for more info</a>. * `frozenset`: * In requests and responses, treated the same as a `set`: * In requests, a list will be read, eliminating duplicates and converting it to a `set`. diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index ad253a336..49b00c730 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -184,7 +184,7 @@ It will be defined in OpenAPI with `anyOf`. To do that, use the standard Python type hint <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: !!! note - When defining a <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a>, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. + When defining a <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. === "Python 3.10+" diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 7d521696d..98ac55d1f 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -163,7 +163,7 @@ path -> item_id !!! warning These are technical details that you might skip if it's not important for you now. -`RequestValidationError` is a sub-class of Pydantic's <a href="https://pydantic-docs.helpmanual.io/usage/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. +`RequestValidationError` is a sub-class of Pydantic's <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. **FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log. diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index 847b56334..6246d6680 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -95,7 +95,7 @@ The same way, there are many compatible tools. Including code generation tools f ## Pydantic -All the data validation is performed under the hood by <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, so you get all the benefits from it. And you know you are in good hands. +All the data validation is performed under the hood by <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, so you get all the benefits from it. And you know you are in good hands. You can use the same type declarations with `str`, `float`, `bool` and many other complex data types. diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 7a9bc4875..24784efad 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -500,7 +500,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t ``` !!! tip - Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. + Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. !!! tip Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`. diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index d5683ac7f..0e6292629 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -383,7 +383,7 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. !!! info - FastAPI uses Pydantic model's `.dict()` with <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this. + FastAPI uses Pydantic model's `.dict()` with <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this. !!! info You can also use: @@ -391,7 +391,7 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - as described in <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`. + as described in <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`. #### Data with values for fields with defaults diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 70d9482df..1a2000f02 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -338,7 +338,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class. -This <a href="https://pydantic-docs.helpmanual.io/usage/model_config/" class="external-link" target="_blank">`Config`</a> class is used to provide configurations to Pydantic. +This <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">`Config`</a> class is used to provide configurations to Pydantic. In the `Config` class, set the attribute `orm_mode = True`. diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index 1496628d1..7623d8eb1 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -179,7 +179,7 @@ Con **FastAPI** obtienes todas las características de **Starlette** (porque Fas ## Características de Pydantic -**FastAPI** está basado y es completamente compatible con <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Tanto así, que cualquier código de Pydantic que tengas también funcionará. +**FastAPI** está basado y es completamente compatible con <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Tanto así, que cualquier código de Pydantic que tengas también funcionará. Esto incluye a librerías externas basadas en Pydantic como <abbr title="Object-Relational Mapper">ORM</abbr>s y <abbr title="Object-Document Mapper">ODM</abbr>s para bases de datos. diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 28b7f4d1b..b3d9c8bf2 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -111,7 +111,7 @@ Python 3.8+ FastAPI está sobre los hombros de gigantes: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> para las partes web. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> para las partes de datos. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> para las partes de datos. ## Instalación diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index b83cbe3f5..89edbb31e 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -237,7 +237,7 @@ Una vez más tendrás todo el soporte del editor: ## Modelos de Pydantic -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> es una library de Python para llevar a cabo validación de datos. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> es una library de Python para llevar a cabo validación de datos. Tú declaras la "forma" de los datos mediante clases con atributos. @@ -254,7 +254,7 @@ Tomado de la documentación oficial de Pydantic: ``` !!! info "Información" - Para aprender más sobre <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic mira su documentación</a>. + Para aprender más sobre <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic mira su documentación</a>. **FastAPI** está todo basado en Pydantic. diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 765ae4140..7faa92f51 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ De la misma manera hay muchas herramientas compatibles. Incluyendo herramientas ## Pydantic -Toda la validación de datos es realizada tras bastidores por <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos. +Toda la validación de datos es realizada tras bastidores por <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos. Puedes usar las mismas declaraciones de tipos con `str`, `float`, `bool` y otros tipos de datos más complejos. diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md index 3040ce3dd..58c34b7fc 100644 --- a/docs/fa/docs/features.md +++ b/docs/fa/docs/features.md @@ -182,7 +182,7 @@ FastAPI شامل یک سیستم <abbr title='همچنین به عنوان "comp ## ویژگی های Pydantic -**FastAPI** کاملا (و براساس) با <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a> سازگار است. بنابراین هرکد Pydantic اضافی که داشته باشید، نیز کار خواهد کرد. +**FastAPI** کاملا (و براساس) با <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a> سازگار است. بنابراین هرکد Pydantic اضافی که داشته باشید، نیز کار خواهد کرد. از جمله کتابخانه های خارجی نیز مبتنی بر Pydantic میتوان به <abbr title="Object-Relational Mapper">ORM</abbr> و <abbr title="Object-Document Mapper">ODM</abbr> ها برای دیتابیس ها اشاره کرد. diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index b267eef23..e5231ec8d 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -111,7 +111,7 @@ FastAPI یک وب فریمورک مدرن و سریع (با کارایی با FastAPI مبتنی بر ابزارهای قدرتمند زیر است: * فریمورک <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> برای بخش وب. -* کتابخانه <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> برای بخش داده. +* کتابخانه <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> برای بخش داده. ## نصب diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md index 8e58a3dfa..a64edd671 100644 --- a/docs/fr/docs/alternatives.md +++ b/docs/fr/docs/alternatives.md @@ -371,7 +371,7 @@ Exister. ## Utilisés par **FastAPI** -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les Python type hints. diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index ce7508d27..1457df2a5 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -174,7 +174,7 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Starlette** (FastAP ## Fonctionnalités de Pydantic -**FastAPI** est totalement compatible avec (et basé sur) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Le code utilisant Pydantic que vous ajouterez fonctionnera donc aussi. +**FastAPI** est totalement compatible avec (et basé sur) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Le code utilisant Pydantic que vous ajouterez fonctionnera donc aussi. Inclus des librairies externes basées, aussi, sur Pydantic, servent d'<abbr title="Object-Relational Mapper">ORM</abbr>s, <abbr title="Object-Document Mapper">ODM</abbr>s pour les bases de données. diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md index b77664be6..beb649121 100644 --- a/docs/fr/docs/history-design-future.md +++ b/docs/fr/docs/history-design-future.md @@ -54,7 +54,7 @@ Le tout de manière à offrir la meilleure expérience de développement à tous ## Exigences -Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a> pour ses avantages. +Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a> pour ses avantages. J'y ai ensuite contribué, pour le rendre entièrement compatible avec JSON Schema, pour supporter différentes manières de définir les déclarations de contraintes, et pour améliorer le support des éditeurs (vérifications de type, autocomplétion) sur la base des tests effectués dans plusieurs éditeurs. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 3a757409f..bc3ae3c06 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -120,7 +120,7 @@ Python 3.8+ FastAPI repose sur les épaules de géants : * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> pour les parties web. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> pour les parties données. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> pour les parties données. ## Installation diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index f49fbafd3..4232633e3 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -265,7 +265,7 @@ Et vous aurez accès, encore une fois, au support complet offert par l'éditeur ## Les modèles Pydantic -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> est une bibliothèque Python pour effectuer de la validation de données. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> est une bibliothèque Python pour effectuer de la validation de données. Vous déclarez la forme de la donnée avec des classes et des attributs. @@ -282,7 +282,7 @@ Extrait de la documentation officielle de **Pydantic** : ``` !!! info - Pour en savoir plus à propos de <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, allez jeter un coup d'oeil à sa documentation</a>. + Pour en savoir plus à propos de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, allez jeter un coup d'oeil à sa documentation</a>. **FastAPI** est basé entièrement sur **Pydantic**. diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index 89720c973..ae952405c 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -6,7 +6,7 @@ Le corps d'une **requête** est de la donnée envoyée par le client à votre AP Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un client n'a pas toujours à envoyer un corps de **requête**. -Pour déclarer un corps de **requête**, on utilise les modèles de <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> en profitant de tous leurs avantages et fonctionnalités. +Pour déclarer un corps de **requête**, on utilise les modèles de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> en profitant de tous leurs avantages et fonctionnalités. !!! info Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 894d62dd4..817545c1c 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -106,7 +106,7 @@ pour de nombreux langages. ## Pydantic -Toute la validation de données est effectué en arrière-plan avec <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, +Toute la validation de données est effectué en arrière-plan avec <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, dont vous bénéficierez de tous les avantages. Vous savez donc que vous êtes entre de bonnes mains. ## L'ordre importe diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index e404baa59..335a22743 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -115,7 +115,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג FastAPI עומדת על כתפי ענקיות: - <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> לחלקי הרשת. -- <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> לחלקי המידע. +- <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> לחלקי המידע. ## התקנה diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 3bc3724e2..75ea88c4d 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -120,7 +120,7 @@ Python 3.8+ A FastAPI óriások vállán áll: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> a webes részekhez. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> az adat részekhez. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> az adat részekhez. ## Telepítés diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 0b7a896e1..a69008d2b 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -115,7 +115,7 @@ Python 3.6+ FastAPI è basata su importanti librerie: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> per le parti web. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> per le parti dei dati. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> per le parti dei dati. ## Installazione diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index ca6b29a07..ce4b36408 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -342,7 +342,7 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ ## **FastAPI**が利用しているもの -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydanticは、Pythonの型ヒントを元にデータのバリデーション、シリアライゼーション、 (JSON Schemaを使用した) ドキュメントを定義するライブラリです。 diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 854c0764c..98c59e7c4 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -177,7 +177,7 @@ FastAPIには非常に使いやすく、非常に強力な<abbr title='also know ## Pydanticの特徴 -**FastAPI**は<a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic </strong></a>と完全に互換性があります(そしてベースになっています)。したがって、追加のPydanticコードがあれば、それも機能します。 +**FastAPI**は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic </strong></a>と完全に互換性があります(そしてベースになっています)。したがって、追加のPydanticコードがあれば、それも機能します。 データベースのために<abbr title = "Object-Relational Mapper">ORM</abbr>sや、<abbr title = "Object-Document Mapper">ODM</abbr>sなどの、Pydanticに基づく外部ライブラリを備えています。 diff --git a/docs/ja/docs/history-design-future.md b/docs/ja/docs/history-design-future.md index d0d1230c4..5d53cf77a 100644 --- a/docs/ja/docs/history-design-future.md +++ b/docs/ja/docs/history-design-future.md @@ -55,7 +55,7 @@ ## 要件 -いくつかの代替手法を試したあと、私は<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a>の強みを利用することを決めました。 +いくつかの代替手法を試したあと、私は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a>の強みを利用することを決めました。 そして、JSON Schemaに完全に準拠するようにしたり、制約宣言を定義するさまざまな方法をサポートしたり、いくつかのエディターでのテストに基づいてエディターのサポート (型チェック、自動補完) を改善するために貢献しました。 diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 84cb48308..4f66b1a40 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -112,7 +112,7 @@ Python 3.8+ FastAPI は巨人の肩の上に立っています。 - Web の部分は<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> -- データの部分は<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +- データの部分は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> ## インストール diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index bbfef2adf..f8e02fdc3 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -266,7 +266,7 @@ John Doe ## Pydanticのモデル -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> はデータ検証を行うためのPythonライブラリです。 +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> はデータ検証を行うためのPythonライブラリです。 データの「形」を属性付きのクラスとして宣言します。 @@ -283,7 +283,7 @@ Pydanticの公式ドキュメントから引用: ``` !!! info "情報" - Pydanticについてより学びたい方は<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">ドキュメントを参照してください</a>. + Pydanticについてより学びたい方は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">ドキュメントを参照してください</a>. **FastAPI** はすべてPydanticをベースにしています。 diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 7f916c47a..092e25798 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -118,7 +118,7 @@ Pydanticモデルの各属性には型があります。 `str`や`int`、`float`のような通常の単数型の他にも、`str`を継承したより複雑な単数型を使うこともできます。 -すべてのオプションをみるには、<a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">Pydanticのエキゾチック な型</a>のドキュメントを確認してください。次の章でいくつかの例をみることができます。 +すべてのオプションをみるには、<a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydanticのエキゾチック な型</a>のドキュメントを確認してください。次の章でいくつかの例をみることができます。 例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index d2559205b..12332991d 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -6,7 +6,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければなりません。しかし、クライアントは必ずしも **リクエスト** ボディを送らなければいけないわけではありません。 -**リクエスト** ボディを宣言するために <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> モデルを使用します。そして、その全てのパワーとメリットを利用します。 +**リクエスト** ボディを宣言するために <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> モデルを使用します。そして、その全てのパワーとメリットを利用します。 !!! info "情報" データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 diff --git a/docs/ja/docs/tutorial/extra-data-types.md b/docs/ja/docs/tutorial/extra-data-types.md index a152e0322..c0fdbd58c 100644 --- a/docs/ja/docs/tutorial/extra-data-types.md +++ b/docs/ja/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * Pythonの`datetime.timedelta`です。 * リクエストとレスポンスでは合計秒数の`float`で表現されます。 - * Pydanticでは「ISO 8601 time diff encoding」として表現することも可能です。<a href="https://pydantic-docs.helpmanual.io/#json-serialisation" class="external-link" target="_blank">詳細はドキュメントを参照してください</a>。 + * Pydanticでは「ISO 8601 time diff encoding」として表現することも可能です。<a href="https://docs.pydantic.dev/latest/concepts/serialization/" class="external-link" target="_blank">詳細はドキュメントを参照してください</a>。 * `frozenset`: * リクエストとレスポンスでは`set`と同じように扱われます: * リクエストでは、リストが読み込まれ、重複を排除して`set`に変換されます。 @@ -50,7 +50,7 @@ * Pythonの標準的な`Decimal`です。 * リクエストやレスポンスでは`float`と同じように扱います。 -* Pydanticの全ての有効な型はこちらで確認できます: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">Pydantic data types</a>。 +* Pydanticの全ての有効な型はこちらで確認できます: <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic data types</a>。 ## 例 ここでは、上記の型のいくつかを使用したパラメータを持つ*path operation*の例を示します。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index ec36e9880..0b95cae0f 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -163,7 +163,7 @@ path -> item_id !!! warning "注意" これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 -`RequestValidationError`はPydanticの<a href="https://pydantic-docs.helpmanual.io/#error-handling" class="external-link" target="_blank">`ValidationError`</a>のサブクラスです。 +`RequestValidationError`はPydanticの<a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>のサブクラスです。 **FastAPI** は`response_model`でPydanticモデルを使用していて、データにエラーがあった場合、ログにエラーが表示されるようにこれを使用しています。 diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index 66de05afb..b395dc41d 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー ## Pydantic -すべてのデータバリデーションは <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。 +すべてのデータバリデーションは <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。 `str`、 `float` 、 `bool` および他の多くの複雑なデータ型を型宣言に使用できます。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index 749b33061..b8b6978d4 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -122,7 +122,7 @@ FastAPIは`response_model`を使って以下のことをします: ``` !!! info "情報" - FastAPIはこれをするために、Pydanticモデルの`.dict()`を<a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">その`exclude_unset`パラメータ</a>で使用しています。 + FastAPIはこれをするために、Pydanticモデルの`.dict()`を<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">その`exclude_unset`パラメータ</a>で使用しています。 !!! info "情報" 以下も使用することができます: @@ -130,7 +130,7 @@ FastAPIは`response_model`を使って以下のことをします: * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - `exclude_defaults`と`exclude_none`については、<a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。 + `exclude_defaults`と`exclude_none`については、<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。 #### デフォルト値を持つフィールドの値を持つデータ diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index 3102a4936..d96163b82 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -8,7 +8,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 ## Pydanticの`schema_extra` -<a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydanticのドキュメント: スキーマのカスタマイズ</a>で説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: +<a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Pydanticのドキュメント: スキーマのカスタマイズ</a>で説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: ```Python hl_lines="15 16 17 18 19 20 21 22 23" {!../../../docs_src/schema_extra_example/tutorial001.py!} diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index 42a3ff172..54479165e 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -179,7 +179,7 @@ FastAPI는 사용하기 매우 간편하지만, 엄청난 <abbr title='"컴포 ## Pydantic 기능 -**FastAPI**는 <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>을 기반으로 하며 Pydantic과 완벽하게 호환됩니다. 그래서 어느 추가적인 Pydantic 코드를 여러분이 가지고 있든 작동할 것입니다. +**FastAPI**는 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>을 기반으로 하며 Pydantic과 완벽하게 호환됩니다. 그래서 어느 추가적인 Pydantic 코드를 여러분이 가지고 있든 작동할 것입니다. Pydantic을 기반으로 하는, 데이터베이스를 위한 <abbr title="Object-Relational Mapper">ORM</abbr>, <abbr title="Object-Document Mapper">ODM</abbr>을 포함한 외부 라이브러리를 포함합니다. diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 09f368ce9..eeadc0363 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -112,7 +112,7 @@ Python 3.8+ FastAPI는 거인들의 어깨 위에 서 있습니다: * 웹 부분을 위한 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. -* 데이터 부분을 위한 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>. +* 데이터 부분을 위한 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>. ## 설치 diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 16b93a7a9..267ce6c7e 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -265,7 +265,7 @@ John Doe ## Pydantic 모델 -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>은 데이터 검증(Validation)을 위한 파이썬 라이브러리입니다. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>은 데이터 검증(Validation)을 위한 파이썬 라이브러리입니다. 당신은 속성들을 포함한 클래스 형태로 "모양(shape)"을 선언할 수 있습니다. @@ -282,7 +282,7 @@ Pydantic 공식 문서 예시: ``` !!! info "정보" - Pydantic<에 대해 더 배우고 싶다면 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a> + Pydantic<에 대해 더 배우고 싶다면 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a> **FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다. diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index 7b41aa35b..edf1a5f77 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -117,7 +117,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. `str`, `int`, `float` 등과 같은 단일 타입과는 별개로, `str`을 상속하는 더 복잡한 단일 타입을 사용할 수 있습니다. -모든 옵션을 보려면, <a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">Pydantic's exotic types</a> 문서를 확인하세요. 다음 장에서 몇가지 예제를 볼 수 있습니다. +모든 옵션을 보려면, <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic's exotic types</a> 문서를 확인하세요. 다음 장에서 몇가지 예제를 볼 수 있습니다. 예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 931728572..8b98284bb 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -6,7 +6,7 @@ 여러분의 API는 대부분의 경우 **응답** 본문을 보내야 합니다. 하지만 클라이언트는 **요청** 본문을 매 번 보낼 필요가 없습니다. -**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 모델을 사용합니다. +**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 모델을 사용합니다. !!! 정보 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 6d5d37352..a75c3cc8c 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ ## Pydantic -모든 데이터 검증은 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>에 의해 내부적으로 수행되므로 이로 인한 이점을 모두 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다. +모든 데이터 검증은 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>에 의해 내부적으로 수행되므로 이로 인한 이점을 모두 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다. `str`, `float`, `bool`, 그리고 다른 여러 복잡한 데이터 타입 선언을 할 수 있습니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index 0c9d5c16e..feff88a42 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -122,7 +122,7 @@ FastAPI는 이 `response_model`를 사용하여: ``` !!! info "정보" - FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank"> `exclude_unset` 매개변수</a>를 사용합니다. + FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank"> `exclude_unset` 매개변수</a>를 사용합니다. !!! info "정보" 아래 또한 사용할 수 있습니다: @@ -130,7 +130,7 @@ FastAPI는 이 `response_model`를 사용하여: * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic 문서</a>에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. + <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 문서</a>에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. #### 기본값이 있는 필드를 갖는 값의 데이터 diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index 13f6d2ad7..a6435977c 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -174,7 +174,7 @@ Dzięki **FastAPI** otrzymujesz wszystkie funkcje **Starlette** (ponieważ FastA ## Cechy Pydantic -**FastAPI** jest w pełni kompatybilny z (oraz bazuje na) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Tak więc każdy dodatkowy kod Pydantic, który posiadasz, również będzie działał. +**FastAPI** jest w pełni kompatybilny z (oraz bazuje na) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Tak więc każdy dodatkowy kod Pydantic, który posiadasz, również będzie działał. Wliczając w to zewnętrzne biblioteki, również oparte o Pydantic, takie jak <abbr title="Mapowanie obiektowo-relacyjne. Po angielsku: Object-Relational Mapper">ORM</abbr>, <abbr title="Object-Document Mapper">ODM</abbr> dla baz danych. diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 828b13a05..ab33bfb9c 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -111,7 +111,7 @@ Python 3.8+ FastAPI oparty jest na: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> dla części webowej. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> dla części obsługujących dane. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> dla części obsługujących dane. ## Instalacja diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index 61ee4f900..ba721536f 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -340,7 +340,7 @@ Agora APIStar é um conjunto de ferramentas para validar especificações OpenAP ## Usados por **FastAPI** -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydantic é uma biblioteca para definir validação de dados, serialização e documentação (usando JSON Schema) baseado nos Python _type hints_. diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index 83bd0ea92..64efeeae1 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -175,7 +175,7 @@ Com **FastAPI**, você terá todos os recursos do **Starlette** (já que FastAPI ## Recursos do Pydantic -**FastAPI** é totalmente compatível com (e baseado no) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Então, qualquer código Pydantic adicional que você tiver, também funcionará. +**FastAPI** é totalmente compatível com (e baseado no) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Então, qualquer código Pydantic adicional que você tiver, também funcionará. Incluindo bibliotecas externas também baseadas no Pydantic, como <abbr title="Object-Relational Mapper">ORM</abbr>s e <abbr title="Object-Document Mapper">ODM</abbr>s para bancos de dados. diff --git a/docs/pt/docs/history-design-future.md b/docs/pt/docs/history-design-future.md index 45427ec63..a7a177660 100644 --- a/docs/pt/docs/history-design-future.md +++ b/docs/pt/docs/history-design-future.md @@ -54,7 +54,7 @@ Tudo de uma forma que oferecesse a melhor experiência de desenvolvimento para t ## Requisitos -Após testar várias alternativas, eu decidi que usaria o <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a> por suas vantagens. +Após testar várias alternativas, eu decidi que usaria o <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a> por suas vantagens. Então eu contribuí com ele, para deixá-lo completamente de acordo com o JSON Schema, para dar suporte a diferentes maneiras de definir declarações de restrições, e melhorar o suporte a editores (conferências de tipos, auto completações) baseado nos testes em vários editores. diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 390247ec9..05786a0aa 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -105,7 +105,7 @@ Python 3.8+ FastAPI está nos ombros de gigantes: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> para as partes web. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> para a parte de dados. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> para a parte de dados. ## Instalação diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 9f12211c7..52b2dad8e 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -266,7 +266,7 @@ E então, novamente, você recebe todo o suporte do editor: ## Modelos Pydantic -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank"> Pydantic </a> é uma biblioteca Python para executar a validação de dados. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank"> Pydantic </a> é uma biblioteca Python para executar a validação de dados. Você declara a "forma" dos dados como classes com atributos. @@ -283,7 +283,7 @@ Retirado dos documentos oficiais dos Pydantic: ``` !!! info "Informação" - Para saber mais sobre o <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank"> Pydantic, verifique seus documentos </a>. + Para saber mais sobre o <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"> Pydantic, verifique seus documentos </a>. **FastAPI** é todo baseado em Pydantic. diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index 8ab77173e..e039b09b2 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -121,7 +121,7 @@ Novamente, apenas fazendo essa declaração, com o **FastAPI**, você ganha: Além dos tipos singulares normais como `str`, `int`, `float`, etc. Você também pode usar tipos singulares mais complexos que herdam de `str`. -Para ver todas as opções possíveis, cheque a documentação para os<a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">tipos exoticos do Pydantic</a>. Você verá alguns exemplos no próximo capitulo. +Para ver todas as opções possíveis, cheque a documentação para os<a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">tipos exoticos do Pydantic</a>. Você verá alguns exemplos no próximo capitulo. Por exemplo, no modelo `Image` nós temos um campo `url`, nós podemos declara-lo como um `HttpUrl` do Pydantic invés de como uma `str`: diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 99e05ab77..5901b8414 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -6,7 +6,7 @@ O corpo da **requisição** é a informação enviada pelo cliente para sua API. Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não necessariamente precisam enviar um corpo em toda **requisição**. -Para declarar um corpo da **requisição**, você utiliza os modelos do <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> com todos os seus poderes e benefícios. +Para declarar um corpo da **requisição**, você utiliza os modelos do <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> com todos os seus poderes e benefícios. !!! info "Informação" Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index e4b9913dc..5d50d8942 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: * `datetime.timedelta`: * O `datetime.timedelta` do Python. * Em requisições e respostas será representado como um `float` de segundos totais. - * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", <a href="https://pydantic-docs.helpmanual.io/#json-serialisation" class="external-link" target="_blank">cheque a documentação para mais informações</a>. + * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", <a href="https://docs.pydantic.dev/latest/concepts/serialization/" class="external-link" target="_blank">cheque a documentação para mais informações</a>. * `frozenset`: * Em requisições e respostas, será tratado da mesma forma que um `set`: * Nas requisições, uma lista será lida, eliminando duplicadas e convertendo-a em um `set`. @@ -49,7 +49,7 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: * `Decimal`: * O `Decimal` padrão do Python. * Em requisições e respostas será representado como um `float`. -* Você pode checar todos os tipos de dados válidos do Pydantic aqui: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">Tipos de dados do Pydantic</a>. +* Você pode checar todos os tipos de dados válidos do Pydantic aqui: <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Tipos de dados do Pydantic</a>. ## Exemplo diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 1343a3ae4..3b1f6ee54 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -179,7 +179,7 @@ Isso será definido no OpenAPI com `anyOf`. Para fazer isso, use a dica de tipo padrão do Python <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: !!! note - Ao definir um <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a>, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. + Ao definir um <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. === "Python 3.8 and above" diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md index 97a2e3eac..d9f3d6782 100644 --- a/docs/pt/docs/tutorial/handling-errors.md +++ b/docs/pt/docs/tutorial/handling-errors.md @@ -160,7 +160,7 @@ path -> item_id !!! warning "Aviso" Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. -`RequestValidationError` é uma subclasse do <a href="https://pydantic-docs.helpmanual.io/#error-handling" class="external-link" target="_blank">`ValidationError`</a> existente no Pydantic. +`RequestValidationError` é uma subclasse do <a href="https://docs.pydantic.dev/latest/#error-handling" class="external-link" target="_blank">`ValidationError`</a> existente no Pydantic. **FastAPI** faz uso dele para que você veja o erro no seu log, caso você utilize um modelo de Pydantic em `response_model`, e seus dados tenham erro. diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index cd8c18858..be2b7f7a4 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ Da mesma forma, existem muitas ferramentas compatíveis. Incluindo ferramentas d ## Pydantic -Toda a validação de dados é feita por baixo dos panos pelo <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, então você tem todos os benefícios disso. E assim você sabe que está em boas mãos. +Toda a validação de dados é feita por baixo dos panos pelo <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, então você tem todos os benefícios disso. E assim você sabe que está em boas mãos. Você pode usar as mesmas declarações de tipo com `str`, `float`, `bool` e muitos outros tipos complexos de dados. diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index 0355450fa..d04dc1a26 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -6,7 +6,7 @@ Aqui estão várias formas de se fazer isso. ## `schema_extra` do Pydantic -Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em <a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Documentação do Pydantic: Schema customization</a>: +Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em <a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Documentação do Pydantic: Schema customization</a>: ```Python hl_lines="15-23" {!../../../docs_src/schema_extra_example/tutorial001.py!} diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index 9e3c497d1..24a45fa55 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -384,7 +384,7 @@ Hug был одним из первых фреймворков, реализов ## Что используется в **FastAPI** -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydantic - это библиотека для валидации данных, сериализации и документирования (используя JSON Schema), основываясь на подсказках типов Python, что делает его чрезвычайно интуитивным. diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index d67a9654b..110c7d31e 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -177,7 +177,7 @@ FastAPI включает в себя чрезвычайно простую в и ## Особенности и возможности Pydantic -**FastAPI** основан на <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a> и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать. +**FastAPI** основан на <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a> и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать. Включая внешние библиотеки, также основанные на Pydantic, такие как: <abbr title="Object-Relational Mapper">ORM'ы</abbr>, <abbr title="Object-Document Mapper">ODM'ы</abbr> для баз данных. diff --git a/docs/ru/docs/history-design-future.md b/docs/ru/docs/history-design-future.md index 2a5e428b1..e9572a6d6 100644 --- a/docs/ru/docs/history-design-future.md +++ b/docs/ru/docs/history-design-future.md @@ -52,7 +52,7 @@ ## Зависимости -Протестировав несколько вариантов, я решил, что в качестве основы буду использовать <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a> и его преимущества. +Протестировав несколько вариантов, я решил, что в качестве основы буду использовать <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a> и его преимущества. По моим предложениям был изменён код этого фреймворка, чтобы сделать его полностью совместимым с JSON Schema, поддержать различные способы определения ограничений и улучшить помощь редакторов (проверки типов, автозаполнение). diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 6e88b496f..477567af6 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -114,7 +114,7 @@ Python 3.8+ FastAPI стоит на плечах гигантов: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> для части связанной с вебом. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> для части связанной с данными. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> для части связанной с данными. ## Установка diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index 7523083c8..3c8492c67 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -265,7 +265,7 @@ John Doe ## Pydantic-модели -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> является Python-библиотекой для выполнения валидации данных. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> является Python-библиотекой для выполнения валидации данных. Вы объявляете «форму» данных как классы с атрибутами. @@ -282,7 +282,7 @@ John Doe ``` !!! info - Чтобы узнать больше о <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, читайте его документацию</a>. + Чтобы узнать больше о <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, читайте его документацию</a>. **FastAPI** целиком основан на Pydantic. diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index bbf9b7685..51a32ba56 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -192,7 +192,7 @@ my_list: List[str] Помимо обычных простых типов, таких как `str`, `int`, `float`, и т.д. Вы можете использовать более сложные базовые типы, которые наследуются от типа `str`. -Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с документацией <a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">по необычным типам Pydantic</a>. Вы увидите некоторые примеры в следующей главе. +Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с документацией <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">по необычным типам Pydantic</a>. Вы увидите некоторые примеры в следующей главе. Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index c03d40c3f..96f80af06 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -6,7 +6,7 @@ Ваш API почти всегда отправляет тело **ответа**. Но клиентам не обязательно всегда отправлять тело **запроса**. -Чтобы объявить тело **запроса**, необходимо использовать модели <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, со всей их мощью и преимуществами. +Чтобы объявить тело **запроса**, необходимо использовать модели <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, со всей их мощью и преимуществами. !!! info "Информация" Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index 0f613a6b2..d4727e2d4 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * Встроенный в Python `datetime.timedelta`. * В запросах и ответах будет представлен в виде общего количества секунд типа `float`. - * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders" class="external-link" target="_blank">см. документацию для получения дополнительной информации</a>. + * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">см. документацию для получения дополнительной информации</a>. * `frozenset`: * В запросах и ответах обрабатывается так же, как и `set`: * В запросах будет прочитан список, исключены дубликаты и преобразован в `set`. @@ -49,7 +49,7 @@ * `Decimal`: * Встроенный в Python `Decimal`. * В запросах и ответах обрабатывается так же, как и `float`. -* Вы можете проверить все допустимые типы данных pydantic здесь: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">Типы данных Pydantic</a>. +* Вы можете проверить все допустимые типы данных pydantic здесь: <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Типы данных Pydantic</a>. ## Пример diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 30176b4e3..78855313d 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -179,7 +179,7 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: !!! note "Примечание" - При объявлении <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a>, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. + При объявлении <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. === "Python 3.10+" diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index f578cf198..40b6f9bc4 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -163,7 +163,7 @@ path -> item_id !!! warning "Внимание" Это технические детали, которые можно пропустить, если они не важны для вас сейчас. -`RequestValidationError` является подклассом Pydantic <a href="https://pydantic-docs.helpmanual.io/usage/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. +`RequestValidationError` является подклассом Pydantic <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. **FastAPI** использует его для того, чтобы, если вы используете Pydantic-модель в `response_model`, и ваши данные содержат ошибку, вы увидели ошибку в журнале. diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index 55b498ef0..1241e0919 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ ## Pydantic -Вся проверка данных выполняется под капотом с помощью <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>. Поэтому вы можете быть уверены в качестве обработки данных. +Вся проверка данных выполняется под капотом с помощью <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>. Поэтому вы можете быть уверены в качестве обработки данных. Вы можете использовать в аннотациях как простые типы данных, вроде `str`, `float`, `bool`, так и более сложные типы. diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index cc826b871..108aefefc 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -479,7 +479,7 @@ q: Union[str, None] = None ``` !!! tip "Подсказка" - Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">Обязательные Опциональные поля</a>. + Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Обязательные Опциональные поля</a>. ### Использование Pydantic's `Required` вместо Ellipsis (`...`) diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 38b45e2a5..9b9b60dd5 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -377,7 +377,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма ``` !!! info "Информация" - "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">с параметром `exclude_unset`</a>, чтобы достичь такого эффекта. + "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">с параметром `exclude_unset`</a>, чтобы достичь такого эффекта. !!! info "Информация" Вы также можете использовать: @@ -385,7 +385,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - как описано в <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">документации Pydantic</a> для параметров `exclude_defaults` и `exclude_none`. + как описано в <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">документации Pydantic</a> для параметров `exclude_defaults` и `exclude_none`. #### Если значение поля отличается от значения по-умолчанию diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index a13ab5935..e1011805a 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -6,7 +6,7 @@ ## Pydantic `schema_extra` -Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в <a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic документации: Настройка схемы</a>: +Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в <a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Pydantic документации: Настройка схемы</a>: === "Python 3.10+" diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md index 9c69503c9..462d8b304 100644 --- a/docs/tr/docs/alternatives.md +++ b/docs/tr/docs/alternatives.md @@ -336,7 +336,7 @@ Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bi ## **FastAPI** Tarafından Kullanılanlar -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydantic Python tip belirteçlerine dayanan; veri doğrulama, veri dönüştürme ve dökümantasyon tanımlamak (JSON Şema kullanarak) için bir kütüphanedir. diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index ef4975c59..1cda8c7fb 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -182,7 +182,7 @@ Bütün entegrasyonlar kullanımı kolay olmak üzere (zorunluluklar ile beraber ## Pydantic özellikleri -**FastAPI** ile <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a> tamamiyle uyumlu ve üzerine kurulu. Yani FastAPI üzerine ekleme yapacağınız herhangi bir Pydantic kodu da çalışacaktır. +**FastAPI** ile <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a> tamamiyle uyumlu ve üzerine kurulu. Yani FastAPI üzerine ekleme yapacağınız herhangi bir Pydantic kodu da çalışacaktır. Bunlara Pydantic üzerine kurulu <abbr title="Object-Relational Mapper">ORM</abbr> databaseler ve , <abbr title="Object-Document Mapper">ODM</abbr> kütüphaneler de dahil olmak üzere. diff --git a/docs/tr/docs/history-design-future.md b/docs/tr/docs/history-design-future.md index 950fcf37d..1dd0e637f 100644 --- a/docs/tr/docs/history-design-future.md +++ b/docs/tr/docs/history-design-future.md @@ -54,7 +54,7 @@ Hepsi, tüm geliştiriciler için en iyi geliştirme deneyimini sağlayacak şek ## Gereksinimler -Çeşitli alternatifleri test ettikten sonra, avantajlarından dolayı <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a>'i kullanmaya karar verdim. +Çeşitli alternatifleri test ettikten sonra, avantajlarından dolayı <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a>'i kullanmaya karar verdim. Sonra, JSON Schema ile tamamen uyumlu olmasını sağlamak, kısıtlama bildirimlerini tanımlamanın farklı yollarını desteklemek ve birkaç editördeki testlere dayanarak editör desteğini (tip kontrolleri, otomatik tamamlama) geliştirmek için katkıda bulundum. diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index fbde3637a..afbb27f7d 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -120,7 +120,7 @@ Python 3.8+ FastAPI iki devin omuzları üstünde duruyor: * Web tarafı için <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. -* Data tarafı için <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>. +* Data tarafı için <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>. ## Kurulum diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index 3b9ab9050..a0d32c86e 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -265,7 +265,7 @@ Ve yine bütün editör desteğini alırsınız: ## Pydantic modelleri -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> veri doğrulaması yapmak için bir Python kütüphanesidir. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> veri doğrulaması yapmak için bir Python kütüphanesidir. Verilerin "biçimini" niteliklere sahip sınıflar olarak düzenlersiniz. @@ -282,7 +282,7 @@ Resmi Pydantic dokümanlarından alınmıştır: ``` !!! info - Daha fazla şey öğrenmek için <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic'i takip edin</a>. + Daha fazla şey öğrenmek için <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic'i takip edin</a>. **FastAPI** tamamen Pydantic'e dayanmaktadır. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index cfcf881fd..c19023645 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -95,7 +95,7 @@ Aynı şekilde, farklı diller için kod türetme araçları da dahil olmak üze ## Pydantic -Tüm veri doğrulamaları <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> tarafından arka planda gerçekleştirilir, bu sayede tüm avantajlardan faydalanabilirsiniz. Böylece, emin ellerde olduğunuzu hissedebilirsiniz. +Tüm veri doğrulamaları <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> tarafından arka planda gerçekleştirilir, bu sayede tüm avantajlardan faydalanabilirsiniz. Böylece, emin ellerde olduğunuzu hissedebilirsiniz. Aynı tip tanımlamalarını `str`, `float`, `bool` ve diğer karmaşık veri tipleri ile kullanma imkanınız vardır. diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index e71257976..bdb62513e 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -340,7 +340,7 @@ Hug був одним із перших фреймворків, який реа ## Використовується **FastAPI** -### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> +### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> Pydantic — це бібліотека для визначення перевірки даних, серіалізації та документації (за допомогою схеми JSON) на основі підказок типу Python. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index afcaa8918..32f1f544a 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -115,7 +115,7 @@ Python 3.8+ FastAPI стоїть на плечах гігантів: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> для web частини. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> для частини даних. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> для частини даних. ## Вставновлення diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index 6c8e29016..e767db2fb 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -385,7 +385,7 @@ John Doe ## Pydantic моделі -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> це бібліотека Python для валідації даних. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> це бібліотека Python для валідації даних. Ви оголошуєте «форму» даних як класи з атрибутами. @@ -416,7 +416,7 @@ John Doe ``` !!! info - Щоб дізнатись більше про <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, перегляньте його документацію</a>. + Щоб дізнатись більше про <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, перегляньте його документацію</a>. **FastAPI** повністю базується на Pydantic. diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 9759e7f45..11e94e929 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -6,7 +6,7 @@ Ваш API майже завжди має надсилати тіло **відповіді**. Але клієнтам не обов’язково потрібно постійно надсилати тіла **запитів**. -Щоб оголосити тіло **запиту**, ви використовуєте <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> моделі з усією їх потужністю та перевагами. +Щоб оголосити тіло **запиту**, ви використовуєте <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> моделі з усією їх потужністю та перевагами. !!! info Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index ec5ec0d18..01852803a 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * Пайтонівський `datetime.timedelta`. * У запитах та відповідях буде представлений як `float` загальної кількості секунд. - * Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders" class="external-link" target="_blank">більше інформації дивись у документації</a>. + * Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">більше інформації дивись у документації</a>. * `frozenset`: * У запитах і відповідях це буде оброблено так само, як і `set`: * У запитах список буде зчитано, дублікати будуть видалені та він буде перетворений на `set`. @@ -49,7 +49,7 @@ * `Decimal`: * Стандартний Пайтонівський `Decimal`. * У запитах і відповідях це буде оброблено так само, як і `float`. -* Ви можете перевірити всі дійсні типи даних Pydantic тут: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">типи даних Pydantic</a>. +* Ви можете перевірити всі дійсні типи даних Pydantic тут: <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">типи даних Pydantic</a>. ## Приклад diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md index 306aeb359..9edb1c8fa 100644 --- a/docs/vi/docs/features.md +++ b/docs/vi/docs/features.md @@ -172,7 +172,7 @@ Với **FastAPI**, bạn có được tất cả những tính năng của **Sta ## Tính năng của Pydantic -**FastAPI** tương thích đầy đủ với (và dựa trên) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Do đó, bất kì code Pydantic nào bạn thêm vào cũng sẽ hoạt động. +**FastAPI** tương thích đầy đủ với (và dựa trên) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Do đó, bất kì code Pydantic nào bạn thêm vào cũng sẽ hoạt động. Bao gồm các thư viện bên ngoài cũng dựa trên Pydantic, như <abbr title="Object-Relational Mapper">ORM</abbr>s, <abbr title="Object-Document Mapper">ODM</abbr>s cho cơ sở dữ liệu. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index a3dec4be7..3ade853e2 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -121,7 +121,7 @@ Python 3.8+ FastAPI đứng trên vai những người khổng lồ: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> cho phần web. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> cho phần data. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> cho phần data. ## Cài đặt diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 4999caac3..b2a399aa5 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -440,7 +440,7 @@ Nó không có nghĩa "`one_person`" là một **lớp** gọi là `Person`. ## Pydantic models -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> là một thư viện Python để validate dữ liệu hiệu năng cao. +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> là một thư viện Python để validate dữ liệu hiệu năng cao. Bạn có thể khai báo "hình dạng" của dữa liệu như là các lớp với các thuộc tính. @@ -471,14 +471,14 @@ Một ví dụ từ tài liệu chính thức của Pydantic: ``` !!! info - Để học nhiều hơn về <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, tham khảo tài liệu của nó</a>. + Để học nhiều hơn về <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, tham khảo tài liệu của nó</a>. **FastAPI** được dựa hoàn toàn trên Pydantic. Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}. !!! tip - Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. + Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. ## Type Hints với Metadata Annotations diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 9e844d44e..5684f0a6a 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -120,7 +120,7 @@ Python 3.8+ FastAPI dúró lórí àwọn èjìká tí àwọn òmíràn: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> fún àwọn ẹ̀yà ayélujára. -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> fún àwọn ẹ̀yà àkójọf'áyẹ̀wò. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> fún àwọn ẹ̀yà àkójọf'áyẹ̀wò. ## Fifi sórí ẹrọ diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index eec12dfae..9859d3c51 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -120,7 +120,7 @@ Python 3.8+ FastAPI 是站在以下巨人的肩膀上: - <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> 負責網頁的部分 -- <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 負責資料的部分 +- <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 負責資料的部分 ## 安裝 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 76070fb7f..d793b9c7f 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -127,7 +127,7 @@ Hello World from Python ## Pydantic 的 `Settings` -幸运的是,Pydantic 提供了一个很好的工具来处理来自环境变量的设置,即<a href="https://pydantic-docs.helpmanual.io/usage/settings/" class="external-link" target="_blank">Pydantic: Settings management</a>。 +幸运的是,Pydantic 提供了一个很好的工具来处理来自环境变量的设置,即<a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>。 ### 创建 `Settings` 对象 @@ -314,7 +314,7 @@ APP_NAME="ChimichangApp" 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 !!! tip - `Config` 类仅用于 Pydantic 配置。您可以在<a href="https://pydantic-docs.helpmanual.io/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>中阅读更多相关信息。 + `Config` 类仅用于 Pydantic 配置。您可以在<a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic Model Config</a>中阅读更多相关信息。 ### 使用 `lru_cache` 仅创建一次 `Settings` diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index 9fba24814..d8190032f 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -179,7 +179,7 @@ FastAPI 有一个使用非常简单,但是非常强大的<abbr title='也叫 ## Pydantic 特性 -**FastAPI** 和 <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a> 完全兼容(并基于)。所以,你有的其他的 Pydantic 代码也能正常工作。 +**FastAPI** 和 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a> 完全兼容(并基于)。所以,你有的其他的 Pydantic 代码也能正常工作。 兼容包括基于 Pydantic 的外部库, 例如用与数据库的 <abbr title="对象关系映射">ORM</abbr>s, <abbr title="对象文档映射">ODM</abbr>s。 diff --git a/docs/zh/docs/history-design-future.md b/docs/zh/docs/history-design-future.md index 56a15d003..798b8fb5f 100644 --- a/docs/zh/docs/history-design-future.md +++ b/docs/zh/docs/history-design-future.md @@ -53,7 +53,7 @@ ## 需求项 -经过测试多种备选方案,我最终决定使用 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a>,并充分利用它的优势。 +经过测试多种备选方案,我最终决定使用 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a>,并充分利用它的优势。 我甚至为它做了不少贡献,让它完美兼容了 JSON Schema,支持多种方式定义约束声明,并基于多个编辑器,改进了它对编辑器支持(类型检查、自动补全)。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 7451d1072..a480d6640 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -112,7 +112,7 @@ Python 3.8 及更高版本 FastAPI 站在以下巨人的肩膀之上: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> 负责 web 部分。 -* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 负责数据部分。 +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 负责数据部分。 ## 安装 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index 6cdb4b588..214b47611 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -237,7 +237,7 @@ John Doe ## Pydantic 模型 -<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 是一个用来用来执行数据校验的 Python 库。 +<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 是一个用来用来执行数据校验的 Python 库。 你可以将数据的"结构"声明为具有属性的类。 @@ -254,7 +254,7 @@ John Doe ``` !!! info - 想进一步了解 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic,请阅读其文档</a>. + 想进一步了解 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic,请阅读其文档</a>. 整个 **FastAPI** 建立在 Pydantic 的基础之上。 diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index c65308bef..3f519ae33 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -182,7 +182,7 @@ Pydantic 模型的每个属性都具有类型。 除了普通的单一值类型(如 `str`、`int`、`float` 等)外,你还可以使用从 `str` 继承的更复杂的单一值类型。 -要了解所有的可用选项,请查看关于 <a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">来自 Pydantic 的外部类型</a> 的文档。你将在下一章节中看到一些示例。 +要了解所有的可用选项,请查看关于 <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">来自 Pydantic 的外部类型</a> 的文档。你将在下一章节中看到一些示例。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 5cf53c0c2..3d615be39 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -6,7 +6,7 @@ 你的 API 几乎总是要发送**响应**体。但是客户端并不总是需要发送**请求**体。 -我们使用 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。 +我们使用 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。 !!! info 你不能使用 `GET` 操作(HTTP 方法)发送请求体。 diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index f4a77050c..cf39de0dd 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * 一个 Python `datetime.timedelta`. * 在请求和响应中将表示为 `float` 代表总秒数。 - * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders" class="external-link" target="_blank">查看文档了解更多信息</a>。 + * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">查看文档了解更多信息</a>。 * `frozenset`: * 在请求和响应中,作为 `set` 对待: * 在请求中,列表将被读取,消除重复,并将其转换为一个 `set`。 @@ -49,7 +49,7 @@ * `Decimal`: * 标准的 Python `Decimal`。 * 在请求和响应中被当做 `float` 一样处理。 -* 您可以在这里检查所有有效的pydantic数据类型: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">Pydantic data types</a>. +* 您可以在这里检查所有有效的pydantic数据类型: <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic data types</a>. ## 例子 diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 06427a73d..f89d58dd1 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -180,7 +180,7 @@ UserInDB( !!! note - 定义一个 <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 + 定义一个 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 === "Python 3.10+" diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index a0d66e557..701cd241e 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -179,7 +179,7 @@ path -> item_id 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 -`RequestValidationError` 是 Pydantic 的 <a href="https://pydantic-docs.helpmanual.io/usage/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a> 的子类。 +`RequestValidationError` 是 Pydantic 的 <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a> 的子类。 **FastAPI** 调用的就是 `RequestValidationError` 类,因此,如果在 `response_model` 中使用 Pydantic 模型,且数据有错误时,在日志中就会看到这个错误。 diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 1b428d662..5bb4eba80 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -93,7 +93,7 @@ ## Pydantic -所有的数据校验都由 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。 +所有的数据校验都由 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。 你可以使用同样的类型声明来声明 `str`、`float`、`bool` 以及许多其他的复合数据类型。 diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index 39253eb0d..af0428837 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -152,7 +152,7 @@ q: Union[str, None] = Query(default=None, min_length=3) ``` !!! tip - Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关<a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">必需可选字段</a>的更多信息。 + Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关<a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">必需可选字段</a>的更多信息。 ### 使用Pydantic中的`Required`代替省略号(`...`) diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index e731b6989..0f1b3b4b9 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -160,7 +160,7 @@ FastAPI 将使用此 `response_model` 来: ``` !!! info - FastAPI 通过 Pydantic 模型的 `.dict()` 配合 <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">该方法的 `exclude_unset` 参数</a> 来实现此功能。 + FastAPI 通过 Pydantic 模型的 `.dict()` 配合 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">该方法的 `exclude_unset` 参数</a> 来实现此功能。 !!! info 你还可以使用: @@ -168,7 +168,7 @@ FastAPI 将使用此 `response_model` 来: * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` - 参考 <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic 文档</a> 中对 `exclude_defaults` 和 `exclude_none` 的描述。 + 参考 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 文档</a> 中对 `exclude_defaults` 和 `exclude_none` 的描述。 #### 默认值字段有实际值的数据 diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md index ebc04da8b..ae204dc61 100644 --- a/docs/zh/docs/tutorial/schema-extra-example.md +++ b/docs/zh/docs/tutorial/schema-extra-example.md @@ -8,7 +8,7 @@ ## Pydantic `schema_extra` -您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如<a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic 文档:定制 Schema </a>中所述: +您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如<a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Pydantic 文档:定制 Schema </a>中所述: === "Python 3.10+" diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index c49374971..be0c76593 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -329,7 +329,7 @@ name: str 现在,在用于查询的 Pydantic*模型*`Item`中`User`,添加一个内部`Config`类。 -此类[`Config`](https://pydantic-docs.helpmanual.io/usage/model_config/)用于为 Pydantic 提供配置。 +此类[`Config`](https://docs.pydantic.dev/latest/api/config/)用于为 Pydantic 提供配置。 在`Config`类中,设置属性`orm_mode = True`。 diff --git a/docs_src/custom_response/tutorial006c.py b/docs_src/custom_response/tutorial006c.py index db87a9389..87c720364 100644 --- a/docs_src/custom_response/tutorial006c.py +++ b/docs_src/custom_response/tutorial006c.py @@ -6,4 +6,4 @@ app = FastAPI() @app.get("/pydantic", response_class=RedirectResponse, status_code=302) async def redirect_pydantic(): - return "https://pydantic-docs.helpmanual.io/" + return "https://docs.pydantic.dev/" diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006c.py b/tests/test_tutorial/test_custom_response/test_tutorial006c.py index 51aa1833d..2675f2a93 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial006c.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial006c.py @@ -8,7 +8,7 @@ client = TestClient(app) def test_redirect_status_code(): response = client.get("/pydantic", follow_redirects=False) assert response.status_code == 302 - assert response.headers["location"] == "https://pydantic-docs.helpmanual.io/" + assert response.headers["location"] == "https://docs.pydantic.dev/" def test_openapi_schema(): From 3aa6c8809e21267a1e5a548bd0308f30b39fd17c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 22 Mar 2024 01:42:39 +0000 Subject: [PATCH 075/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 279356f24..3608dacfb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update links to Pydantic docs to point to new website. PR [#11328](https://github.com/tiangolo/fastapi/pull/11328) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo in `docs/en/docs/tutorial/extra-models.md`. PR [#11329](https://github.com/tiangolo/fastapi/pull/11329) by [@alejsdev](https://github.com/alejsdev). * 📝 Update `project-generation.md`. PR [#11326](https://github.com/tiangolo/fastapi/pull/11326) by [@alejsdev](https://github.com/alejsdev). * 📝 Update External Links. PR [#11327](https://github.com/tiangolo/fastapi/pull/11327) by [@alejsdev](https://github.com/alejsdev). From ddff295f44a5836f179bc29c02ecf5d75149e093 Mon Sep 17 00:00:00 2001 From: Sk Imtiaz Ahmed <imtiaz101325@gmail.com> Date: Mon, 25 Mar 2024 20:11:39 +0100 Subject: [PATCH 076/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Bengali=20translat?= =?UTF-8?q?ions=20for=20`docs/bn/docs/learn/index.md`=20(#11337)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/bn/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/bn/docs/learn/index.md diff --git a/docs/bn/docs/learn/index.md b/docs/bn/docs/learn/index.md new file mode 100644 index 000000000..4e4c62038 --- /dev/null +++ b/docs/bn/docs/learn/index.md @@ -0,0 +1,5 @@ +# শিখুন + +এখানে **FastAPI** শিখার জন্য প্রাথমিক বিভাগগুলি এবং টিউটোরিয়ালগুলি রয়েছে। + +আপনি এটিকে একটি **বই**, একটি **কোর্স**, এবং FastAPI শিখার **অফিসিয়াল** এবং প্রস্তাবিত উপায় বিবেচনা করতে পারেন। 😎 From bb3930593908f76fd39798c7334a1bbb5cbda5ff Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 25 Mar 2024 19:12:03 +0000 Subject: [PATCH 077/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3608dacfb..bc721f201 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Translations +* 🌐 Add Bengali translations for `docs/bn/docs/learn/index.md`. PR [#11337](https://github.com/tiangolo/fastapi/pull/11337) by [@imtiaz101325](https://github.com/imtiaz101325). * 🌐 Fix Korean translation for `docs/ko/docs/index.md`. PR [#11296](https://github.com/tiangolo/fastapi/pull/11296) by [@choi-haram](https://github.com/choi-haram). * 🌐 Add Korean translation for `docs/ko/docs/about/index.md`. PR [#11299](https://github.com/tiangolo/fastapi/pull/11299) by [@choi-haram](https://github.com/choi-haram). * 🌐 Add Korean translation for `docs/ko/docs/advanced/index.md`. PR [#9613](https://github.com/tiangolo/fastapi/pull/9613) by [@ElliottLarsen](https://github.com/ElliottLarsen). From 2a54cd5abe1c7a8b252277db6e852ed03393b116 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 25 Mar 2024 18:10:11 -0500 Subject: [PATCH 078/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20add?= =?UTF-8?q?=20MongoDB=20(#11346)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/docs/img/sponsors/mongodb-banner.png | Bin 0 -> 4044 bytes docs/en/docs/img/sponsors/mongodb.png | Bin 0 -> 10884 bytes docs/en/overrides/main.html | 6 ++++++ 5 files changed, 10 insertions(+) create mode 100755 docs/en/docs/img/sponsors/mongodb-banner.png create mode 100755 docs/en/docs/img/sponsors/mongodb.png diff --git a/README.md b/README.md index 0c05687ce..67275d29d 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ The key features are: <a href="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge" target="_blank" title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files"><img src="https://fastapi.tiangolo.com/img/sponsors/scalar.svg"></a> <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> <a href="https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> +<a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> <a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 8401fd33e..85ac30d6d 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -23,6 +23,9 @@ gold: - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024 title: Coherence img: https://fastapi.tiangolo.com/img/sponsors/coherence.png + - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral + title: Simplify Full Stack Development with FastAPI & MongoDB + img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png silver: - url: https://training.talkpython.fm/fastapi-courses title: FastAPI video courses on demand from people you trust diff --git a/docs/en/docs/img/sponsors/mongodb-banner.png b/docs/en/docs/img/sponsors/mongodb-banner.png new file mode 100755 index 0000000000000000000000000000000000000000..25bc85eaae908ab8502036865d1451c5afbd319a GIT binary patch literal 4044 zcmV;-4>RzIP)<h;3K|Lk000e1NJLTq00A@r001Zm1^@s6aN-8b00009a7bBm000XU z000XU0RWnu7ytkO0drDELIAGL9O(c600d`2O+f$vv5yP<VFdsH4`E3}K~#7F?Ok1L z9Mu&*vrcT{A8bezCk7LTgjk{?2EqeB5;3U&sSsn*N=*|;1Qo$l6|^SwF~*UqRwRVd z2S}i;_$%;4lK>A50_;lsJS3^@RH!y_a2jOCQ9>NNj%#D~a=vqS*1PN3|DD-g`+m~O z-km!$cQ%>N-#O>IXDn*@i6RFyuDXso`i@afFgiij#qap%B+>YHWKHoDzYmasfkEbI zSXEEmeZ7=Rs3IS!m6s7!lu$M?kMadm0kY1Fku^MK$jiXMMO0N($ZKSDlyU_($PDmN zt^p!Db%A_cr^y-|HDqRB;4(Uo9HzB5uAy8()mFMfW<X9Anl<ca67w4pGcfQNBYr>S z0%}nysp>Lv3prD0P-WJsZw;9l7~}xRp{-qW6L|?$TtsSV1-S|D6&ga!{%^=a!r#Ea zASXcn40$v!p=$ViB}L>WJXdIj%nS_j1IVSJ;^_sT&WOWJx8W(FNtkKK%)lTo0F_o( zQ{#zJ6LsbRJR>yg>_u(KFfcI48yx8P*c+ARQdKh=-VoZvl(u9P00J$wT!kqn1B1B& zgr4^`-a&3bRTR6PJG0>lp$VByeoy%h^*{~L{nezlFDC<oxdid1t#Qel=8-xB+$S`s zvvcE=?|>>(57y{6t1Bq*SS=YC%oQM?)_LTJSUHx})KE5|7R)EF5R=eG#>c3tG;;%7 zp@f=hS5zLMnU&gVZ_C;S2Dt{5THVr`?B>-<ymN;Y(M{Jp?X=;N`NjO2FT|D!d}5we zl+Tb*^VZ8|ZfK|=>mO&xAh&2(wTk}m>&GR}gNj^tU!UW+qkn&!KL5`#dh7Rpq>iJ9 z>B8u=8~&rcFVFZa-Z3U7C+U)s68b;?-0{exqFS8J`&{c&^z*y!);TE4qTYc4N`z%K zOC#oi>w9#=e0k(k$u-<K?0L??#^$!*{q3yMpqp`J<2BA#nzqC{QE!oX*d7l^6Q z2F?vr-NI_h2%{7EpF1lrB6Zh7=WW#`q;9PugWLi)HB`f^@4ZV;{9<!Vhx@vgM>6gr zVISkZwRh0t8#g5!-_+PBp&I7a-J9IGKid13i1)ZAylndfenKJPn3%`bd)HILHLGaZ z(xv1T2AI^K)-2W{I6uDgwCx>5-nql#YQd@nnT4E%;5k#bR0(m#+|ES;>(dc3$St(9 zy__ofroznz)r6m~@lD@<@O@g*bPv6=YY#oNb4O?&+=x52wb04I!HB%j)_a>o1-0(k zE&Hz7yitw^BEz=l-+Ge?W|N%D?nv<)CLC<*;W5AE{UYY(=O~1f%;#@y?LtOSHHb@o z+1@6f0kBA59w6rrSuy_fsaC2guMo0me`&7}=+2k-g|1hOuR>(m&1t0qT+_gNS{3R) zB)BRoG)MfK*npDEWd{!+E}>-_ZW4N$<vCPzs5v%8R2KHNAdgnYCFik7rKwu3;(aTL z{NI!Bsooje^|7mXT&;|;-WbeFVhqjE2G5m-CwZ>t$@<`2>~R3b9XcB^&Mm+I+Hg(1 zkW=&RjY;hTGK1p6J_sdk9O(R52<yH^eVnGXjS|v5|Mr_gT3uiMS4a(t=+FEa$nKSQ z56bT#z-U6-a!(Uo@ar2H1O<WwsqJaqE~E$&+sTAAFf=6Rz`1_R^8zsDAQRom(}UEu zZKs?AXk_xhxj+ybnE1Bdvz~Gd5Ns?!y)Bd68&sSoy^+yxsk{F;d5MJCIur&*E~ZCp zRsmQwDB5#|8@ep&Yk`70aWUc}Yw!P9z42cxj>;8sZ4P9m?p!4MT8HwJ%mA4et5jTr zZ;Ni|iDHP_UPo$WDfwPJ6*-Ro0Qk1_2!X2=rKH+c=zVt&keldYWd!xo$$79RHg1;p zAP>O)=>$9fQyCU6fh6#1d!&UnY;UD^cJHA9COr^eER6VLE05OacJaPLj-fE}Q4h09 zL%SZ3<+?CZfKtP&WALz$H3(x16Ib__z0|?K+oV?r(BElf$SuW%>#n8BRabb{EH*Bo zVG<d2uAL|VLR%5FzHE46MhL1_EFde2(DYaisZUQhhNWW8<^AM%g@EDd^nlefO4hHw zpuh{)5_+N7q$Yq84XRPApT83>nuv14m@)VMy^%}mKd1=<Bm_Li>ZUo4Arva>2rDxu zqSE=eO%i5e`)ltVjM&~K;pch@u97WjX@hE`6d)+LAIP?i6&`N*t}pvS<1hw45z^UV zCR7gQ`*8aXnhn6Usqt?}&HF}p1aO<!tXM6$Z8TqhGwtvCoYH~su=^F6OcD5J<X=^U zQ0lHlk)Q4U$}y}8ytbOFpu=)QTaSGaL3&a-Wio@e%{p{WLe9`OCOXx;gv(jwj$xa4 z;vTp{R3L4r)_FcA3#af7$5(b(3{vuIQt@HmAi;oerMQ7HJV)zwR*Yc;rk-RqwxmRd z&f&+#etd1d4gc1P4C5Lu)e0@f7_X72^J*?SvpStK*BxSW1+3w;*KwlAShsMo6dVW6 zx#J#4SbhMRH8<Q$vlhuHsNvYf4eNum`bNGjvKorYDU?n$B%FKUN3zWa65M-ANFl%> zUI++Pd4KivN}}UTK<)ixeR5t_Fob*KKqTr;J`bxSU;A+;sR<!TkZg#|5IWjpSan(5 zoUCRdPR3)0JenLMMx|GX_x{D2tjBVr#uJf5E=a`boO6-P09p1F1c(d@?fNUP7GiS) zN!3%qrYW0j3#4%)Ztw^=ke7s3vEbLrNi|n%1w@(v<hTyU0>OZAY$C+5eZT7!ADm4x zwwkjzoV7k15u&p8pV8zS9HYsELtV~Yi86%J!+z!S#6Krvn8=XF6S51cM<_ffG!;&u zsQ~AFre42ZyjCm1?zwrh8pMaR402fZw7(k>pXCavB}HgmU!M?GO$ifIR1o+qDp?<; z*d#ZWNPS=o{A?j2VTI)oqN=MG==@xCfdHhy<R!{19Pz4$We$sdaUB2D^fu%NdmM-r z$_w+TPGgN7h?5BzFW-hPP3F7mg<SIqs1Sx@$F@f!-0w(OBL|ml;5@Ktpn7RnQ2~5r zf9`c-#hl^N*#Ezv*4!Yqq#bWvr%t34dKN^5lY)d5FYHA4mgpED4TN&YCk2ZEPT^)~ zyi*A4Pwo4%&P?igH-v?tI5$YjK6hFC4hM<4iYS}#;)UE$j=1(%=Hxs<<Bc~-HPa@O z5BI%HO)hkpz<IiQd+9)Dhg4CY2%2+I;Y1+<RR-8V<^mG6+XksYC}m@brH!N)S;3Rm z_4QZ5q+SvUy^95+(1>&%t8JxzgPRwMjLATf@IA?eQ`Y`rIfi<yRzf<*F-$_Jz)00J znnafrPZLoxK&Z>%rl=zj69^G`JHD3CoN+Cj#GipBnyBK2(xmf%AkBo|0lu#a_u9ii zO@WNg2OAQ?go@8l;k0d@H*Vf2<nj2X%~G{=vT_{k=#Yvdpci86?h^P6<OYjJyHp&N zENMdC3m!7~%5Xf8AnYC2v(ke%4Ck@u6>hlg=4vJ?nDD^$A9!E9XBtYJ_XC4NG~0oP zp(N8X2;pZop8=fGnglHqDLI)qS|D}>(kjggS7Hd;a3jBwe3e#idfeEzTo#)E?0j2P zc!pdTLRQJEr2^#YVAw?!6}h+vk40RE91o#zQ~^M8Z->rChSKGc|M~R#)~Xqm&u9pl z+BrkKzq&N*i~149foR~%g4^B(tQ8;|0P7>Su5Xg}>tgt~{`B@65_ZBb2BRy0_qX$V z?Due(s~;q_E_gl|Z=dB*5!+=Boq7%!`%v(+tC(P;eQ42r``5C1gC8zD6rGJo^<gN8 z{!&h9#X!o-;Gxb?ent4HlY0(8%b)^lwJj<QHzICqxc@nk9xv2Fbx#uHw^T{uUdZa5 zVQth6?x$9lOOjrygrA*f(itaf-zlQj<rLtAy7kEjDVz_=>cy|8_X}1P!z-nsW66T~ zqEJylRGnQYfZc?NO^OaU7V=%YztWXXc*{;t>O7y)*DL$LLW0jYybM64Lh0RB$<@_y zsltZl6dG4NJq`#~Rqf+R2<&%3oh$7w3MYt;ph<Pa$vhjw2n%I}ap6m)!+*Dpxb`CO zc-6`CVT6U10#)VZ5!<2sUJdiN*?zNgAN`AFGg5sR3Zg%VB;@KdMOuA5Y^4UN=;SFW z)aM5Hf@V^=IfoNm!>1Qm*|8!DyLqD(76^<$3i#a~2jbg#T$2!!gT-H^^<b3k0b`<+ zkp%*IdU_d&bz+><r@8_fUStp}2NYA#^)KoZIj#onRkL0njZlzs+$fj773N`!H%_Xw zQDepGF`V6h|D7-G6E)PftwqSFBgPV(a3gK3)dTh_fx6)ONEmB7jvf)CE5ggxsAWwy zp5)IFa)R(M2js&*P$(=^@vEz^Px5A1WR5kZAXJ2%;m5NJ71JT;?1MaWGmVF#Kpe#t zNl7B1u{IH$9KgPw;ezN;>x95F_2heYAnzUi;%DRhneXn%n_H|J+n49e=;|htF{h?$ zU`@0iRt<n8Uw!{wAwPtgc4v>dYMPA(JZGwY5v7Z4<kB+k>wyW_OQaA7FIN=>OJ;zm zmqJ;tL^CUuqQo%&Sw?0+GNh3%u_W3L>I?nB{<@=`UO}s%ur@`8%z|XL;&RFa$fel= zDP3f&&?3OOvm2%sav8Q%4vkz5TC1EK8Z!UrE<kcwsF-q5K$cmda|jb$qWqtMK{kOf zQ`J^dHjt@G%W7|2wA=2E%BR`Q>TF2m2l<UqCRRxa-5_;<xKuC~2S{?h$Nb?i@CFKv z8?jciI(t5{OnWe9jnJ%NzvIJD>_&C50K!ALTiU1`Jsh`%i@{770yD@3M3upsF)zE_ zXwz*~W+OWx=ja6adNXhG2U0_&32jFVu^AZT7etYP$QGAnoyctHw*M;aZXB7<3S@Tt zJY@rRA9K4cv4Md>ZUFL9B}JsFE}=l}r4*>=>iG>zw8zXPG6O~~`Z??@r*x4~$SGka zp6Zlkpn_BvbY8~`R}BniJ46))pFFNg=M$lWMRCxy>fz(zyh5gr&rI(dnF^3KG|GgQ z;WG!~KpxJ(FOV7t&QwVa<^qJkO6Q3(BD`iHX}O7%wIfuS@7Nhv$t)cD5%nhgG??9h zk1Me9a#GhV*5=geazkcmAh~Z0itNmoCb1keZo~p%6Mh=ZHh7U_pKF*&XiQ#0TH{k> yeLKNFzsrlYney=0#ycXqEf^RSA`FqahaUjFZGXP1Lcl`+0000<MNUMnLSTYFn4lg2 literal 0 HcmV?d00001 diff --git a/docs/en/docs/img/sponsors/mongodb.png b/docs/en/docs/img/sponsors/mongodb.png new file mode 100755 index 0000000000000000000000000000000000000000..113ca478582b24b0010f20ad21270d590df55da6 GIT binary patch literal 10884 zcmV-~Dtpz5P)<h;3K|Lk000e1NJLTq008g+003kN1^@s6xT3ws00009a7bBm000XU z000XU0RWnu7ytkO0drDELIAGL9O(c600d`2O+f$vv5yP<VFdsHDj7*cK~#7F?R^P& z6jj#tTb-p7va$(;00CuH1OWl{`y}YdEDnmy%<nF!qoSiSf;uyf!=mHN@3^2o^SF$P zh$DWEj)KdmxDfn*6j_5Pn*u>X*db&kTi18qTV0*%POs_iq?7dfq@G@?>Q+_fzW1E_ zo^$WjFym)B;%JJhI@q=xMtebaMg~R<8jO|e*CCGBhMr&pax$RzNDFvuBI0O@ntIs2 zKZf>%((-b|5&Ix%^<EjmOj}UL#|i8Sl6U)2ptb?+4Ya~>#4hwcSwUG{E8+yUq8*c$ zC@n8T9I*$w%=&4afebrBMR0byBcPp=m)KLXAN_KAA&%HWbID7@2~1G1YUku7N-N5d zot}v}Vh41an@e7z!xLCLSkWQKOHjy)_k&{xdbds?_jx_har?ma4ru$!g}{}Fqy0l? zu(VG8=gF~Qv-IQyLv0Qd9h1Q2HL&e2?GRSCqa!ON9n&tk1S19v!pgO4vG~*X5ev{I z&I@}2!bQg-un1M!-ZE&VC(&UM!)ZHu*A(b!(jPo}61K`3gp0oEJ@DIWuEvPdhoJOC z8M3ouqyJCq3vr(#fsR37y32<u4R^W0fesA~F$?`t5p;61kX>Al>E+{*otBQ$stUZk zbQwyk<^LC=!TO=%AntnfQRr0-Sn>Kx*tBCiVgbtfMhNYjz;WU>L9AwE>FmwqN_9Lh zQwVIwf-~=N?OVF^V;nC%0i<Zq(n4dgmTpsx*0PU2Md5cl5EBSPb@oL2Q=x^l(p*E^ zegw9{1JFv!<K(q~Ds-$V(fxYnV8fEv{2$byW5V#!m~-PT2o+kI4Nt!Q8ctMKptYfA zBuAw0YodJ+n0;Fb2Px8SJ_OtM$Dx(iB95luV1@~!Mk7{0%lq~tk74AHAweBKcg74% z`^jX43X(V`x(^YwzC_z`p@pOhRE}lSD(j3_5;bmNLqcgq>suld(|<Y{BZ4HaiO27` zN33=)6z<r8l^fRK#L3{F$0qS4o5N7@5*<dpacG*c*^Jj{LQhRXB++~VODIOG5)zR> z)pgM7^*E8*2q@-E7(J%dhZfTM&bc*ompD5!19N|Kt9oBlybljN_Z(jS;N2z`Ho3k5 zBL)t_SDQq<V*4-GTQKJyOr3NAa&vRtjx8%I!@lBTm94gU+cp%Hlwia6JMjP3t;5Nr z2--P&WNl_>rNu>|c7a&Q$Qmi+%FFGIaKQ5yKKKB#M6rJA->>16lunp9Y839c`Wl=* zWGFH-GqH5}XSja$A5mIXj`PQlZ9-mx$7K#1rrw`3cAVS3RcqJa)n!ZZ();hBHZjcp zt39&4*5C*n&su7Cp!MYd|JDqx^y`&_NMY`6w<1xD%AfAIO_9-xDPnQ+B#d;~O?P7C zu+ZFf;=HrRs_niRw_%A8`A;uCkNSjW5-}mN1P)l5$`ux2C{Et?1zO>}oSas*#GNB} zZMxMLUwB~?@|qxVH-7MMgacacdw+8~cE0mIhIQ?ZSb$#wYkN<q%%!-y+&;0aV1=^6 zt%bs^+Ym`;0kX_U@<@P0{@{g$IPH|4A)Oa#>q~eqkuI}@Wa3u0{e!ObrTG)l8lV8h zercqjw_uovB);p4D?>U*rBFr~UJ0!2JQk0mb|9$O@aUG04VP9{;K_xr_}(w%e)7dv zTqG~tvJEf4u~dj(;`8{HL>CdxLV~>o2&~-ZIC(o1*dJcGe!U7U^~;HzuoMVdlBNjk zjgTbcSwH<He*3_~E@JX^`rY?q;^o(SEpM5q%`J&9R(}=J@#qxU7%<^RVC_g%+->f_ zpe4=|Ww^!q#R(cpt1EEX&39tyX9cdWOC=_|^s^Pp#r6ho-_uh2IzAeB{mr-V(woad zI!C2ZMi`9*W;$X?eCpAT4wCqUSmYM7#+?#Sm~kAJz43_atJ1n^T>sH?z|hV?6+!ae z_29#pIw|^n`EqGo{y6_3Tr>NA)P|6WtopwZPNO7TabQK>2n=x7dn7}@HV3vxix5ZK zMA7~dwb2?+`}t&fzhA|RqcW0-QJ(>6!dj_&AB*?*{a)Yz)25`d_wEEp2os4-UC)Bm zYq3fC#7xpyDesYE$1{Cbq08>x$WI!K-d>V5!U2i<^roeFeAQbxwD5b-_9Y^O=uBqh z$xCQzWd_d3$R8>Ka4a4U^sqyFb}zKI4<e5C0a|2ZHULBFHL|%HMVw7Lb~KCNdbVr} zq|WTF0rm@VPYNkg#ImK!b<WFxHm*QE2becX$gBV3boELkmYl=|)dMgkc_c<v_rkdG z<Ix;!-LeG*b=&dov32UTdW?7k?;Hl^ey{eYBsfspH83&t1|9m~u0XQb%T7^9rHqv8 ztk3A9$m@E)sT|s_D#X$D;V*BR$sqky-<fe%gXElpnxqa2BwkK4ER;=y?dRRlFgs7& z(?(*{=cHgcO4LTAE`Jnf^cje*2W-f*byXXo(kHVrQM|Vpj*KMyaN+=trPpEe@!i;! zR*JfuRQX=Y?ZcykbLUNPDxaBGT!jf^&PHDE9OUKZD6y{S;C?Ln^h2yXunk4k;jjK- z5I6#=vwm3*wYhya?^I~FZUHLeb5FHr(DIg+yQgHDVi?IC)}V>(L}(el)!U3L9i<um ztr{)oS{xDM!cSg2&C@+T_g5t&5K^=Tcru3rH0IuTGiF|UO_RhCl9*e*Gh{dKwMCf! z;cH=8<wTAu3b*fT^n1Nb7%tY>ad&^%=6{bkIu_W6#(v|y;eIz-ab2r5Jn>q_MFYo1 z^?IqFNwQ@nLo0RP*N~p1TxMF`mPDd>8V--l5l#X0@4qcT{@5`=l`-$i=@^+i0N4NP zDU{Y%qd7>7i1iiG3TZxCk#n=5pDBHruj2}LM}-Pcb?t_J=k><!aYDrL-Gz+eGJkUv z*ih>CT>ZzQa{ZzoaE9Ub>Yqrf@LmbD!WwAyWFc;<`aW&NVN_0Rnf&B5)T2fk9;*sX z%lqQ}^MfX@i7EemzKU;O|MuUdkqSN4(#BN@!U4&Ni@Nzg=I%Vi(XsKvo_*MTq5?Q9 z7PrW0G)T()Q~aO!qh2oZV&e(%hm$$I1`_R!F;!Y$k~ekTakWJY_U+|J-Cl-jA#c6M z;A2iqFy%)VpgEX+@x_=nA|K6xO$*n3z9xuRp}5kD=y7y7^t7kquhVbD(XUox_k*uu z+MW@}d#DWf?=`^e?||h;{1;Fl7J8N(cX1)I|F9o(kN*f8fA>6&e7X`#?)wu?t85&7 z#J(;!MKmFDvb@^L>(N~BT(hhc*(hpN56+a}kvn;tJ28P3PfWW_O*|heG~2jQdUHn` zslM;xGlM%=Txi=pu`#V@9MK2!gde=|Cd|0@I<NZ|y}1<gpZz<EW(fh0iDmv-KlcMp zh&HoI+~o}t8-C+B^3NTQx1WE?>xiP)zjz;W5<b9=flcR<CIJbOQ7OurDA(n6sOy!A zq!OdwNn$4LuQv8OBW3FN^hDGQ_PCxUjMOtL4ZpwVPL)UAoN>mUn0WthQE>FTkj_aA zYpCG4KBV=^`lfwiT3}8I>O+xsv*ZV*fAjHC1cKW+JFB35S&H@mHjF;ICGwnX3^gym zqkd6WR~XORc`fz(^zYdVOCNa*XABwY^BAp514>^wO=3BG4!Q5m^8fxs!YW&Z%oC+v zogww*XL+*8?x8=RVBRV<tHy%4zgJ4G6_=lTG0rO<fuDRn7vG-m-j8fTKntwGS93(L zE)oZydF|DR6sC+h4+S5EM&PgpDC*~Ad*4yvgQO$;xY1H6^{G9SAg0ggYmnXFwWYGE zV=16Xg>O&sW<}15de`&mr*aW2yYYH!AL!2vGoIV?JRzx0(U9j%>S~;0o;U9_m1Lt2 zh|G!r{_xQCzxGSsC*OJz)4RNZ(o9P|*(Qc$$uZ>Z?}C{PKb1z@;->yW>chWAVd*!k z)IbJrgC97&?>`eC3d>~<1&L8u;vy?4HPlnWoL07{_vCEN2Z7<I@+g)1`znL{=?RL= z{-9ee6wf`_jz&<)Z=fx8#w+Ey7>2Vww%d5UZZovyN0s;CczT$7L$|A1k(kh4DKXA* zo%gl;u2StD862>23<oK-^|*ZMRG<6jfASCf_N<jaUrS^D_r1V^BFvn2m6|o<i92Uu z?%|7og_gkyL*@AAPe)PxL7er|U#JvHPxQ^|iLpDg5p76t6iKp$;=3~S)7*Rwhs@?| zB2}R^K;aSCr@K}i+VNI=VYqqv6yF3^E~Z#>ZBxfwabEkUgi)UP0T9dTxGu;62htE| ztBxCu<GB&8<TdV%C-a8A;rfsMf_bCX8X+Wgpj6g7wjq0IIbQnnd^|Dd_pUzfyx+{g zOGAGn{olil1u$DnNL-p+rslVrzu@U6*NCPCR-#r#Eho2BN_4Q`IOhEEXS=qQU#{_b z979UGA6kfM!_E&{(2BW<-L<dFR0^i5Xg-u{<vs>sb#<{c`emmmYo#_nN;q9h)iA&a zjk(UFtKP%+Ffg}c`O43hEu4Gu2W6pYZKa_L*)2|w?sVV}f3n)`b7^TQCVns*i_YHN z_+^O*PPcBw$YVXQ@tuER`Y$hSQVzo_8z()AJnMpjx$>-UO04zFWXyZwX*Uvch~L&v zHY)X*;#Fcv^O7U1AZa^EjM)rN)uc=8IYio6r~0Awo%h5uK9A)rn~U!F9e#WE&kzj4 z`%kj3=FJ^D=woHMgTbvhN3n(dWfE2MRIY{C6vXHv!XF`L^f6L9H#v#U^Vm0}Kqh5s z7V?|N(z0<KS$(R+CRd$soulsC;~cNo7~vF=c>E?~vT<tyi%K_j=7<Nnr=Wf(@mAQs z#d%^;gU|p>4MO`Oda+XC;jCfkyyQ*HzUr4KDk{QdUp|P!A6qK@VR_Eq?ZnLSQ<T;9 zhmrkH!-~`gF!ABLP;_;ILEtQDP+uMm{Bf&m4DhPeYjFGgzv1LnnW%LNSIp3|TS7^7 zB2*>GcT}4jyrgGRoldAQ)MrzPrdnMUW`f9Z=O7P~*O-hTaQ}JkmD90k?WZVB@}H*> z9)S<kC^xPN!X@y>M+__LMY%SGGpf`+Ewr+R1|b#EO^79RNFR{>K(`!iy6uy?Da*+I zr|sI!u6@dqvfp@3Z{V@r0k7d|40auI8;zxoXM+^%Jp}`kv;izIg)H#dI7&>eA920F z?(U(~pOTAv(<Wit`eIDk{|yS$<#$*mJI?DRYI8aAUTMHfe|kc>lffWQRP7aaJcfz) z-HxJr6POAGd?Si=e;XzaI2(VM{}(*E@Sn;urlK(}Ol7$q?&`9cxkYljf6wDWQ=)^l z!&J@hn*T7KSon&1&u~~Euq!cP(3x1adp#m?4_*;!dZe~9NSB5p&Ra(1_Y|`fIsAl} z%<;&yPHsdY*bn45Wh%3la@BKG7@;o}tG19x?UT=*3OZF@b)O#BPy}(_r{_JX@K2EU z6cn6dp`PB<3)1iI564Gi)TUE?=Kav+-V}wD)|#dbf+H;xFC^#UlA69;sMjFxfA#<~ zzQNnG9t@hiCg@sj{QF|$y->+@LyhwKcfstG!T7)L6@={8Dso%4P+=1*YS)76r}Ewx z%>5mXZ~hXyS1pf7%((GB!oe3_;)=dncUs>NLOrINXBD&b0jbL3Yi9P2H*00arhT}H zX1GcB7H8$Xd%OP%FTx0|nz!qdRD4!zzxhnlb@d*Hbu|)GLL{&sXpf5e{Nr`THgzMk z+qS4@qowy2f(i?MRx5Cb6+wg3Lm=srY<O<VUcCQZu^MmdOYkzm{l&$__@HnLUM)TW zTZWW1+?iULI0Q%f4Mj_XA*2+Mva0nE>Ej43>v7ZWz=MFoa-muAbhhfAZnPH?G_gG1 zknSE5QPyHahHEecEtDd!S-!V$)qqr=_ux855zLDs9;Az};H&>nnEhbuXJV(H2FzD? z#2=i$m(Q@B3AtB>moy0{saP-*U^rGgN&`%6m1W8TyRdz@eEF3TI_jH^X9r(|XPq9b zeZ>}aeBaKQ>eY&)DVaDXn<HJev|P2e5p@2BVlls#`cWR56%Q9mh2CE!;UgVY&7cnT zfRQ6d26e2O<Eu!*Yk8S|j|*FlWIvDYnhTX)tW}ViRq${Hm8dkrX)(m2DC;^eLPHZP zLTe2@p)KAA{noyQyKe0RJF~;QHds9(JE@r~929~mrGziK(`+mvMPLs1OKAMxrEXr0 z%JGvL_n&c>sLn;ewk5*7J#MGg3^3Ls3OdR5xIF6zQg;8#fwSDhVRUP09jO>Mh)`8K zI5PS7rVvK)tGZVwL_2u%@*B(49A6j}SUd}#z!a0{j+%YMiiRdGXHeGHTiLX_v~+Yq zSy`prfL3Fdv!Cswf~t@ZEn=9Jmth=zM5Zegq=`jS{batUP-ShfOl#cJPaK^08$uVu zm2Meq<LHSfCUaB|ACJU?#i;LLnU^XjPqzDj)9*uAnBjfuSQ3}X6&xj`roIu_cT~Vu zW~jK1Oe4?PHOq##GDO%)5G9%lG{+e;SDMGVowL1B{8GaJXWx%tQM7Xh@=hJ(_n3mO z)?g14JyPX*nSmSphy(<g?c;dnbXTQdDxfKp(?U0^f|=)wm}RC{vR@bQc&CC*>*RG# zE@$6Y3p5HQ02F~vO*O6|jTV(&)o+)^%CnJCVKM$D5>r;<oJZeT<uC&-;V$5{8B3mf znsLrEdl4+ud8XBN-lMBQV?)qfb=sp3O!t}YFiA|f5jhH=m}DkbSd$TJ1~r{{-3%=e zbxuXvBq~EoR<Z^Xx7a^_`QJ+sG-^*`rS#>4fj%(HAaMXh#uuQH>WtUA^~c!n3f200 zBpGN+8!L5CeKsn?%u*6d=(s!2EeV63f}v0!Z`!Evy6M4NCFUfn0UH#is4h#xp)$}& zW>4$Jdt&3`oT0?+o*1TLS^TZMHFPAMnP9^AOe}e3m`Y<+69;+>P|%&fpMIKqf7%re zbB2;!za_mJ3WLF9$%O!hk`!?@!=<+G3a;V?3pNleH|3kvs1Y&Ab9}DP`w~)`!wyXa zn(sO2f$tp|!P~TCEyDTGiP8z^BGHI((#7c=+^P=|OUY3=xFV9M{uL{QeD(~<_=FJ0 z@i(J#8L`;<#>&hFfr1O&P;2r9vzewEgTYlFS=>{zu~6sI;xQ(>_)L{3;SzjkA^+*# zsJL>9C7$Y-dn#=6cQ)>GR(kbb8U!_6u1Y4!G|2Uc_es!oX?ScF>!=iH`8_zfL6du0 ze$>4m&A|sV`nY}@b-cM#GzRUXqejE#VKE&%XN2<~FN(IqQ`P40C=E%IhJxy}JWI2e z7E18l@F^n8mUyUG5ss)6VkcCTx%$7sfYv<ekYUkj;aLV<_11t2A&I+Qog(4EiG71V zv0NJXjL-)x_=9E}Gcuyhh_Voz2TMX15u4187KlV{MtLez$(anIQR($I49~;*Xch(8 z*FFauDj|%D;aWWd5{^O^U3kx=4bOXmv*8Qkp473_7X17Mx*sd5`BT{a4D$>X$s%Z- zT>N#w<7h#XoGx~Q5Yi-Posd02_Hn;CiLFUkH)Y$38${GPWc<$dd-|g0s_+&K_XqoP zKfw0v56WFnN!4&N6apU+mAzXgB8kW+#j+yMGDLDF$}lpAw4H&4A%B(I>poge@c>k^ z$j2UiX)%nN{DU3lTwsX&Jw@^yg$VwyxbU_8+pkb_`Z&MGk&IRgZ0#pEcQ^utti)c) zu&LQIQe0VA;erY@XXMbuy{<{;bnej;07FIO39PJK%Z$lvE$F8>g&!Y@8D<|?S^N$L z2WPxkI1h>UJ|A`Q$_l!*$un|X6WgiKk8BC%OdRk(xZet;Mpx8{g57woD<8TfaNSO< zszaBg6m(5aMP8Rv)G85))pa<YvJaj6_QtWgY9)Xjt2>F^M-SpebtP&tn>VXw#0jh& z5^K4*d10fr0zRWsm8s}bWw-Xt*)Mhu@$>9!cNEkgKLFb!HzW1uzeaWbR74y03>$2> z_ea&_#;J`x$!gAT#VK_dPvW4J1m_?J#*Eb<hK$BgQz+?`wz>xVsLv3L>d_DRgNEbu zK||C81D+@>EcBYlQ6^;m_Pg!){M$l&w)<PG+_5=mLPxw0+)-fm^;L|QD)fO`BPV&1 zGbA)`XM8GMK}vde5gTWq=IkH&?!z_{bk$Q=`~zk8IYLs8!-8c_tp43P;g*><;npda zt5qHXp`f4u`T6+)k7MfSs!i)L@4Y41h6=yO#t9q_I7oqg-2ukhJxXMfu#PWbs-r=# z*P*dDAyzLrxf5)IMnfMm8jc}nhonH8P)hXHHPE+j05+~bZEY3ocZ%|UqFyY0x8^O+ z5-NniT^>7tdvClNx85)<DB_x6DrH_?9zwzE?=QpspS^+at9<14#|a!q#No=~@qI{2 zT|MgZh9c3P2EDte#+}lkrKYQ;SdLXxK&#@!edTaeS0G`}Hq_Tt!f~=f^|7rWfvYd> z0sHz=G{|-9$3%BZoo?@yW5t*`IAd7o4UjJvIuK})FZ#=DY}1=s;}-He;^;`=Jjq&s znsqWs4%qjd%AmroLf7|0MvrN-mXd2oyXLz^s2QCNn}|=TD-NSU`md47gEqnbGc&cG z?r~+a$QusWpZ;jh0`$NC1~`)374SHL<A^Af+nm_!l#sCCU{+PR1Gb!G*8l{DlPFfz zgh*&A(Q2+}2^-m@Yg98RLzVffA76^rK;ND@7@O4_tE&#UeIF-q9FYaBWaBczEe{no z>f}aPhkTdnj18Mp>S!L5-|3l&Ds062<}^BL<WWx3dCwXC$;fP;7}p&4*$S%No`@4T zj>tmdGrB`F#H$v7{qrNL53E2^W;DI9BBOJJQn<+-Pp{pA-(A@9DV!fH{{)-2Yy}3o zPec)Ovr@*<#vvA1qY18W8Eup?+l+Th4DyyYxGnS@4cw1hJpbNuv?RV<{S~g8eZSXf zgW?2^BeGB#5*in-Rbm#R%wt;D%JdY~-?h>DMtNlh4$PR*Z9H!Id<*s!7bBXWyZ*=d z58?dFug8%x@A2RSEvM%^!~hsR7&m-4@^W(2wrBr-pU2L;;wlVr#?yXs&bipMV~5-R zIXB;eB02v=dEi6}mesRcH*A*}U9e?%-Ycz6FxT>heo_X@w3fjIvpj!`5rYPyrnVL* zYh!E`iUwh-&1nl9j7=IHV2xinjI1Y(i(v<0E{x|5oWZ7(r!2Bx3hJ-OQF+QKn@<2o z>tM5MLhK|&5^NySmmkE*LDQfo+p#{iJD&QX4EwilK|)m-2KJ2H+QeUO-h!w0*Wkv@ zhw<U_&%se?kT<ET9raz^y8tmmU=m{C+y_)eo_XcfYBKDvzS->cSQ75Q(W6MQC*#um ziCDI>z-|BBn`S6d2U8JPR#8a_4oZ0oX5FK%NrLz*!+NhH2MxvviCcO$0KQ<ohKUWY z{txm;jls+Bz3cjJ*E|1FuhV~i34Sb%)axIAgfCuNtj-PQxmpww({&B%w-8uC-mA|f zZ#~H@pB+X&nFLG_6P+NR6CDmDH8{{cH4R4&A6B0gG^ph~Rf(3yKuZv{TN=)!Q5mQ| zD@z^9{;i`{7XsUqVw_OXfW#v;Xz13w1P_*B-&}^|qAGR$1`;Ua|G4%uvus^vE?(8T z;~D82f3|g}vdWbQicwcyhVI=1lbSK!FTdG>kN211@r^t2n;m8Ndr~e|*}J1MTh3qh z3Q%b@?A{0*Qz90Lbi@3)%KEUPKlwjPaHm+v#qYn1Qn60vdxD>{Ga3gy=k?0LB@^<6 zOieA}oSSaJ1JaW5m=S{qV_CrpxyBepKoczcx}Q&GmaL0NBL@z~gi)ih>AM~39B=pP z{rVaTHmp+?^}35EtNpz1OD9ZpyT+y++ob`@S7oswnBWluHOoKx+2>-Vd!bFhPpsA^ z93OZ}cbq@^Z1E-rV?eK7$jRx0QgIdg<o3pi6XnRtGX5uf_LfLdx>_%&Ovv!fj&1mQ z`!;O&?mKLh|3|&%+nigcinTcvXnOLxvwz$;(Yrwg=0S7n9b@@X`4cr-cTS~aRkQsq z9)76bFnlPlADYi9&y=)m3$o;yyPj-1^Crp9b<Wi=$qc6`)(;^grU=YRym0P(^=ek+ znO9wnWuLE5gf-t^Dnu!e{iY=%5kGzIc|{7oXXUUWpTyX(UXkqaS$E@9IhTZeXQe@8 zRn`H+O)Zi#OP!6tw8@jP=-qd)aL#;;k_xn^WWU?Je)jD1>b|DlGt2Gzb8nu33ufGe zORvaRpXrK|$ZQBauQBtAtL40Ruu|@g&t)YrNy~dCPLx+5W?`LDM|Y1Q+2r$uBS)!c zn>_IXuSxzcSaxwPWh?$`+*sFpl`Fh<4PN}udsx41EBwtiZdIUtA(UP-CnX4GA^~%_ zB$uc=gz#ZZ*w=I(>e#ZtQn5*bm+>y%dgO7;7poZzXt6hK-;M|V@vQnhMcisDmeS&i zCCztQI1-%iZ+u{`A}~P<TPoyUCZslrde`HRs^dqB)z0hH+l|1ySKc29%<I#Nn%B>F zmPz8y<h@84^M#~)N(|zf*C080eU_D-o}u19;4G8)?AaGoxojXx%VT(8gvYFuCMJzI zOKAz`j2(waf{noC+%B7{$oyc@+jybth87vnzzGMMOq&~JG)~wT<0>>ODG5W@k`<jq zqZ>-{u(F%h$P-0E2D-)sEnZfJd)5uzSN5y9k8U{|2VN%}Qn=l#SVvl9(<P@UMeNzX z4^!`+g+l2|zb)7F1S>c1XXX0!svp17=^2<f^^%Kmp;&Uy)WVns#{-Mi{p<8!<AWC# z`Xw({?F$C}jw6|$8+8Ys+d9cu%q+?z<``#lKCYHPn%1Cn0$-~k#*_u7<!V^FQIX?i zAss93BC*JHt4U;Egd>S)xp%%}UB<2vJdelF5}Rb874!tl*znKSrSCZhp@3zRi0eg+ zvZ9|fJdaCXp7&m`!C2$w$=8;sYtULx6M<^Lr57v9OcY8vbjzQTvf47{|N3U!JL9&1 z$8m`fu9r)ATWW>G<<zagEJgC`pIoUrptsuIlKyXWM<to_d~u>alDW>Dz%N2DryJsH zrB34dwzF+wG!iXaFxE2I<Dvy$*Kh6niaHt^U1+V=fui@{_utp`0xOZN#5LCo4i-b7 zz6QI`s&}Sz>LKSqdqPbFu%leXvy<iZ#DtHU9K#9wI7y$?wGMT{K9-?7&*dCpt_Hy} z-&g9u3{(&7;(jjL0D`UjtxXbN*KgP4^#ExcDtQSKmn2^F=2E3RPnmQ9nuDH0`eWN* zBjMjvpiOXccXK9=Ixi`ezLpoQ9vwggQx@4$j?={^nQ0vpoL1UOQgay@9z(*O3`Q99 zl3*Usg^nY9SVSzFRI|@FZ^QY+gI|Hq-HkR}X|DUr^>nF5b4ku%z~fa}BaJC}{VC8Y zbIX#o73}h&bejWNSCZ13QXP()O(Cnn>-TLO%ubpxYK&XIk>8b8RJi(<giBZ|iB1v( z%g^g&#A>NNo7XYIT8+zTP_Sxuu!ND=Tf4p(SkZYO`sVtd-qjSRy!C$#;`UZVCMg3g zM@pCbS2y1-@g@WXlDoO8b(3Xdq6}jm>IPJLvA}IU7n%gQ)FW)fB#@URc58y_HN~N6 z&ZLTHVD3$~sO+sfC9cbB@iRg4zV*lgC0H?gYo<kIZm-ytI|LJV>3HSyHGYp{A2*Od zMG^-h@8_%6VDwL?V*R&4FOk-4DC_H7ZK5T>Wn)r>yj5*Mg=RdJ)|4R?#%*a;S@9VQ z<vxB-#h2js{lwz=%9&;eiX>vJmMXRt)~qS2!?c!xuCsE(I(43ztii+#zEUkWt?eR- z^)8nEJdTMShVrbdkQlS7cuz0My*$~*Rput}5(nPZITzO<7mqLBhFK|Pxc2<9h&1S` z&)p^e!$1EK+M$+9FLkXp;an{u8Y@JY3U{rpq1Mkl)G=d$O$$Xrl6cIzGQOWIG2E+^ z5cJlgj~kgz+%MnpSnl_R8y=X8>n2~KV!jj-UVir-^*za@$`PT2i4$ggHqdowU9XdS zBp5Erb`I*Mwaxa3J2Nrk$tAD4?u|(rY(z-jHWky201A5z!F8R-qU(EG@vGNA#VhN# z;_D#ezn<7zT#QAZuf^>DzfF}lu`&k*1Kh21(sMr`@uqKJfA@e97Y-9@Quh^ykveM& z?6bDI?W=b#??SSf>pwMj4JbAS)-uecV**W$7&8`_mXDR5X@!i@T4Sn4vco!+VMQxO zm-%|JXhy<EnQ~h_K_b%XkvL3iG~H*Cmho0IYl;I2%+$+ZuH%_?#p7trJ;CfPtNQGj zVb-pc>BPXJ_mA}(iZ{VcApO<EC2KG;mFs<HBJ*T9^0G6aiN#?_R9p454D2Z_7eOck zUmq<~dBZFNot=HpEbrH;OHBsWm7`uZ3P1LoWY`9G0tR)0qjw5yz3i@)2tC173bDUN z4N26uR|4CsP%qm_)6S)Ow|7=i%T%CM?zM<nd?r23eerUK<$Jzr&N8Zdgl@@WhQO@Q z{hdNnKaY&7qW$}t9BW#=yq>-lN|N!yTW)e2y+i9bt(QS&T4QEynR&^c*V!#Zoi0}N zuE)2lfepsB-LtMpRL{f<lAHq<MqP7-61G@A?<L!Ltr3=7@Aim*B9D-=e)w4M7jXL( zJQw6MKl_j3xFa{sSk?ZZkndOx>W`ijMeT&KS?|#!ub7QSwWmmwD1_}ItxOMT0CMGK z%BllCn=b`AT8J3}GY6Pf_Y$#sfs|tADAUa~$Il-3W6g>@hTf4lh57kvgb&HY%qU;i zn=RM*w_JzEnuIg6u68anvc62KO?UYv=>l-$;0Wd~vs@CG4TWchSu8?NkP4e27R;Ui zy^~m|<OE|Q?0%|>Wz{|XXr<~Gwxmki1W7i7aJkMFpianIR%>ka^1iCx7{E~PBypnC zvU0}9RM|Qu8oxuQrqA5!&*p)c%fw<hCfHC<I2lf+1@(9SG}Y%dhW=4K=Dp1lQU`l} ztV0o2Dyg0=@lS5{X13=wb#kuZlBNoQtN&D>`f+X<MbX3!7r8_%ePA{)FgkNX$Ktca zTpT!*IBmFt5dwjh@<r)Gb07q*JcY4P&W}~-VqNqeVx7{H8?8@-!9JbYAB=RaunCq= zGKDWyg@#yqws<C%AJF~gXrT50Wo>(;K|due@}#wUpT5TI53(XAnTvaeS>dhg3KOlh z$hYUSnJJMi{cLdpw{t|5xIx0I(yB0v^drrRYRwlmNkFi#X<gu(FqPZptg93)wDz;b z3EYmMcTRzxo25jlmO_mLg8V79W(8#;gg?ZRP-KG7=5H{6)SoT2DP7~!%C<x3q8vL0 zcZGgxmlh>2;SejI^!#7Z8qjIelA>3o`E2$De?V(M_mT(AwTR;cZfDTxE)VN2VUQMB zYSSCCl2N^B73_b$U0LFmf~$fvW*aTE%Cl*W&(_s_v{b*YJz{5C**L<3>g(o8pDQOr zP379Ekc!r@M#P;jKS6SOIvhQEtGSe;fz(gmLjCFjQO6|4JFGL%J-nq;0;0vAZH4h{ zXLfZXFs<*hO{?SU1GfjzW!6s<cezt!Co>NV)%C#YgX-0umIm877r-(80@Mv37uJMu zN~ztoRm%Pp_+%MsDl3h?p+^OeDq8v3vOA?=WbObI?ARP9a9f8W@8E7N-q#Hp#TCYO ztVVsbGlg-$VAxK{k=G%p8!!|}X-39Worm~CwHAl=0TmU{cWnc9Z-aiY#HiQ=E4P_C znbZos!Dv2Pro`xbq<VceT3?cvh!eOCBj(9#1+CVBDwU&*vbx4JMhiG_-R4|O$=ejF zDh!sHWLTpvDJ^Gl1EB?<jh45xx&lQ<joGH-1a6~fQ{?pq<|Ugs%B=8pQVl)Vzhy3R zqRo|?JmsAKLcw>NQCd}rm_{?6&0F5JC-OwJ%IkWH%lZ;=0=Gf5dGdw<tNYl|;O*Jt zVWc()C0KPp@)Cu6cVWti)=8giP4Jn$HC%B5w=w8_vSLeZZef&GSE8_ZcZVV|pS7@f zm)Cu90=FUP-8!j6jgF3@qX!j<=~A|L@EJ*7Q?&9#oWN}as^6R2atmt3I!Izx>h?@x zKAZWRz7QvH8-d<8tJOvm#VX9o-5%X(K2sp_67d?*20+(Y&6p8K6PWIFdm^#f=M6+& zA|6I+18@xQ(P35RP!NpE8OtzJBuU<2W8HBJ9OF=f6XN6z3JkL_*?}ZzYv4Vbao$i8 aRsI*bPopuk8O0U=0000<MNUMnLSTZPm}}Dj literal 0 HcmV?d00001 diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index bc863d61a..28a912fb3 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -70,6 +70,12 @@ <img class="sponsor-image" src="/img/sponsors/coherence-banner.png" /> </a> </div> + <div class="item"> + <a title="Build your next app with FastAPI and MongoDB" style="display: block; position: relative;" href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank"> + <span class="sponsor-badge">sponsor</span> + <img class="sponsor-image" src="/img/sponsors/mongodb-banner.png" /> + </a> + </div> </div> </div> {% endblock %} From b0dd4f7bfc54a3c0907bd7505d7f70f9cb8254bf Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 25 Mar 2024 23:10:38 +0000 Subject: [PATCH 079/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bc721f201..b2a11b7dd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 🔧 Update sponsors, add MongoDB. PR [#11346](https://github.com/tiangolo/fastapi/pull/11346) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump dorny/paths-filter from 2 to 3. PR [#11028](https://github.com/tiangolo/fastapi/pull/11028) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 3.0.0 to 3.1.4. PR [#11310](https://github.com/tiangolo/fastapi/pull/11310) by [@dependabot[bot]](https://github.com/apps/dependabot). * ♻️ Refactor computing FastAPI People, include 3 months, 6 months, 1 year, based on comment date, not discussion date. PR [#11304](https://github.com/tiangolo/fastapi/pull/11304) by [@tiangolo](https://github.com/tiangolo). From 5ccc869fee663b264a68cd33990861c8a2f6eb47 Mon Sep 17 00:00:00 2001 From: Charlie Marsh <crmarsh416@gmail.com> Date: Tue, 26 Mar 2024 12:56:53 -0400 Subject: [PATCH 080/846] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20configur?= =?UTF-8?q?ation=20for=20Ruff=20v0.2.0=20(#11075)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 2 +- docs_src/dependencies/tutorial005_an.py | 2 +- docs_src/dependencies/tutorial005_an_py310.py | 2 +- docs_src/dependencies/tutorial005_an_py39.py | 2 +- docs_src/header_params/tutorial002.py | 2 +- docs_src/header_params/tutorial002_an_py310.py | 2 +- docs_src/header_params/tutorial002_py310.py | 2 +- docs_src/query_params_str_validations/tutorial003.py | 2 +- docs_src/query_params_str_validations/tutorial003_an.py | 2 +- .../query_params_str_validations/tutorial003_an_py310.py | 2 +- .../query_params_str_validations/tutorial003_an_py39.py | 2 +- docs_src/query_params_str_validations/tutorial007.py | 2 +- docs_src/query_params_str_validations/tutorial007_an.py | 2 +- .../query_params_str_validations/tutorial007_an_py310.py | 2 +- .../query_params_str_validations/tutorial007_an_py39.py | 2 +- .../query_params_str_validations/tutorial007_py310.py | 2 +- docs_src/query_params_str_validations/tutorial014.py | 2 +- docs_src/query_params_str_validations/tutorial014_an.py | 2 +- .../query_params_str_validations/tutorial014_an_py310.py | 2 +- .../query_params_str_validations/tutorial014_an_py39.py | 2 +- .../query_params_str_validations/tutorial014_py310.py | 2 +- docs_src/security/tutorial003_an.py | 4 ++-- docs_src/security/tutorial003_an_py310.py | 4 ++-- docs_src/security/tutorial003_an_py39.py | 4 ++-- docs_src/security/tutorial004.py | 2 +- docs_src/security/tutorial004_an.py | 8 ++++---- docs_src/security/tutorial004_an_py310.py | 8 ++++---- docs_src/security/tutorial004_an_py39.py | 8 ++++---- docs_src/security/tutorial004_py310.py | 2 +- docs_src/security/tutorial005.py | 6 +++--- docs_src/security/tutorial005_an.py | 8 ++++---- docs_src/security/tutorial005_an_py310.py | 8 ++++---- docs_src/security/tutorial005_an_py39.py | 8 ++++---- docs_src/security/tutorial005_py310.py | 6 +++--- docs_src/security/tutorial005_py39.py | 6 +++--- docs_src/security/tutorial007_an.py | 2 +- docs_src/security/tutorial007_an_py39.py | 2 +- fastapi/dependencies/utils.py | 2 +- fastapi/encoders.py | 2 +- pyproject.toml | 8 ++++---- requirements-tests.txt | 2 +- tests/test_param_include_in_schema.py | 6 +++--- tests/test_regex_deprecated_body.py | 2 +- tests/test_regex_deprecated_params.py | 2 +- 44 files changed, 76 insertions(+), 76 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a7f2fb3f2..4d49845d6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.1.2 + rev: v0.2.0 hooks: - id: ruff args: diff --git a/docs_src/dependencies/tutorial005_an.py b/docs_src/dependencies/tutorial005_an.py index 6785099da..1d78c17a2 100644 --- a/docs_src/dependencies/tutorial005_an.py +++ b/docs_src/dependencies/tutorial005_an.py @@ -21,6 +21,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py310.py b/docs_src/dependencies/tutorial005_an_py310.py index 6c0aa0b36..5ccfc62bd 100644 --- a/docs_src/dependencies/tutorial005_an_py310.py +++ b/docs_src/dependencies/tutorial005_an_py310.py @@ -20,6 +20,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py39.py b/docs_src/dependencies/tutorial005_an_py39.py index e8887e162..d5dd8dca9 100644 --- a/docs_src/dependencies/tutorial005_an_py39.py +++ b/docs_src/dependencies/tutorial005_an_py39.py @@ -20,6 +20,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/header_params/tutorial002.py b/docs_src/header_params/tutorial002.py index 639ab1735..0a34f17cc 100644 --- a/docs_src/header_params/tutorial002.py +++ b/docs_src/header_params/tutorial002.py @@ -7,6 +7,6 @@ app = FastAPI() @app.get("/items/") async def read_items( - strange_header: Union[str, None] = Header(default=None, convert_underscores=False) + strange_header: Union[str, None] = Header(default=None, convert_underscores=False), ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an_py310.py b/docs_src/header_params/tutorial002_an_py310.py index b340647b6..8a102749f 100644 --- a/docs_src/header_params/tutorial002_an_py310.py +++ b/docs_src/header_params/tutorial002_an_py310.py @@ -7,6 +7,6 @@ app = FastAPI() @app.get("/items/") async def read_items( - strange_header: Annotated[str | None, Header(convert_underscores=False)] = None + strange_header: Annotated[str | None, Header(convert_underscores=False)] = None, ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_py310.py b/docs_src/header_params/tutorial002_py310.py index b7979b542..10d6716c6 100644 --- a/docs_src/header_params/tutorial002_py310.py +++ b/docs_src/header_params/tutorial002_py310.py @@ -5,6 +5,6 @@ app = FastAPI() @app.get("/items/") async def read_items( - strange_header: str | None = Header(default=None, convert_underscores=False) + strange_header: str | None = Header(default=None, convert_underscores=False), ): return {"strange_header": strange_header} diff --git a/docs_src/query_params_str_validations/tutorial003.py b/docs_src/query_params_str_validations/tutorial003.py index 73d2e08c8..7d4917373 100644 --- a/docs_src/query_params_str_validations/tutorial003.py +++ b/docs_src/query_params_str_validations/tutorial003.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Union[str, None] = Query(default=None, min_length=3, max_length=50) + q: Union[str, None] = Query(default=None, min_length=3, max_length=50), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an.py b/docs_src/query_params_str_validations/tutorial003_an.py index a3665f6a8..0dd14086c 100644 --- a/docs_src/query_params_str_validations/tutorial003_an.py +++ b/docs_src/query_params_str_validations/tutorial003_an.py @@ -8,7 +8,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None + q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an_py310.py b/docs_src/query_params_str_validations/tutorial003_an_py310.py index 836af04de..79a604b6c 100644 --- a/docs_src/query_params_str_validations/tutorial003_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial003_an_py310.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(min_length=3, max_length=50)] = None + q: Annotated[str | None, Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an_py39.py b/docs_src/query_params_str_validations/tutorial003_an_py39.py index 87a426839..3d6697793 100644 --- a/docs_src/query_params_str_validations/tutorial003_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial003_an_py39.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None + q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007.py b/docs_src/query_params_str_validations/tutorial007.py index cb836569e..27b649e14 100644 --- a/docs_src/query_params_str_validations/tutorial007.py +++ b/docs_src/query_params_str_validations/tutorial007.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Union[str, None] = Query(default=None, title="Query string", min_length=3) + q: Union[str, None] = Query(default=None, title="Query string", min_length=3), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an.py b/docs_src/query_params_str_validations/tutorial007_an.py index 3bc85cc0c..4b3c8de4b 100644 --- a/docs_src/query_params_str_validations/tutorial007_an.py +++ b/docs_src/query_params_str_validations/tutorial007_an.py @@ -8,7 +8,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None + q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an_py310.py b/docs_src/query_params_str_validations/tutorial007_an_py310.py index 5933911fd..ef18e500d 100644 --- a/docs_src/query_params_str_validations/tutorial007_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_an_py310.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(title="Query string", min_length=3)] = None + q: Annotated[str | None, Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an_py39.py b/docs_src/query_params_str_validations/tutorial007_an_py39.py index dafa1c5c9..8d7a82c46 100644 --- a/docs_src/query_params_str_validations/tutorial007_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial007_an_py39.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None + q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_py310.py b/docs_src/query_params_str_validations/tutorial007_py310.py index e3e1ef2e0..c283576d5 100644 --- a/docs_src/query_params_str_validations/tutorial007_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_py310.py @@ -5,7 +5,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: str | None = Query(default=None, title="Query string", min_length=3) + q: str | None = Query(default=None, title="Query string", min_length=3), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial014.py b/docs_src/query_params_str_validations/tutorial014.py index 50e0a6c2b..779db1c80 100644 --- a/docs_src/query_params_str_validations/tutorial014.py +++ b/docs_src/query_params_str_validations/tutorial014.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Union[str, None] = Query(default=None, include_in_schema=False) + hidden_query: Union[str, None] = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an.py b/docs_src/query_params_str_validations/tutorial014_an.py index a9a9c4427..2eaa58540 100644 --- a/docs_src/query_params_str_validations/tutorial014_an.py +++ b/docs_src/query_params_str_validations/tutorial014_an.py @@ -8,7 +8,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None + hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py310.py b/docs_src/query_params_str_validations/tutorial014_an_py310.py index 5fba54150..e728dbdb5 100644 --- a/docs_src/query_params_str_validations/tutorial014_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_an_py310.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None + hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py39.py b/docs_src/query_params_str_validations/tutorial014_an_py39.py index b07985210..aaf7703a5 100644 --- a/docs_src/query_params_str_validations/tutorial014_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial014_an_py39.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None + hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_py310.py b/docs_src/query_params_str_validations/tutorial014_py310.py index 1b617efdd..97bb3386e 100644 --- a/docs_src/query_params_str_validations/tutorial014_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_py310.py @@ -5,7 +5,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: str | None = Query(default=None, include_in_schema=False) + hidden_query: str | None = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/security/tutorial003_an.py b/docs_src/security/tutorial003_an.py index 261cb4857..8fb40dd4a 100644 --- a/docs_src/security/tutorial003_an.py +++ b/docs_src/security/tutorial003_an.py @@ -68,7 +68,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -90,6 +90,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial003_an_py310.py b/docs_src/security/tutorial003_an_py310.py index a03f4f8bf..ced4a2fbc 100644 --- a/docs_src/security/tutorial003_an_py310.py +++ b/docs_src/security/tutorial003_an_py310.py @@ -67,7 +67,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -89,6 +89,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial003_an_py39.py b/docs_src/security/tutorial003_an_py39.py index 308dbe798..068a3933e 100644 --- a/docs_src/security/tutorial003_an_py39.py +++ b/docs_src/security/tutorial003_an_py39.py @@ -67,7 +67,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -89,6 +89,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 044eec700..d0fbaa572 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -114,7 +114,7 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index c78e8496c..eebd36d64 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -108,7 +108,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -117,7 +117,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -135,13 +135,13 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 36dbc677e..4e50ada7c 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -107,7 +107,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -116,7 +116,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -134,13 +134,13 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index 23fc04a72..eb49aaa67 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -107,7 +107,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -116,7 +116,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -134,13 +134,13 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 8363d45ab..5a905783d 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -113,7 +113,7 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index b16bf440a..d4a6975da 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -136,7 +136,7 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +145,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -165,7 +165,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index 95e406b32..982daed2f 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -137,7 +137,7 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -146,7 +146,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -161,14 +161,14 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index c6116a5ed..79aafbff1 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -136,7 +136,7 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +145,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -160,14 +160,14 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index af51c08b5..3bdab5507 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -136,7 +136,7 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +145,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -160,14 +160,14 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index 37a22c709..9f75aa0be 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -135,7 +135,7 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -144,7 +144,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -164,7 +164,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index c27580763..bac248932 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -136,7 +136,7 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +145,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -165,7 +165,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial007_an.py b/docs_src/security/tutorial007_an.py index 9e9c3cd70..0d211dfde 100644 --- a/docs_src/security/tutorial007_an.py +++ b/docs_src/security/tutorial007_an.py @@ -10,7 +10,7 @@ security = HTTPBasic() def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] + credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" diff --git a/docs_src/security/tutorial007_an_py39.py b/docs_src/security/tutorial007_an_py39.py index 3d9ea2726..87ef98657 100644 --- a/docs_src/security/tutorial007_an_py39.py +++ b/docs_src/security/tutorial007_an_py39.py @@ -10,7 +10,7 @@ security = HTTPBasic() def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] + credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index b73473484..02284b4ed 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -743,7 +743,7 @@ async def request_body_to_args( results: List[Union[bytes, str]] = [] async def process_fn( - fn: Callable[[], Coroutine[Any, Any, Any]] + fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 diff --git a/fastapi/encoders.py b/fastapi/encoders.py index e50171393..431387f71 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -86,7 +86,7 @@ ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { def generate_encoders_by_class_tuples( - type_encoder_map: Dict[Any, Callable[[Any], Any]] + type_encoder_map: Dict[Any, Callable[[Any], Any]], ) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( tuple diff --git a/pyproject.toml b/pyproject.toml index c23e82ef4..24dc5ab77 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -139,7 +139,7 @@ omit = [ "docs_src/response_model/tutorial003_04_py310.py", ] -[tool.ruff] +[tool.ruff.lint] select = [ "E", # pycodestyle errors "W", # pycodestyle warnings @@ -155,7 +155,7 @@ ignore = [ "W191", # indentation contains tabs ] -[tool.ruff.per-file-ignores] +[tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "docs_src/dependencies/tutorial007.py" = ["F821"] "docs_src/dependencies/tutorial008.py" = ["F821"] @@ -188,9 +188,9 @@ ignore = [ "docs_src/dependencies/tutorial008b_an_py39.py" = ["B904"] -[tool.ruff.isort] +[tool.ruff.lint.isort] known-third-party = ["fastapi", "pydantic", "starlette"] -[tool.ruff.pyupgrade] +[tool.ruff.lint.pyupgrade] # Preserve types, even if a file imports `from __future__ import annotations`. keep-runtime-typing = true diff --git a/requirements-tests.txt b/requirements-tests.txt index a5586c5ce..09ca9cb52 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -4,7 +4,7 @@ pydantic-settings >=2.0.0 pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.4.1 -ruff ==0.1.2 +ruff ==0.2.0 email_validator >=1.1.1,<3.0.0 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy diff --git a/tests/test_param_include_in_schema.py b/tests/test_param_include_in_schema.py index 26201e9e2..f461947c9 100644 --- a/tests/test_param_include_in_schema.py +++ b/tests/test_param_include_in_schema.py @@ -9,14 +9,14 @@ app = FastAPI() @app.get("/hidden_cookie") async def hidden_cookie( - hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False) + hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False), ): return {"hidden_cookie": hidden_cookie} @app.get("/hidden_header") async def hidden_header( - hidden_header: Optional[str] = Header(default=None, include_in_schema=False) + hidden_header: Optional[str] = Header(default=None, include_in_schema=False), ): return {"hidden_header": hidden_header} @@ -28,7 +28,7 @@ async def hidden_path(hidden_path: str = Path(include_in_schema=False)): @app.get("/hidden_query") async def hidden_query( - hidden_query: Optional[str] = Query(default=None, include_in_schema=False) + hidden_query: Optional[str] = Query(default=None, include_in_schema=False), ): return {"hidden_query": hidden_query} diff --git a/tests/test_regex_deprecated_body.py b/tests/test_regex_deprecated_body.py index ca1ab514c..7afddd9ae 100644 --- a/tests/test_regex_deprecated_body.py +++ b/tests/test_regex_deprecated_body.py @@ -14,7 +14,7 @@ def get_client(): @app.post("/items/") async def read_items( - q: Annotated[str | None, Form(regex="^fixedquery$")] = None + q: Annotated[str | None, Form(regex="^fixedquery$")] = None, ): if q: return f"Hello {q}" diff --git a/tests/test_regex_deprecated_params.py b/tests/test_regex_deprecated_params.py index 79a653353..7190b543c 100644 --- a/tests/test_regex_deprecated_params.py +++ b/tests/test_regex_deprecated_params.py @@ -14,7 +14,7 @@ def get_client(): @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(regex="^fixedquery$")] = None + q: Annotated[str | None, Query(regex="^fixedquery$")] = None, ): if q: return f"Hello {q}" From 910413e2155c14a342363ff5eb31881101cbac4d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 26 Mar 2024 16:57:16 +0000 Subject: [PATCH 081/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b2a11b7dd..34efb633e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* ⬆️ Upgrade configuration for Ruff v0.2.0. PR [#11075](https://github.com/tiangolo/fastapi/pull/11075) by [@charliermarsh](https://github.com/charliermarsh). * 🔧 Update sponsors, add MongoDB. PR [#11346](https://github.com/tiangolo/fastapi/pull/11346) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump dorny/paths-filter from 2 to 3. PR [#11028](https://github.com/tiangolo/fastapi/pull/11028) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 3.0.0 to 3.1.4. PR [#11310](https://github.com/tiangolo/fastapi/pull/11310) by [@dependabot[bot]](https://github.com/apps/dependabot). From d0fcfd0dff42128cf8e45a72046e6a28c85518fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 26 Mar 2024 12:38:21 -0500 Subject: [PATCH 082/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20Ruff=20config,?= =?UTF-8?q?=20add=20extra=20ignore=20rule=20from=20SQLModel=20(#11353)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/people/app/main.py | 2 +- pyproject.toml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index 657f2bf5e..9f2b9369d 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -378,7 +378,7 @@ def get_discussion_nodes(settings: Settings) -> List[DiscussionsNode]: def get_discussions_experts( - discussion_nodes: List[DiscussionsNode] + discussion_nodes: List[DiscussionsNode], ) -> DiscussionExpertsResults: commenters = Counter() last_month_commenters = Counter() diff --git a/pyproject.toml b/pyproject.toml index 24dc5ab77..c3801600a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -152,6 +152,7 @@ select = [ ignore = [ "E501", # line too long, handled by black "B008", # do not perform function calls in argument defaults + "C901", # too complex "W191", # indentation contains tabs ] From 8bfed9aee2401a937bc38f336cddd903722c5286 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 26 Mar 2024 17:38:55 +0000 Subject: [PATCH 083/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 34efb633e..889f0a7c0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 🔧 Update Ruff config, add extra ignore rule from SQLModel. PR [#11353](https://github.com/tiangolo/fastapi/pull/11353) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade configuration for Ruff v0.2.0. PR [#11075](https://github.com/tiangolo/fastapi/pull/11075) by [@charliermarsh](https://github.com/charliermarsh). * 🔧 Update sponsors, add MongoDB. PR [#11346](https://github.com/tiangolo/fastapi/pull/11346) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump dorny/paths-filter from 2 to 3. PR [#11028](https://github.com/tiangolo/fastapi/pull/11028) by [@dependabot[bot]](https://github.com/apps/dependabot). From 8953d23a2b1707b7bdea416f3161d83f57f2e7a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 26 Mar 2024 22:02:41 -0500 Subject: [PATCH 084/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20build-docs=20Gi?= =?UTF-8?q?tHub=20Action=20path=20filter=20(#11354)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build-docs.yml | 3 +++ .github/workflows/publish.yml | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index a4667b61e..c81f800e5 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -28,6 +28,9 @@ jobs: - docs/** - docs_src/** - requirements-docs.txt + - pyproject.toml + - mkdocs.yml + - mkdocs.insiders.yml - .github/workflows/build-docs.yml - .github/workflows/deploy-docs.yml langs: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8ebb28a80..ce54ca4fe 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -20,7 +20,7 @@ jobs: python-version: "3.10" # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" - cache-dependency-path: pyproject.toml + # cache-dependency-path: pyproject.toml - uses: actions/cache@v3 id: cache with: From 040448811a6e4524607e438d5b1d3e8f203d2c62 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 27 Mar 2024 03:03:01 +0000 Subject: [PATCH 085/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 889f0a7c0..b748f1d17 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 👷 Update build-docs GitHub Action path filter. PR [#11354](https://github.com/tiangolo/fastapi/pull/11354) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Ruff config, add extra ignore rule from SQLModel. PR [#11353](https://github.com/tiangolo/fastapi/pull/11353) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade configuration for Ruff v0.2.0. PR [#11075](https://github.com/tiangolo/fastapi/pull/11075) by [@charliermarsh](https://github.com/charliermarsh). * 🔧 Update sponsors, add MongoDB. PR [#11346](https://github.com/tiangolo/fastapi/pull/11346) by [@tiangolo](https://github.com/tiangolo). From ff41af83a4d1a4b104678638d1173b998468cc56 Mon Sep 17 00:00:00 2001 From: Samuel Favarin <samuelbfavarin@hotmail.com> Date: Thu, 28 Mar 2024 05:05:17 +0100 Subject: [PATCH 086/846] :globe_with_meridians: Add Portuguese translation for `docs/pt/docs/advanced/templates.md` (#11338) --- docs/pt/docs/advanced/templates.md | 119 +++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 docs/pt/docs/advanced/templates.md diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md new file mode 100644 index 000000000..3bada5e43 --- /dev/null +++ b/docs/pt/docs/advanced/templates.md @@ -0,0 +1,119 @@ +# Templates + +Você pode usar qualquer template engine com o **FastAPI**. + +Uma escolha comum é o Jinja2, o mesmo usado pelo Flask e outras ferramentas. + +Existem utilitários para configurá-lo facilmente que você pode usar diretamente em sua aplicação **FastAPI** (fornecidos pelo Starlette). + +## Instalação de dependências + +Para instalar o `jinja2`, siga o código abaixo: + +<div class="termy"> + +```console +$ pip install jinja2 +``` + +</div> + +## Usando `Jinja2Templates` + +* Importe `Jinja2Templates`. +* Crie um `templates` que você possa reutilizar posteriormente. +* 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!} +``` + +!!! note + Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. + + Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. + + +!!! tip "Dica" + Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. + + +!!! note "Detalhes Técnicos" + Você também poderia usar `from starlette.templating import Jinja2Templates`. + + **FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. + +## Escrevendo Templates + +Então você pode escrever um template em `templates/item.html`, por exemplo: + +```jinja hl_lines="7" +{!../../../docs_src/templates/templates/item.html!} +``` + +### Interpolação de Valores no Template + +No código HTML que contém: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...aparecerá o `id` obtido do "context" `dict` que você passou: + +```Python +{"id": id} +``` + +Por exemplo, dado um ID de valor `42`, aparecerá: + +```html +Item ID: 42 +``` + +### Argumentos do `url_for` + +Você também pode usar `url_for()` dentro do template, ele recebe como argumentos os mesmos argumentos que seriam usados pela sua *path operation function*. + +Logo, a seção com: + +{% raw %} + +```jinja +<a href="{{ url_for('read_item', id=id) }}"> +``` + +{% endraw %} + +...irá gerar um link para a mesma URL que será tratada pela *path operation function* `read_item(id=id)`. + +Por exemplo, com um ID de `42`, isso renderizará: + +```html +<a href="/items/42"> +``` + +## Templates e Arquivos Estáticos + +Você também pode usar `url_for()` dentro do template e usá-lo, por examplo, com o `StaticFiles` que você montou com o `name="static"`. + +```jinja hl_lines="4" +{!../../../docs_src/templates/templates/item.html!} +``` + +Neste exemplo, ele seria vinculado a um arquivo CSS em `static/styles.css` com: + +```CSS hl_lines="4" +{!../../../docs_src/templates/static/styles.css!} +``` + +E como você está usando `StaticFiles`, este arquivo CSS será automaticamente servido pela sua aplicação FastAPI na URL `/static/styles.css`. + +## Mais detalhes + +Para obter mais detalhes, incluindo como testar templates, consulte a <a href="https://www.starlette.io/templates/" class="external-link" target="_blank">documentação da Starlette sobre templates</a>. From cb0ab4322456c52a3b8463d217f3445a82cbbf9c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 28 Mar 2024 04:05:40 +0000 Subject: [PATCH 087/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b748f1d17..677eac267 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Translations +* :globe_with_meridians: Add Portuguese translation for `docs/pt/docs/advanced/templates.md`. PR [#11338](https://github.com/tiangolo/fastapi/pull/11338) by [@SamuelBFavarin](https://github.com/SamuelBFavarin). * 🌐 Add Bengali translations for `docs/bn/docs/learn/index.md`. PR [#11337](https://github.com/tiangolo/fastapi/pull/11337) by [@imtiaz101325](https://github.com/imtiaz101325). * 🌐 Fix Korean translation for `docs/ko/docs/index.md`. PR [#11296](https://github.com/tiangolo/fastapi/pull/11296) by [@choi-haram](https://github.com/choi-haram). * 🌐 Add Korean translation for `docs/ko/docs/about/index.md`. PR [#11299](https://github.com/tiangolo/fastapi/pull/11299) by [@choi-haram](https://github.com/choi-haram). From cd3e2bc2d27ef5a026fff39f7b65cd36673ea055 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 28 Mar 2024 18:28:07 -0500 Subject: [PATCH 088/846] =?UTF-8?q?=F0=9F=91=B7=20Add=20CI=20to=20test=20s?= =?UTF-8?q?dists=20for=20redistribution=20(e.g.=20Linux=20distros)=20(#113?= =?UTF-8?q?65)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test-redistribute.yml | 51 +++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 .github/workflows/test-redistribute.yml diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml new file mode 100644 index 000000000..c2e05013b --- /dev/null +++ b/.github/workflows/test-redistribute.yml @@ -0,0 +1,51 @@ +name: Test Redistribute + +on: + push: + branches: + - master + pull_request: + types: + - opened + - synchronize + +jobs: + test-redistribute: + runs-on: ubuntu-latest + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.10" + # Issue ref: https://github.com/actions/setup-python/issues/436 + # cache: "pip" + # cache-dependency-path: pyproject.toml + - name: Install build dependencies + run: pip install build + - name: Build source distribution + run: python -m build --sdist + - name: Decompress source distribution + run: | + cd dist + tar xvf fastapi*.tar.gz + - name: Install test dependencies + run: | + cd dist/fastapi-*/ + pip install -r requirements-tests.txt + - name: Run source distribution tests + run: | + cd dist/fastapi-*/ + bash scripts/test.sh + - name: Build wheel distribution + run: | + cd dist + pip wheel --no-deps fastapi-*.tar.gz + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" From 43160896c5cc9163d9f862e0bd1af931c7acd5bd Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 28 Mar 2024 23:28:29 +0000 Subject: [PATCH 089/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 677eac267..d5ccca675 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -36,6 +36,7 @@ hide: ### Internal +* 👷 Add CI to test sdists for redistribution (e.g. Linux distros). PR [#11365](https://github.com/tiangolo/fastapi/pull/11365) by [@tiangolo](https://github.com/tiangolo). * 👷 Update build-docs GitHub Action path filter. PR [#11354](https://github.com/tiangolo/fastapi/pull/11354) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Ruff config, add extra ignore rule from SQLModel. PR [#11353](https://github.com/tiangolo/fastapi/pull/11353) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade configuration for Ruff v0.2.0. PR [#11075](https://github.com/tiangolo/fastapi/pull/11075) by [@charliermarsh](https://github.com/charliermarsh). From 04249d589bc22baae902e40ac004de37056642f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 28 Mar 2024 18:32:17 -0500 Subject: [PATCH 090/846] =?UTF-8?q?=F0=9F=91=B7=20Do=20not=20use=20Python?= =?UTF-8?q?=20packages=20cache=20for=20publish=20(#11366)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/publish.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ce54ca4fe..899e49057 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -21,13 +21,7 @@ jobs: # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" # cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 - id: cache - with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish - name: Install build dependencies - if: steps.cache.outputs.cache-hit != 'true' run: pip install build - name: Build distribution run: python -m build From 461420719dddc122bb3fa21d3a7a2d095f32746e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 28 Mar 2024 23:32:41 +0000 Subject: [PATCH 091/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d5ccca675..a1ca3712a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -36,6 +36,7 @@ hide: ### Internal +* 👷 Do not use Python packages cache for publish. PR [#11366](https://github.com/tiangolo/fastapi/pull/11366) by [@tiangolo](https://github.com/tiangolo). * 👷 Add CI to test sdists for redistribution (e.g. Linux distros). PR [#11365](https://github.com/tiangolo/fastapi/pull/11365) by [@tiangolo](https://github.com/tiangolo). * 👷 Update build-docs GitHub Action path filter. PR [#11354](https://github.com/tiangolo/fastapi/pull/11354) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Ruff config, add extra ignore rule from SQLModel. PR [#11353](https://github.com/tiangolo/fastapi/pull/11353) by [@tiangolo](https://github.com/tiangolo). From 11b3c7e791c61c3e91be5ea4e87b9f0c38e5f466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 29 Mar 2024 15:35:31 -0500 Subject: [PATCH 092/846] =?UTF-8?q?=F0=9F=91=B7=20Fix=20logic=20for=20when?= =?UTF-8?q?=20to=20install=20and=20use=20MkDocs=20Insiders=20(#11372)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build-docs.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index c81f800e5..9b167ee66 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -49,7 +49,7 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v06 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v07 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt @@ -90,12 +90,12 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v06 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v08 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.secret_source != 'Actions' ) && steps.cache.outputs.cache-hit != 'true' + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' run: | pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git From b37426329a53cacc18aaa01fabef86cb780bf8c2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 29 Mar 2024 20:35:51 +0000 Subject: [PATCH 093/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a1ca3712a..b155512de 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -36,6 +36,7 @@ hide: ### Internal +* 👷 Fix logic for when to install and use MkDocs Insiders. PR [#11372](https://github.com/tiangolo/fastapi/pull/11372) by [@tiangolo](https://github.com/tiangolo). * 👷 Do not use Python packages cache for publish. PR [#11366](https://github.com/tiangolo/fastapi/pull/11366) by [@tiangolo](https://github.com/tiangolo). * 👷 Add CI to test sdists for redistribution (e.g. Linux distros). PR [#11365](https://github.com/tiangolo/fastapi/pull/11365) by [@tiangolo](https://github.com/tiangolo). * 👷 Update build-docs GitHub Action path filter. PR [#11354](https://github.com/tiangolo/fastapi/pull/11354) by [@tiangolo](https://github.com/tiangolo). From 5a30f8226438764e0ae44f59c48280bb8e9ec9cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 29 Mar 2024 15:50:47 -0500 Subject: [PATCH 094/846] =?UTF-8?q?=F0=9F=91=B7=20Disable=20MkDocs=20insid?= =?UTF-8?q?ers=20social=20plugin=20while=20an=20issue=20in=20MkDocs=20Mate?= =?UTF-8?q?rial=20is=20handled=20(#11373)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.insiders.yml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index d204974b8..8f3538a80 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -1,7 +1,8 @@ plugins: - social: - cards_layout_dir: ../en/layouts - cards_layout: custom - cards_layout_options: - logo: ../en/docs/img/icon-white.svg + # TODO: Re-enable once this is fixed: https://github.com/squidfunk/mkdocs-material/issues/6983 + # social: + # cards_layout_dir: ../en/layouts + # cards_layout: custom + # cards_layout_options: + # logo: ../en/docs/img/icon-white.svg typeset: From b8f8c559913644ef7892aecc171473a3d7eee7be Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 29 Mar 2024 20:51:06 +0000 Subject: [PATCH 095/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b155512de..3827c968f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -36,6 +36,7 @@ hide: ### Internal +* 👷 Disable MkDocs insiders social plugin while an issue in MkDocs Material is handled. PR [#11373](https://github.com/tiangolo/fastapi/pull/11373) by [@tiangolo](https://github.com/tiangolo). * 👷 Fix logic for when to install and use MkDocs Insiders. PR [#11372](https://github.com/tiangolo/fastapi/pull/11372) by [@tiangolo](https://github.com/tiangolo). * 👷 Do not use Python packages cache for publish. PR [#11366](https://github.com/tiangolo/fastapi/pull/11366) by [@tiangolo](https://github.com/tiangolo). * 👷 Add CI to test sdists for redistribution (e.g. Linux distros). PR [#11365](https://github.com/tiangolo/fastapi/pull/11365) by [@tiangolo](https://github.com/tiangolo). From 009b14846362b0249303e49d00c3187859a5e176 Mon Sep 17 00:00:00 2001 From: Sun Bin <165283125+shandongbinzhou@users.noreply.github.com> Date: Sat, 30 Mar 2024 07:06:20 +0800 Subject: [PATCH 096/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`fastapi/security/oauth2.py`=20(#11368)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/security/oauth2.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 0606291b8..d7ba44bce 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -54,7 +54,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 similar, and get the two parts `items` and `read`. Many applications do that to - group and organize permisions, you could do it as well in your application, just + 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. """ @@ -196,7 +196,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 similar, and get the two parts `items` and `read`. Many applications do that to - group and organize permisions, you could do it as well in your application, just + 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 f324f31dda42db5ec881b4f748038cdefcc02da7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 29 Mar 2024 23:06:40 +0000 Subject: [PATCH 097/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3827c968f..62a66adf6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#11368](https://github.com/tiangolo/fastapi/pull/11368) by [@shandongbinzhou](https://github.com/shandongbinzhou). * 📝 Update links to Pydantic docs to point to new website. PR [#11328](https://github.com/tiangolo/fastapi/pull/11328) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo in `docs/en/docs/tutorial/extra-models.md`. PR [#11329](https://github.com/tiangolo/fastapi/pull/11329) by [@alejsdev](https://github.com/alejsdev). * 📝 Update `project-generation.md`. PR [#11326](https://github.com/tiangolo/fastapi/pull/11326) by [@alejsdev](https://github.com/alejsdev). From 0c14608618b0d0f1c4160b4ad3de248bed4f0da5 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 18:58:08 +0100 Subject: [PATCH 098/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/request-files.md`=20(#10364)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/request-files.md | 314 +++++++++++++++++++++++++ 1 file changed, 314 insertions(+) create mode 100644 docs/de/docs/tutorial/request-files.md diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md new file mode 100644 index 000000000..67b5e3a87 --- /dev/null +++ b/docs/de/docs/tutorial/request-files.md @@ -0,0 +1,314 @@ +# Dateien im Request + +Mit `File` können sie vom Client hochzuladende Dateien definieren. + +!!! info + Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + + Z. B. `pip install python-multipart`. + + Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. + +## `File` importieren + +Importieren Sie `File` und `UploadFile` von `fastapi`: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +## `File`-Parameter definieren + +Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +!!! info + `File` ist eine Klasse, die direkt von `Form` erbt. + + Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben + +!!! tip "Tipp" + Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. + +Die Dateien werden als „Formulardaten“ hochgeladen. + +Wenn Sie den Typ Ihrer *Pfadoperation-Funktion* als `bytes` deklarieren, wird **FastAPI** die Datei für Sie auslesen, und Sie erhalten den Inhalt als `bytes`. + +Bedenken Sie, dass das bedeutet, dass sich der gesamte Inhalt der Datei im Arbeitsspeicher befindet. Das wird für kleinere Dateien gut funktionieren. + +Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwenden. + +## Datei-Parameter mit `UploadFile` + +Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="13" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: + +* Sie müssen `File()` nicht als Parameter-Defaultwert verwenden. +* Es wird eine <abbr title='Aufgespult, Warteschlangenartig'>„Spool“</abbr>-Datei verwendet: + * Eine Datei, die bis zu einem bestimmten Größen-Limit im Arbeitsspeicher behalten wird, und wenn das Limit überschritten wird, auf der Festplatte gespeichert wird. +* Das bedeutet, es wird für große Dateien wie Bilder, Videos, große Binärdateien, usw. gut funktionieren, ohne den ganzen Arbeitsspeicher aufzubrauchen. +* Sie können Metadaten aus der hochgeladenen Datei auslesen. +* Es hat eine <abbr title="dateiartig"><a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a></abbr> `async`hrone Schnittstelle. +* Es stellt ein tatsächliches Python-<abbr title="Warteschlangenartige, temporäre Datei"><a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a></abbr>-Objekt bereit, welches Sie direkt anderen Bibliotheken übergeben können, die ein dateiartiges Objekt erwarten. + +### `UploadFile` + +`UploadFile` hat die folgenden Attribute: + +* `filename`: Ein `str` mit dem ursprünglichen Namen der hochgeladenen Datei (z. B. `meinbild.jpg`). +* `content_type`: Ein `str` mit dem Inhaltstyp (MIME-Typ / Medientyp) (z. B. `image/jpeg`). +* `file`: Ein <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> (ein <a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a> Objekt). Das ist das tatsächliche Python-Objekt, das Sie direkt anderen Funktionen oder Bibliotheken übergeben können, welche ein „file-like“-Objekt erwarten. + +`UploadFile` hat die folgenden `async`hronen Methoden. Sie alle rufen die entsprechenden Methoden des darunterliegenden Datei-Objekts auf (wobei intern `SpooledTemporaryFile` verwendet wird). + +* `write(daten)`: Schreibt `daten` (`str` oder `bytes`) in die Datei. +* `read(anzahl)`: Liest `anzahl` (`int`) bytes/Zeichen aus der Datei. +* `seek(versatz)`: Geht zur Position `versatz` (`int`) in der Datei. + * Z. B. würde `await myfile.seek(0)` zum Anfang der Datei gehen. + * Das ist besonders dann nützlich, wenn Sie `await myfile.read()` einmal ausführen und dann diese Inhalte erneut auslesen müssen. +* `close()`: Schließt die Datei. + +Da alle diese Methoden `async`hron sind, müssen Sie sie `await`en („erwarten“). + +Zum Beispiel können Sie innerhalb einer `async` *Pfadoperation-Funktion* den Inhalt wie folgt auslesen: + +```Python +contents = await myfile.read() +``` + +Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, können Sie direkt auf `UploadFile.file` zugreifen, zum Beispiel: + +```Python +contents = myfile.file.read() +``` + +!!! note "Technische Details zu `async`" + Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem <abbr title="Mehrere unabhängige Kindprozesse">Threadpool</abbr> aus und erwartet sie. + +!!! 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. + +## Was sind „Formulardaten“ + +HTML-Formulare (`<form></form>`) senden die Daten in einer „speziellen“ Kodierung zum Server, welche sich von JSON unterscheidet. + +**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. + +!!! note "Technische Details" + Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert. + + Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss. + + Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>. + +!!! warning "Achtung" + Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + + Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +## Optionaler Datei-Upload + +Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: + +=== "Python 3.10+" + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10 18" + {!> ../../../docs_src/request_files/tutorial001_02_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## `UploadFile` mit zusätzlichen Metadaten + +Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: + +=== "Python 3.9+" + + ```Python hl_lines="9 15" + {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 14" + {!> ../../../docs_src/request_files/tutorial001_03_an.py!} + ``` + +=== "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!} + ``` + +## Mehrere Datei-Uploads + +Es ist auch möglich, mehrere Dateien gleichzeitig hochzuladen. + +Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten gesendet wird. + +Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/request_files/tutorial002_an.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/request_files/tutorial002_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002.py!} + ``` + +Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. + +!!! note "Technische Details" + Sie können auch `from starlette.responses import HTMLResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +### Mehrere Datei-Uploads mit zusätzlichen Metadaten + +Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="11 18-20" + {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12 19-21" + {!> ../../../docs_src/request_files/tutorial003_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Zusammenfassung + +Verwenden Sie `File`, `bytes` und `UploadFile`, um hochladbare Dateien im Request zu deklarieren, die als Formulardaten gesendet werden. From ab7494f2888bb0c07dbc02e2a4d1d7feb1cc5d16 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 17:58:36 +0000 Subject: [PATCH 099/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 62a66adf6..678d75603 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/request-files.md`. PR [#10364](https://github.com/tiangolo/fastapi/pull/10364) by [@nilslindemann](https://github.com/nilslindemann). * :globe_with_meridians: Add Portuguese translation for `docs/pt/docs/advanced/templates.md`. PR [#11338](https://github.com/tiangolo/fastapi/pull/11338) by [@SamuelBFavarin](https://github.com/SamuelBFavarin). * 🌐 Add Bengali translations for `docs/bn/docs/learn/index.md`. PR [#11337](https://github.com/tiangolo/fastapi/pull/11337) by [@imtiaz101325](https://github.com/imtiaz101325). * 🌐 Fix Korean translation for `docs/ko/docs/index.md`. PR [#11296](https://github.com/tiangolo/fastapi/pull/11296) by [@choi-haram](https://github.com/choi-haram). From 372e2c84e56351b94207052730f776102d99057b Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 18:58:59 +0100 Subject: [PATCH 100/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/query-params-str-validations.?= =?UTF-8?q?md`=20(#10304)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/query-params-str-validations.md | 914 ++++++++++++++++++ 1 file changed, 914 insertions(+) create mode 100644 docs/de/docs/tutorial/query-params-str-validations.md diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md new file mode 100644 index 000000000..92f2bbe7c --- /dev/null +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,914 @@ +# Query-Parameter und Stringvalidierung + +**FastAPI** erlaubt es Ihnen, Ihre Parameter zusätzlich zu validieren, und zusätzliche Informationen hinzuzufügen. + +Nehmen wir als Beispiel die folgende Anwendung: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} + ``` + +Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich. + +!!! note "Hinweis" + FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist + + `Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen. + +## Zusätzliche Validierung + +Wir werden bewirken, dass, obwohl `q` optional ist, wenn es gegeben ist, **seine Länge 50 Zeichen nicht überschreitet**. + +### `Query` und `Annotated` importieren + +Importieren Sie zuerst: + +* `Query` von `fastapi` +* `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9) + +=== "Python 3.10+" + + In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. + + ```Python hl_lines="1 3" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} + ``` + +=== "Python 3.8+" + + In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`. + + Es wird bereits mit FastAPI installiert sein. + + ```Python hl_lines="3-4" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} + ``` + +!!! info + FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + + Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + + Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +## `Annotated` im Typ des `q`-Parameters verwenden + +Erinnern Sie sich, wie ich in [Einführung in Python-Typen](../python-types.md#typhinweise-mit-metadaten-annotationen){.internal-link target=_blank} sagte, dass Sie mittels `Annotated` Metadaten zu Ihren Parametern hinzufügen können? + +Jetzt ist es an der Zeit, das mit FastAPI auszuprobieren. 🚀 + +Wir hatten diese Typannotation: + +=== "Python 3.10+" + + ```Python + q: str | None = None + ``` + +=== "Python 3.8+" + + ```Python + q: Union[str, None] = None + ``` + +Wir wrappen das nun in `Annotated`, sodass daraus wird: + +=== "Python 3.10+" + + ```Python + q: Annotated[str | None] = None + ``` + +=== "Python 3.8+" + + ```Python + q: Annotated[Union[str, None]] = None + ``` + +Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`. + +Wenden wir uns jetzt den spannenden Dingen zu. 🎉 + +## `Query` zu `Annotated` im `q`-Parameter hinzufügen + +Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} + ``` + +Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist. + +Aber jetzt, mit `Query(max_length=50)` innerhalb von `Annotated`, sagen wir FastAPI, dass es diesen Wert aus den Query-Parametern extrahieren soll (das hätte es sowieso gemacht 🤷) und dass wir eine **zusätzliche Validierung** für diesen Wert haben wollen (darum machen wir das, um die zusätzliche Validierung zu bekommen). 😎 + +FastAPI wird nun: + +* Die Daten **validieren** und sicherstellen, dass sie nicht länger als 50 Zeichen sind +* Dem Client einen **verständlichen Fehler** anzeigen, wenn die Daten ungültig sind +* Den Parameter in der OpenAPI-Schema-*Pfadoperation* **dokumentieren** (sodass er in der **automatischen Dokumentation** angezeigt wird) + +## Alternativ (alt): `Query` als Defaultwert + +Frühere Versionen von FastAPI (vor <abbr title="vor 2023-03">0.95.0</abbr>) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen. + +!!! tip "Tipp" + Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 + +So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} + ``` + +Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI). + +Sprich: + +```Python +q: Union[str, None] = Query(default=None) +``` + +... macht den Parameter optional, mit dem Defaultwert `None`, genauso wie: + +```Python +q: Union[str, None] = None +``` + +Und in Python 3.10 und darüber macht: + +```Python +q: str | None = Query(default=None) +``` + +... den Parameter optional, mit dem Defaultwert `None`, genauso wie: + +```Python +q: str | None = None +``` + +Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren. + +!!! info + Bedenken Sie, dass: + + ```Python + = None + ``` + + oder: + + ```Python + = Query(default=None) + ``` + + der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht. + + Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist. + +Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird: + +```Python +q: Union[str, None] = Query(default=None, max_length=50) +``` + +Das wird die Daten validieren, einen verständlichen Fehler ausgeben, wenn die Daten nicht gültig sind, und den Parameter in der OpenAPI-Schema-*Pfadoperation* dokumentieren. + +### `Query` als Defaultwert oder in `Annotated` + +Bedenken Sie, dass wenn Sie `Query` innerhalb von `Annotated` benutzen, Sie den `default`-Parameter für `Query` nicht verwenden dürfen. + +Setzen Sie stattdessen den Defaultwert des Funktionsparameters, sonst wäre es inkonsistent. + +Zum Beispiel ist das nicht erlaubt: + +```Python +q: Annotated[str, Query(default="rick")] = "morty" +``` + +... denn es wird nicht klar, ob der Defaultwert `"rick"` oder `"morty"` sein soll. + +Sie würden also (bevorzugt) schreiben: + +```Python +q: Annotated[str, Query()] = "rick" +``` + +In älterem Code werden Sie auch finden: + +```Python +q: str = Query(default="rick") +``` + +### Vorzüge von `Annotated` + +**Es wird empfohlen, `Annotated` zu verwenden**, statt des Defaultwertes im Funktionsparameter, das ist aus mehreren Gründen **besser**: 🤓 + +Der **Default**wert des **Funktionsparameters** ist der **tatsächliche Default**wert, das spielt generell intuitiver mit Python zusammen. 😌 + +Sie können die Funktion ohne FastAPI an **anderen Stellen aufrufen**, und es wird **wie erwartet funktionieren**. Wenn es einen **erforderlichen** Parameter gibt (ohne Defaultwert), und Sie führen die Funktion ohne den benötigten Parameter aus, dann wird Ihr **Editor** Sie das mit einem Fehler wissen lassen, und **Python** wird sich auch beschweren. + +Wenn Sie aber nicht `Annotated` benutzen und stattdessen die **(alte) Variante mit einem Defaultwert**, dann müssen Sie, wenn Sie die Funktion ohne FastAPI an **anderen Stellen** aufrufen, sich daran **erinnern**, die Argumente der Funktion zu übergeben, damit es richtig funktioniert. Ansonsten erhalten Sie unerwartete Werte (z. B. `QueryInfo` oder etwas Ähnliches, statt `str`). Ihr Editor kann ihnen nicht helfen, und Python wird die Funktion ohne Beschwerden ausführen, es sei denn, die Operationen innerhalb lösen einen Fehler aus. + +Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch mit anderen Tools verwenden, wie etwa <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">Typer</a>. 🚀 + +## Mehr Validierungen hinzufügen + +Sie können auch einen Parameter `min_length` hinzufügen: + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} + ``` + +=== "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/tutorial003_py310.py!} + ``` + +=== "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/tutorial003.py!} + ``` + +## Reguläre Ausdrücke hinzufügen + +Sie können einen <abbr title="Ein regulärer Ausdruck, auch regex oder regexp genannt, ist eine Zeichensequenz, die ein Suchmuster für Strings definiert.">Regulären Ausdruck</abbr> `pattern` definieren, mit dem der Parameter übereinstimmen muss: + +=== "Python 3.10+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} + ``` + +Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert: + +* `^`: mit den nachfolgenden Zeichen startet, keine Zeichen davor hat. +* `fixedquery`: den exakten Text `fixedquery` hat. +* `$`: danach endet, keine weiteren Zeichen hat als `fixedquery`. + +Wenn Sie sich verloren fühlen bei all diesen **„Regulärer Ausdruck“**-Konzepten, keine Sorge. Reguläre Ausdrücke sind für viele Menschen ein schwieriges Thema. Sie können auch ohne reguläre Ausdrücke eine ganze Menge machen. + +Aber wenn Sie sie brauchen und sie lernen, wissen Sie, dass Sie sie bereits direkt in **FastAPI** verwenden können. + +### Pydantic v1 `regex` statt `pattern` + +Vor Pydantic Version 2 und vor FastAPI Version 0.100.0, war der Name des Parameters `regex` statt `pattern`, aber das ist jetzt <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr>. + +Sie könnten immer noch Code sehen, der den alten Namen verwendet: + +=== "Python 3.10+ Pydantic v1" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} + ``` + +Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓 + +## Defaultwerte + +Sie können natürlich andere Defaultwerte als `None` verwenden. + +Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} + ``` + +!!! note "Hinweis" + Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. + +## Erforderliche Parameter + +Wenn wir keine Validierungen oder Metadaten haben, können wir den `q` Query-Parameter erforderlich machen, indem wir einfach keinen Defaultwert deklarieren, wie in: + +```Python +q: str +``` + +statt: + +```Python +q: Union[str, None] = None +``` + +Aber jetzt deklarieren wir den Parameter mit `Query`, wie in: + +=== "Annotiert" + + ```Python + q: Annotated[Union[str, None], Query(min_length=3)] = None + ``` + +=== "Nicht annotiert" + + ```Python + q: Union[str, None] = Query(default=None, min_length=3) + ``` + +Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} + ``` + +=== "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/tutorial006.py!} + ``` + + !!! tip "Tipp" + Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. + + Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉 + +### Erforderlich mit Ellipse (`...`) + +Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das <abbr title='Zeichenfolge, die einen Wert direkt darstellt, etwa 1, "hallowelt", True, None'>Literal</abbr> `...` setzen: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} + ``` + +=== "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!} + ``` + +!!! info + Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Teil von Python und wird „Ellipsis“ genannt</a> (Deutsch: Ellipse). + + Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. + +Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist. + +### Erforderlich, kann `None` sein + +Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erforderlich ist. Das zwingt Clients, den Wert zu senden, selbst wenn er `None` ist. + +Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! 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 <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> erfahren. + +!!! tip "Tipp" + Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. + +## Query-Parameter-Liste / Mehrere Werte + +Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn auch eine Liste von Werten empfangen lassen, oder anders gesagt, mehrere Werte. + +Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Dann, mit einer URL wie: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +bekommen Sie alle `q`-*Query-Parameter*-Werte (`foo` und `bar`) in einer Python-Liste – `list` – in ihrer *Pfadoperation-Funktion*, im Funktionsparameter `q`, überreicht. + +Die Response für diese URL wäre also: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +!!! tip "Tipp" + Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. + +Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte. + +<img src="/img/tutorial/query-params-str-validations/image02.png"> + +### Query-Parameter-Liste / Mehrere Werte mit Defaults + +Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Wenn Sie auf: + +``` +http://localhost:8000/items/ +``` + +gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response erhalten Sie: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### `list` alleine verwenden + +Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} + ``` + +=== "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!} + ``` + +!!! note "Hinweis" + Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. + + Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht. + +## Deklarieren von mehr Metadaten + +Sie können mehr Informationen zum Parameter hinzufügen. + +Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet. + +!!! note "Hinweis" + Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. + + Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren. + +Sie können einen Titel hinzufügen – `title`: + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Und eine Beschreibung – `description`: + +=== "Python 3.10+" + + ```Python hl_lines="14" + {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15" + {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Alias-Parameter + +Stellen Sie sich vor, der Parameter soll `item-query` sein. + +Wie in: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Aber `item-query` ist kein gültiger Name für eine Variable in Python. + +Am ähnlichsten wäre `item_query`. + +Aber Sie möchten dennoch exakt `item-query` verwenden. + +Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Parameter als deprecated ausweisen + +Nehmen wir an, Sie mögen diesen Parameter nicht mehr. + +Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie möchten, dass die Dokumentation klar anzeigt, dass er <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr> ist. + +In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16" + {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} + ``` + +=== "Python 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!} + ``` + +Die Dokumentation wird das so anzeigen: + +<img src="/img/tutorial/query-params-str-validations/image01.png"> + +## Parameter von OpenAPI ausschließen + +Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`. + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Zusammenfassung + +Sie können zusätzliche Validierungen und Metadaten zu ihren Parametern hinzufügen. + +Allgemeine Validierungen und Metadaten: + +* `alias` +* `title` +* `description` +* `deprecated` + +Validierungen spezifisch für Strings: + +* `min_length` +* `max_length` +* `pattern` + +In diesen Beispielen haben Sie gesehen, wie Sie Validierungen für Strings hinzufügen. + +In den nächsten Kapiteln sehen wir, wie man Validierungen für andere Typen hinzufügt, etwa für Zahlen. From 80ae42e0b94634e4474d927a535a5d3fafa699f3 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 18:59:29 +0100 Subject: [PATCH 101/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/path-params-numeric-validatio?= =?UTF-8?q?ns.md`=20(#10307)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-params-numeric-validations.md | 293 ++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 docs/de/docs/tutorial/path-params-numeric-validations.md diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..aa3b59b8b --- /dev/null +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,293 @@ +# Pfad-Parameter und Validierung von Zahlen + +So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metadaten hinzufügen können, können Sie das mittels `Path` auch für Pfad-Parameter tun. + +## `Path` importieren + +Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. + +=== "Python 3.10+" + + ```Python hl_lines="1 3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="1 3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3-4" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` + +!!! info + FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + + Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + + Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +## Metadaten deklarieren + +Sie können die gleichen Parameter deklarieren wie für `Query`. + +Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie: + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` + +!!! note "Hinweis" + Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. + + Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen. + + Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich. + +## Sortieren Sie die Parameter, wie Sie möchten + +!!! tip "Tipp" + Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +Nehmen wir an, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren. + +Und Sie müssen sonst nichts anderes für den Parameter deklarieren, Sie brauchen also nicht wirklich `Query`. + +Aber Sie brauchen `Path` für den `item_id`-Pfad-Parameter. Und Sie möchten aus irgendeinem Grund nicht `Annotated` verwenden. + +Python wird sich beschweren, wenn Sie einen Parameter mit Defaultwert vor einen Parameter ohne Defaultwert setzen. + +Aber Sie können die Reihenfolge der Parameter ändern, den Query-Parameter ohne Defaultwert zuerst. + +Für **FastAPI** ist es nicht wichtig. Es erkennt die Parameter anhand ihres Namens, ihrer Typen, und ihrer Defaultwerte (`Query`, `Path`, usw.). Es kümmert sich nicht um die Reihenfolge. + +Sie können Ihre Funktion also so deklarieren: + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} + ``` + +Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden. + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} + ``` + +## Sortieren Sie die Parameter wie Sie möchten: Tricks + +!!! tip "Tipp" + Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen. + +Wenn Sie eines der folgenden Dinge tun möchten: + +* den `q`-Parameter ohne `Query` oder irgendeinem Defaultwert deklarieren +* den Pfad-Parameter `item_id` mittels `Path` deklarieren +* die Parameter in einer unterschiedlichen Reihenfolge haben +* `Annotated` nicht verwenden + +... dann hat Python eine kleine Spezial-Syntax für Sie. + +Übergeben Sie der Funktion `*` als ersten Parameter. + +Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Parameter als <abbr title="Keyword-Argument – Schlüsselwort-Argument: Das Argument wird anhand seines Namens erkannt, nicht anhand seiner Reihenfolge in der Argumentliste">Keyword-Argumente</abbr> (Schlüssel-Wert-Paare), auch bekannt als <abbr title="Von: K-ey W-ord Arg-uments"><code>kwargs</code></abbr>, verwendet werden. Selbst wenn diese keinen Defaultwert haben. + +```Python hl_lines="7" +{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +``` + +### Besser mit `Annotated` + +Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden. + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} + ``` + +## Validierung von Zahlen: Größer oder gleich + +Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren. + +Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual). +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} + ``` + +## Validierung von Zahlen: Größer und kleiner oder gleich + +Das Gleiche trifft zu auf: + +* `gt`: `g`reater `t`han – größer als +* `le`: `l`ess than or `e`qual – kleiner oder gleich + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} + ``` + +## Validierung von Zahlen: Floats, größer und kleiner + +Zahlenvalidierung funktioniert auch für <abbr title="Kommazahl">`float`</abbr>-Werte. + +Hier wird es wichtig, in der Lage zu sein, <abbr title="greater than – größer als"><code>gt</code></abbr> zu deklarieren, und nicht nur <abbr title="greater than or equal – größer oder gleich"><code>ge</code></abbr>, da Sie hiermit bestimmen können, dass ein Wert, zum Beispiel, größer als `0` sein muss, obwohl er kleiner als `1` ist. + +`0.5` wäre also ein gültiger Wert, aber nicht `0.0` oder `0`. + +Das gleiche gilt für <abbr title="less than – kleiner als"><code>lt</code></abbr>. + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} + ``` + +## Zusammenfassung + +Mit `Query` und `Path` (und anderen, die Sie noch nicht gesehen haben) können Sie Metadaten und Stringvalidierungen deklarieren, so wie in [Query-Parameter und Stringvalidierungen](query-params-str-validations.md){.internal-link target=_blank} beschrieben. + +Und Sie können auch Validierungen für Zahlen deklarieren: + +* `gt`: `g`reater `t`han – größer als +* `ge`: `g`reater than or `e`qual – größer oder gleich +* `lt`: `l`ess `t`han – kleiner als +* `le`: `l`ess than or `e`qual – kleiner oder gleich + +!!! info + `Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse. + + Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben. + +!!! note "Technische Details" + `Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. + + Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben. + + Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird. + + Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt. + + Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten. From 8751ee0323ea76566a5ff54d860d1239d1a74136 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:00:33 +0000 Subject: [PATCH 102/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 678d75603..2c5b86023 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/query-params-str-validations.md`. PR [#10304](https://github.com/tiangolo/fastapi/pull/10304) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-files.md`. PR [#10364](https://github.com/tiangolo/fastapi/pull/10364) by [@nilslindemann](https://github.com/nilslindemann). * :globe_with_meridians: Add Portuguese translation for `docs/pt/docs/advanced/templates.md`. PR [#11338](https://github.com/tiangolo/fastapi/pull/11338) by [@SamuelBFavarin](https://github.com/SamuelBFavarin). * 🌐 Add Bengali translations for `docs/bn/docs/learn/index.md`. PR [#11337](https://github.com/tiangolo/fastapi/pull/11337) by [@imtiaz101325](https://github.com/imtiaz101325). From bea72bfc479599a15540eeb7a2d750db28bd381a Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:00:50 +0100 Subject: [PATCH 103/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/header-params.md`=20(#10326)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/header-params.md | 227 +++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 docs/de/docs/tutorial/header-params.md diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md new file mode 100644 index 000000000..3c9807f47 --- /dev/null +++ b/docs/de/docs/tutorial/header-params.md @@ -0,0 +1,227 @@ +# Header-Parameter + +So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch <abbr title='Header – Kopfzeilen, Header, Header-Felder: Schlüssel-Wert-Metadaten, die vom Client beim Request, und vom Server bei der Response gesendet werden'>Header</abbr>-Parameter definieren. + +## `Header` importieren + +Importieren Sie zuerst `Header`: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` + +## `Header`-Parameter deklarieren + +Dann deklarieren Sie Ihre Header-Parameter, auf die gleiche Weise, wie Sie auch `Path`-, `Query`-, und `Cookie`-Parameter deklarieren. + +Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/header_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial001.py!} + ``` + +!!! note "Technische Details" + `Header` ist eine Schwesterklasse von `Path`, `Query` und `Cookie`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. + + Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Header` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. + +!!! info + Um Header zu deklarieren, müssen Sie `Header` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. + +## Automatische Konvertierung + +`Header` hat weitere Funktionalität, zusätzlich zu der, die `Path`, `Query` und `Cookie` bereitstellen. + +Die meisten Standard-Header benutzen als Trennzeichen einen Bindestrich, auch bekannt als das „Minus-Symbol“ (`-`). + +Aber eine Variable wie `user-agent` ist in Python nicht gültig. + +Darum wird `Header` standardmäßig in Parameternamen den Unterstrich (`_`) zu einem Bindestrich (`-`) konvertieren. + +HTTP-Header sind außerdem unabhängig von Groß-/Kleinschreibung, darum können Sie sie mittels der Standard-Python-Schreibweise deklarieren (auch bekannt als "snake_case"). + +Sie können also `user_agent` schreiben, wie Sie es normalerweise in Python-Code machen würden, statt etwa die ersten Buchstaben groß zu schreiben, wie in `User_Agent`. + +Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen zu Bindestrichen abschalten möchten, setzen Sie den Parameter `convert_underscores` auf `False`. + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/header_params/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/header_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial002.py!} + ``` + +!!! 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. + +## Doppelte Header + +Es ist möglich, doppelte Header zu empfangen. Also den gleichen Header mit unterschiedlichen Werten. + +Sie können solche Fälle deklarieren, indem Sie in der Typdeklaration eine Liste verwenden. + +Sie erhalten dann alle Werte von diesem doppelten Header als Python-`list`e. + +Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen kann, schreiben Sie: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/header_params/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/header_params/tutorial003_py310.py!} + ``` + +=== "Python 3.9+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003_py39.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/header_params/tutorial003.py!} + ``` + +Wenn Sie mit einer *Pfadoperation* kommunizieren, die zwei HTTP-Header sendet, wie: + +``` +X-Token: foo +X-Token: bar +``` + +Dann wäre die Response: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Zusammenfassung + +Deklarieren Sie Header mittels `Header`, auf die gleiche Weise wie bei `Query`, `Path` und `Cookie`. + +Machen Sie sich keine Sorgen um Unterstriche in ihren Variablen, **FastAPI** wird sich darum kümmern, diese zu konvertieren. From 2925f1693c8c383acd2e2562c2ca8b8626cc7bbb Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:01:10 +0100 Subject: [PATCH 104/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/dependencies/index.md`=20(#10?= =?UTF-8?q?399)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/dependencies/index.md | 352 ++++++++++++++++++++ 1 file changed, 352 insertions(+) create mode 100644 docs/de/docs/tutorial/dependencies/index.md diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..6254e976d --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/index.md @@ -0,0 +1,352 @@ +# Abhängigkeiten + +**FastAPI** hat ein sehr mächtiges, aber intuitives **<abbr title="Dependency Injection – Einbringen von Abhängigkeiten: Auch bekannt als Komponenten, Ressourcen, Provider, Services, Injectables">Dependency Injection</abbr>** System. + +Es ist so konzipiert, sehr einfach zu verwenden zu sein und es jedem Entwickler sehr leicht zu machen, andere Komponenten mit **FastAPI** zu integrieren. + +## Was ist „Dependency Injection“ + +**„Dependency Injection“** bedeutet in der Programmierung, dass es für Ihren Code (in diesem Fall Ihre *Pfadoperation-Funktionen*) eine Möglichkeit gibt, Dinge zu deklarieren, die er verwenden möchte und die er zum Funktionieren benötigt: „Abhängigkeiten“ – „Dependencies“. + +Das System (in diesem Fall **FastAPI**) kümmert sich dann darum, Ihren Code mit den erforderlichen Abhängigkeiten zu versorgen („die Abhängigkeiten einfügen“ – „inject the dependencies“). + +Das ist sehr nützlich, wenn Sie: + +* Eine gemeinsame Logik haben (die gleiche Code-Logik immer und immer wieder). +* Datenbankverbindungen teilen. +* Sicherheit, Authentifizierung, Rollenanforderungen, usw. durchsetzen. +* Und viele andere Dinge ... + +All dies, während Sie Codeverdoppelung minimieren. + +## Erste Schritte + +Sehen wir uns ein sehr einfaches Beispiel an. Es ist so einfach, dass es vorerst nicht sehr nützlich ist. + +Aber so können wir uns besser auf die Funktionsweise des **Dependency Injection** Systems konzentrieren. + +### Erstellen Sie eine Abhängigkeit (<abbr title="Das von dem abhängt, die zu verwendende Abhängigkeit">„Dependable“</abbr>) + +Konzentrieren wir uns zunächst auf die Abhängigkeit - die Dependency. + +Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennimmt wie eine *Pfadoperation-Funktion*: +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Das war's schon. + +**Zwei Zeilen**. + +Und sie hat die gleiche Form und Struktur wie alle Ihre *Pfadoperation-Funktionen*. + +Sie können sie sich als *Pfadoperation-Funktion* ohne den „Dekorator“ (ohne `@app.get("/some-path")`) vorstellen. + +Und sie kann alles zurückgeben, was Sie möchten. + +In diesem Fall erwartet diese Abhängigkeit: + +* Einen optionalen Query-Parameter `q`, der ein `str` ist. +* Einen optionalen Query-Parameter `skip`, der ein `int` ist und standardmäßig `0` ist. +* Einen optionalen Query-Parameter `limit`, der ein `int` ist und standardmäßig `100` ist. + +Und dann wird einfach ein `dict` zurückgegeben, welches diese Werte enthält. + +!!! info + FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + + Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + + Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +### `Depends` importieren + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +### Deklarieren der Abhängigkeit im <abbr title="Das Abhängige, der Verwender der Abhängigkeit">„Dependant“</abbr> + +So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: + +=== "Python 3.10+" + + ```Python hl_lines="13 18" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. + +Sie übergeben `Depends` nur einen einzigen Parameter. + +Dieser Parameter muss so etwas wie eine Funktion sein. + +Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), sondern übergeben sie einfach als Parameter an `Depends()`. + +Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*. + +!!! tip "Tipp" + Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. + +Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum: + +* Ihre Abhängigkeitsfunktion („Dependable“) mit den richtigen Parametern aufzurufen. +* Sich das Ergebnis von dieser Funktion zu holen. +* Dieses Ergebnis dem Parameter Ihrer *Pfadoperation-Funktion* zuzuweisen. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen. + +!!! check + Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich. + + Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird. + +## `Annotated`-Abhängigkeiten wiederverwenden + +In den Beispielen oben sehen Sie, dass es ein kleines bisschen **Codeverdoppelung** gibt. + +Wenn Sie die Abhängigkeit `common_parameters()` verwenden, müssen Sie den gesamten Parameter mit der Typannotation und `Depends()` schreiben: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="12 16 21" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14 18 23" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15 19 24" + {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} + ``` + +!!! tip "Tipp" + Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. + + Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎 + +Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`. + +Das ist besonders nützlich, wenn Sie es in einer **großen Codebasis** verwenden, in der Sie in **vielen *Pfadoperationen*** immer wieder **dieselben Abhängigkeiten** verwenden. + +## `async` oder nicht `async` + +Da Abhängigkeiten auch von **FastAPI** aufgerufen werden (so wie Ihre *Pfadoperation-Funktionen*), gelten beim Definieren Ihrer Funktionen die gleichen Regeln. + +Sie können `async def` oder einfach `def` verwenden. + +Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadoperation-Funktionen* oder `def`-Abhängigkeiten innerhalb von `async def`-*Pfadoperation-Funktionen*, usw. deklarieren. + +Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist. + +!!! note "Hinweis" + Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. + +## Integriert in OpenAPI + +Alle Requestdeklarationen, -validierungen und -anforderungen Ihrer Abhängigkeiten (und Unterabhängigkeiten) werden in dasselbe OpenAPI-Schema integriert. + +Die interaktive Dokumentation enthält also auch alle Informationen aus diesen Abhängigkeiten: + +<img src="/img/tutorial/dependencies/image01.png"> + +## Einfache Verwendung + +Näher betrachtet, werden *Pfadoperation-Funktionen* deklariert, um verwendet zu werden, wann immer ein *Pfad* und eine *Operation* übereinstimmen, und dann kümmert sich **FastAPI** darum, die Funktion mit den richtigen Parametern aufzurufen, die Daten aus der Anfrage extrahierend. + +Tatsächlich funktionieren alle (oder die meisten) Webframeworks auf die gleiche Weise. + +Sie rufen diese Funktionen niemals direkt auf. Sie werden von Ihrem Framework aufgerufen (in diesem Fall **FastAPI**). + +Mit dem Dependency Injection System können Sie **FastAPI** ebenfalls mitteilen, dass Ihre *Pfadoperation-Funktion* von etwas anderem „abhängt“, das vor Ihrer *Pfadoperation-Funktion* ausgeführt werden soll, und **FastAPI** kümmert sich darum, es auszuführen und die Ergebnisse zu „injizieren“. + +Andere gebräuchliche Begriffe für dieselbe Idee der „Abhängigkeitsinjektion“ sind: + +* Ressourcen +* Provider +* Services +* Injectables +* Komponenten + +## **FastAPI**-Plugins + +Integrationen und „Plugins“ können mit dem **Dependency Injection** System erstellt werden. Aber tatsächlich besteht **keine Notwendigkeit, „Plugins“ zu erstellen**, da es durch die Verwendung von Abhängigkeiten möglich ist, eine unendliche Anzahl von Integrationen und Interaktionen zu deklarieren, die dann für Ihre *Pfadoperation-Funktionen* verfügbar sind. + +Und Abhängigkeiten können auf sehr einfache und intuitive Weise erstellt werden, sodass Sie einfach die benötigten Python-Packages importieren und sie in wenigen Codezeilen, *im wahrsten Sinne des Wortes*, mit Ihren API-Funktionen integrieren. + +Beispiele hierfür finden Sie in den nächsten Kapiteln zu relationalen und NoSQL-Datenbanken, Sicherheit usw. + +## **FastAPI**-Kompatibilität + +Die Einfachheit des Dependency Injection Systems macht **FastAPI** kompatibel mit: + +* allen relationalen Datenbanken +* NoSQL-Datenbanken +* externen Packages +* externen APIs +* Authentifizierungs- und Autorisierungssystemen +* API-Nutzungs-Überwachungssystemen +* Responsedaten-Injektionssystemen +* usw. + +## Einfach und leistungsstark + +Obwohl das hierarchische Dependency Injection System sehr einfach zu definieren und zu verwenden ist, ist es dennoch sehr mächtig. + +Sie können Abhängigkeiten definieren, die selbst wiederum Abhängigkeiten definieren können. + +Am Ende wird ein hierarchischer Baum von Abhängigkeiten erstellt, und das **Dependency Injection** System kümmert sich darum, alle diese Abhängigkeiten (und deren Unterabhängigkeiten) für Sie aufzulösen und die Ergebnisse bei jedem Schritt einzubinden (zu injizieren). + +Nehmen wir zum Beispiel an, Sie haben vier API-Endpunkte (*Pfadoperationen*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +Dann könnten Sie für jeden davon unterschiedliche Berechtigungsanforderungen hinzufügen, nur mit Abhängigkeiten und Unterabhängigkeiten: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integriert mit **OpenAPI** + +Alle diese Abhängigkeiten, während sie ihre Anforderungen deklarieren, fügen auch Parameter, Validierungen, usw. zu Ihren *Pfadoperationen* hinzu. + +**FastAPI** kümmert sich darum, alles zum OpenAPI-Schema hinzuzufügen, damit es in den interaktiven Dokumentationssystemen angezeigt wird. From fe5ea68d5dcc4c6ab6b1e9f00a463a29bee156e2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:01:43 +0000 Subject: [PATCH 105/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2c5b86023..a3728b0c5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/path-params-numeric-validations.md`. PR [#10307](https://github.com/tiangolo/fastapi/pull/10307) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/query-params-str-validations.md`. PR [#10304](https://github.com/tiangolo/fastapi/pull/10304) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-files.md`. PR [#10364](https://github.com/tiangolo/fastapi/pull/10364) by [@nilslindemann](https://github.com/nilslindemann). * :globe_with_meridians: Add Portuguese translation for `docs/pt/docs/advanced/templates.md`. PR [#11338](https://github.com/tiangolo/fastapi/pull/11338) by [@SamuelBFavarin](https://github.com/SamuelBFavarin). From 32ba7dc04d3a120515f5c082b92d33691d546a3f Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:01:58 +0100 Subject: [PATCH 106/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/dependencies/classes-as-depen?= =?UTF-8?q?dencies.md`=20(#10407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/classes-as-dependencies.md | 481 ++++++++++++++++++ 1 file changed, 481 insertions(+) create mode 100644 docs/de/docs/tutorial/dependencies/classes-as-dependencies.md diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..9faaed715 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,481 @@ +# Klassen als Abhängigkeiten + +Bevor wir tiefer in das **Dependency Injection** System eintauchen, lassen Sie uns das vorherige Beispiel verbessern. + +## Ein `dict` aus dem vorherigen Beispiel + +Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Dependable“) zurückgegeben: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Aber dann haben wir ein `dict` im Parameter `commons` der *Pfadoperation-Funktion*. + +Und wir wissen, dass Editoren nicht viel Unterstützung (wie etwa Code-Vervollständigung) für `dict`s bieten können, weil sie ihre Schlüssel- und Werttypen nicht kennen. + +Das können wir besser machen ... + +## Was macht eine Abhängigkeit aus + +Bisher haben Sie Abhängigkeiten gesehen, die als Funktionen deklariert wurden. + +Das ist jedoch nicht die einzige Möglichkeit, Abhängigkeiten zu deklarieren (obwohl es wahrscheinlich die gebräuchlichste ist). + +Der springende Punkt ist, dass eine Abhängigkeit aufrufbar („callable“) sein sollte. + +Ein „**Callable**“ in Python ist etwas, das wie eine Funktion aufgerufen werden kann („to call“). + +Wenn Sie also ein Objekt `something` haben (das möglicherweise _keine_ Funktion ist) und Sie es wie folgt aufrufen (ausführen) können: + +```Python +something() +``` + +oder + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +dann ist das ein „Callable“ (ein „Aufrufbares“). + +## Klassen als Abhängigkeiten + +Möglicherweise stellen Sie fest, dass Sie zum Erstellen einer Instanz einer Python-Klasse die gleiche Syntax verwenden. + +Zum Beispiel: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +In diesem Fall ist `fluffy` eine Instanz der Klasse `Cat`. + +Und um `fluffy` zu erzeugen, rufen Sie `Cat` auf. + +Eine Python-Klasse ist also auch ein **Callable**. + +Darum können Sie in **FastAPI** auch eine Python-Klasse als Abhängigkeit verwenden. + +Was FastAPI tatsächlich prüft, ist, ob es sich um ein „Callable“ (Funktion, Klasse oder irgendetwas anderes) handelt und ob die Parameter definiert sind. + +Wenn Sie **FastAPI** ein „Callable“ als Abhängigkeit übergeben, analysiert es die Parameter dieses „Callables“ und verarbeitet sie auf die gleiche Weise wie die Parameter einer *Pfadoperation-Funktion*. Einschließlich Unterabhängigkeiten. + +Das gilt auch für Callables ohne Parameter. So wie es auch für *Pfadoperation-Funktionen* ohne Parameter gilt. + +Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von oben in die Klasse `CommonQueryParams` ändern: + +=== "Python 3.10+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9-13" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse verwendet wird: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +... sie hat die gleichen Parameter wie unsere vorherige `common_parameters`: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Diese Parameter werden von **FastAPI** verwendet, um die Abhängigkeit „aufzulösen“. + +In beiden Fällen wird sie haben: + +* Einen optionalen `q`-Query-Parameter, der ein `str` ist. +* Einen `skip`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `0`. +* Einen `limit`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `100`. + +In beiden Fällen werden die Daten konvertiert, validiert, im OpenAPI-Schema dokumentiert, usw. + +## Verwendung + +Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +**FastAPI** ruft die Klasse `CommonQueryParams` auf. Dadurch wird eine „Instanz“ dieser Klasse erstellt und die Instanz wird als Parameter `commons` an Ihre Funktion überreicht. + +## Typannotation vs. `Depends` + +Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +Das letzte `CommonQueryParams`, in: + +```Python +... Depends(CommonQueryParams) +``` + +... ist das, was **FastAPI** tatsächlich verwendet, um die Abhängigkeit zu ermitteln. + +Aus diesem extrahiert FastAPI die deklarierten Parameter, und dieses ist es, was FastAPI auch aufruft. + +--- + +In diesem Fall hat das erste `CommonQueryParams` in: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams ... + ``` + +... keine besondere Bedeutung für **FastAPI**. FastAPI verwendet es nicht für die Datenkonvertierung, -validierung, usw. (da es dafür `Depends(CommonQueryParams)` verwendet). + +Sie könnten tatsächlich einfach schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons = Depends(CommonQueryParams) + ``` + +... wie in: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003.py!} + ``` + +Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was als Parameter `commons` übergeben wird, und Ihnen dann bei der Codevervollständigung, Typprüfungen, usw. helfen kann: + +<img src="/img/tutorial/dependencies/image02.png"> + +## Abkürzung + +Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +**FastAPI** bietet eine Abkürzung für diese Fälle, wo die Abhängigkeit *speziell* eine Klasse ist, welche **FastAPI** aufruft, um eine Instanz der Klasse selbst zu erstellen. + +In diesem speziellen Fall können Sie Folgendes tun: + +Anstatt zu schreiben: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +... schreiben Sie: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + commons: CommonQueryParams = Depends() + ``` + +Sie deklarieren die Abhängigkeit als Typ des Parameters und verwenden `Depends()` ohne Parameter, anstatt die vollständige Klasse *erneut* in `Depends(CommonQueryParams)` schreiben zu müssen. + +Dasselbe Beispiel würde dann so aussehen: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004.py!} + ``` + +... und **FastAPI** wird wissen, was zu tun ist. + +!!! tip "Tipp" + Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht. + + Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren. From 272d27e8b5008908f55f923eda2b5931ee2e3cd9 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:02:19 +0100 Subject: [PATCH 107/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/cookie-params.md`=20(#10323)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/cookie-params.md | 97 ++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 docs/de/docs/tutorial/cookie-params.md diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..c95e28c7d --- /dev/null +++ b/docs/de/docs/tutorial/cookie-params.md @@ -0,0 +1,97 @@ +# Cookie-Parameter + +So wie `Query`- und `Path`-Parameter können Sie auch <abbr title='Cookie – „Keks“: Mechanismus, der kurze Daten in Textform im Browser des Benutzers speichert und abfragt'>Cookie</abbr>-Parameter definieren. + +## `Cookie` importieren + +Importieren Sie zuerst `Cookie`: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +## `Cookie`-Parameter deklarieren + +Dann deklarieren Sie Ihre Cookie-Parameter, auf die gleiche Weise, wie Sie auch `Path`- und `Query`-Parameter deklarieren. + +Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +!!! note "Technische Details" + `Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. + + Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. + +!!! info + Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. + +## Zusammenfassung + +Deklarieren Sie Cookies mittels `Cookie`, auf die gleiche Weise wie bei `Query` und `Path`. From c3dd94b96fece10d1d29c09fe6312f9aa0240c93 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:03:30 +0000 Subject: [PATCH 108/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a3728b0c5..759a3b9d2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/header-params.md`. PR [#10326](https://github.com/tiangolo/fastapi/pull/10326) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/path-params-numeric-validations.md`. PR [#10307](https://github.com/tiangolo/fastapi/pull/10307) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/query-params-str-validations.md`. PR [#10304](https://github.com/tiangolo/fastapi/pull/10304) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-files.md`. PR [#10364](https://github.com/tiangolo/fastapi/pull/10364) by [@nilslindemann](https://github.com/nilslindemann). From 5b3eda9300e30336c4b23c6536cb3c1c361e1e05 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:04:12 +0000 Subject: [PATCH 109/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 759a3b9d2..2a96c279e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/index.md`. PR [#10399](https://github.com/tiangolo/fastapi/pull/10399) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/header-params.md`. PR [#10326](https://github.com/tiangolo/fastapi/pull/10326) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/path-params-numeric-validations.md`. PR [#10307](https://github.com/tiangolo/fastapi/pull/10307) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/query-params-str-validations.md`. PR [#10304](https://github.com/tiangolo/fastapi/pull/10304) by [@nilslindemann](https://github.com/nilslindemann). From dacad696b14ab351c97c8d4f4e25356b0f160ff8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:05:35 +0000 Subject: [PATCH 110/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2a96c279e..940650431 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10407](https://github.com/tiangolo/fastapi/pull/10407) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/index.md`. PR [#10399](https://github.com/tiangolo/fastapi/pull/10399) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/header-params.md`. PR [#10326](https://github.com/tiangolo/fastapi/pull/10326) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/path-params-numeric-validations.md`. PR [#10307](https://github.com/tiangolo/fastapi/pull/10307) by [@nilslindemann](https://github.com/nilslindemann). From e610f0dd6ad9320bf775d33e16608815ddd2f3ea Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:06:16 +0100 Subject: [PATCH 111/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/async.md`=20(#10449)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/async.md | 430 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 430 insertions(+) create mode 100644 docs/de/docs/async.md diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md new file mode 100644 index 000000000..c2a43ac66 --- /dev/null +++ b/docs/de/docs/async.md @@ -0,0 +1,430 @@ +# Nebenläufigkeit und async / await + +Details zur `async def`-Syntax für *Pfadoperation-Funktionen* und Hintergrundinformationen zu asynchronem Code, Nebenläufigkeit und Parallelität. + +## In Eile? + +<abbr title="too long; didn't read – Zu lang; nicht gelesen"><strong>TL;DR:</strong></abbr> + +Wenn Sie Bibliotheken von Dritten verwenden, die mit `await` aufgerufen werden müssen, wie zum Beispiel: + +```Python +results = await some_library() +``` + +Dann deklarieren Sie Ihre *Pfadoperation-Funktionen* mit `async def` wie in: + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +!!! note + Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. + +--- + +Wenn Sie eine Bibliothek eines Dritten verwenden, die mit etwas kommuniziert (einer Datenbank, einer API, dem Dateisystem, usw.) und welche die Verwendung von `await` nicht unterstützt (dies ist derzeit bei den meisten Datenbankbibliotheken der Fall), dann deklarieren Sie Ihre *Pfadoperation-Funktionen* ganz normal nur mit `def`, etwa: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +Wenn Ihre Anwendung (irgendwie) mit nichts anderem kommunizieren und auf dessen Antwort warten muss, verwenden Sie `async def`. + +--- + +Wenn Sie sich unsicher sind, verwenden Sie einfach `def`. + +--- + +**Hinweis**: Sie können `def` und `async def` in Ihren *Pfadoperation-Funktionen* beliebig mischen, so wie Sie es benötigen, und jede einzelne Funktion in der für Sie besten Variante erstellen. FastAPI wird damit das Richtige tun. + +Wie dem auch sei, in jedem der oben genannten Fälle wird FastAPI immer noch asynchron arbeiten und extrem schnell sein. + +Wenn Sie jedoch den oben genannten Schritten folgen, können einige Performance-Optimierungen vorgenommen werden. + +## Technische Details + +Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async`** und **`await`**. + +Nehmen wir obigen Satz in den folgenden Abschnitten Schritt für Schritt unter die Lupe: + +* **Asynchroner Code** +* **`async` und `await`** +* **Coroutinen** + +## Asynchroner Code + +Asynchroner Code bedeutet lediglich, dass die Sprache 💬 eine Möglichkeit hat, dem Computersystem / Programm 🤖 mitzuteilen, dass es 🤖 an einem bestimmten Punkt im Code darauf warten muss, dass *etwas anderes* irgendwo anders fertig wird. Nehmen wir an, *etwas anderes* ist hier „Langsam-Datei“ 📝. + +Während der Zeit, die „Langsam-Datei“ 📝 benötigt, kann das System also andere Aufgaben erledigen. + +Dann kommt das System / Programm 🤖 bei jeder Gelegenheit zurück, wenn es entweder wieder wartet, oder wann immer es 🤖 die ganze Arbeit erledigt hat, die zu diesem Zeitpunkt zu tun war. Und es 🤖 wird nachschauen, ob eine der Aufgaben, auf die es gewartet hat, fertig damit ist, zu tun, was sie tun sollte. + +Dann nimmt es 🤖 die erste erledigte Aufgabe (sagen wir, unsere „Langsam-Datei“ 📝) und bearbeitet sie weiter. + +Das „Warten auf etwas anderes“ bezieht sich normalerweise auf <abbr title="Input and Output – Eingabe und Ausgabe">I/O</abbr>-Operationen, die relativ „langsam“ sind (im Vergleich zur Geschwindigkeit des Prozessors und des Arbeitsspeichers), wie etwa das Warten darauf, dass: + +* die Daten des Clients über das Netzwerk empfangen wurden +* die von Ihrem Programm gesendeten Daten vom Client über das Netzwerk empfangen wurden +* der Inhalt einer Datei vom System von der Festplatte gelesen und an Ihr Programm übergeben wurde +* der Inhalt, den Ihr Programm dem System übergeben hat, auf die Festplatte geschrieben wurde +* eine Remote-API-Operation beendet wurde +* Eine Datenbankoperation abgeschlossen wurde +* eine Datenbankabfrage die Ergebnisse zurückgegeben hat +* usw. + +Da die Ausführungszeit hier hauptsächlich durch das Warten auf <abbr title="Input and Output – Eingabe und Ausgabe">I/O</abbr>-Operationen verbraucht wird, nennt man dies auch „I/O-lastige“ („I/O bound“) Operationen. + +„Asynchron“, sagt man, weil das Computersystem / Programm nicht mit einer langsamen Aufgabe „synchronisiert“ werden muss und nicht auf den genauen Moment warten muss, in dem die Aufgabe beendet ist, ohne dabei etwas zu tun, um schließlich das Ergebnis der Aufgabe zu übernehmen und die Arbeit fortsetzen zu können. + +Da es sich stattdessen um ein „asynchrones“ System handelt, kann die Aufgabe nach Abschluss ein wenig (einige Mikrosekunden) in der Schlange warten, bis das System / Programm seine anderen Dinge erledigt hat und zurückkommt, um die Ergebnisse entgegenzunehmen und mit ihnen weiterzuarbeiten. + +Für „synchron“ (im Gegensatz zu „asynchron“) wird auch oft der Begriff „sequentiell“ verwendet, da das System / Programm alle Schritte in einer Sequenz („der Reihe nach“) ausführt, bevor es zu einer anderen Aufgabe wechselt, auch wenn diese Schritte mit Warten verbunden sind. + +### Nebenläufigkeit und Hamburger + +Diese oben beschriebene Idee von **asynchronem** Code wird manchmal auch **„Nebenläufigkeit“** genannt. Sie unterscheidet sich von **„Parallelität“**. + +**Nebenläufigkeit** und **Parallelität** beziehen sich beide auf „verschiedene Dinge, die mehr oder weniger gleichzeitig passieren“. + +Aber die Details zwischen *Nebenläufigkeit* und *Parallelität* sind ziemlich unterschiedlich. + +Um den Unterschied zu erkennen, stellen Sie sich die folgende Geschichte über Hamburger vor: + +### Nebenläufige Hamburger + +Sie gehen mit Ihrem Schwarm Fastfood holen, stehen in der Schlange, während der Kassierer die Bestellungen der Leute vor Ihnen entgegennimmt. 😍 + +<img src="/img/async/concurrent-burgers/concurrent-burgers-01.png" class="illustration"> + +Dann sind Sie an der Reihe und Sie bestellen zwei sehr schmackhafte Burger für Ihren Schwarm und Sie. 🍔🍔 + +<img src="/img/async/concurrent-burgers/concurrent-burgers-02.png" class="illustration"> + +Der Kassierer sagt etwas zum Koch in der Küche, damit dieser weiß, dass er Ihre Burger zubereiten muss (obwohl er gerade die für die vorherigen Kunden zubereitet). + +<img src="/img/async/concurrent-burgers/concurrent-burgers-03.png" class="illustration"> + +Sie bezahlen. 💸 + +Der Kassierer gibt Ihnen die Nummer Ihrer Bestellung. + +<img src="/img/async/concurrent-burgers/concurrent-burgers-04.png" class="illustration"> + +Während Sie warten, suchen Sie sich mit Ihrem Schwarm einen Tisch aus, Sie sitzen da und reden lange mit Ihrem Schwarm (da Ihre Burger sehr aufwändig sind und die Zubereitung einige Zeit dauert). + +Während Sie mit Ihrem Schwarm am Tisch sitzen und auf die Burger warten, können Sie die Zeit damit verbringen, zu bewundern, wie großartig, süß und klug Ihr Schwarm ist ✨😍✨. + +<img src="/img/async/concurrent-burgers/concurrent-burgers-05.png" class="illustration"> + +Während Sie warten und mit Ihrem Schwarm sprechen, überprüfen Sie von Zeit zu Zeit die auf dem Zähler angezeigte Nummer, um zu sehen, ob Sie bereits an der Reihe sind. + +Dann, irgendwann, sind Sie endlich an der Reihe. Sie gehen zur Theke, holen sich die Burger und kommen zurück an den Tisch. + +<img src="/img/async/concurrent-burgers/concurrent-burgers-06.png" class="illustration"> + +Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨ + +<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration"> + +!!! info + Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +--- + +Stellen Sie sich vor, Sie wären das Computersystem / Programm 🤖 in dieser Geschichte. + +Während Sie an der Schlange stehen, sind Sie einfach untätig 😴, warten darauf, dass Sie an die Reihe kommen, und tun nichts sehr „Produktives“. Aber die Schlange ist schnell abgearbeitet, weil der Kassierer nur die Bestellungen entgegennimmt (und nicht zubereitet), also ist das vertretbar. + +Wenn Sie dann an der Reihe sind, erledigen Sie tatsächliche „produktive“ Arbeit, Sie gehen das Menü durch, entscheiden sich, was Sie möchten, bekunden Ihre und die Wahl Ihres Schwarms, bezahlen, prüfen, ob Sie die richtige Menge Geld oder die richtige Karte geben, prüfen, ob die Rechnung korrekt ist, prüfen, dass die Bestellung die richtigen Artikel enthält, usw. + +Aber dann, auch wenn Sie Ihre Burger noch nicht haben, ist Ihre Interaktion mit dem Kassierer erst mal „auf Pause“ ⏸, weil Sie warten müssen 🕙, bis Ihre Burger fertig sind. + +Aber wenn Sie sich von der Theke entfernt haben und mit der Nummer für die Bestellung an einem Tisch sitzen, können Sie Ihre Aufmerksamkeit auf Ihren Schwarm lenken und an dieser Aufgabe „arbeiten“ ⏯ 🤓. Sie machen wieder etwas sehr „Produktives“ und flirten mit Ihrem Schwarm 😍. + +Dann sagt der Kassierer 💁 „Ich bin mit dem Burger fertig“, indem er Ihre Nummer auf dem Display über der Theke anzeigt, aber Sie springen nicht sofort wie verrückt auf, wenn das Display auf Ihre Nummer springt. Sie wissen, dass niemand Ihnen Ihre Burger wegnimmt, denn Sie haben die Nummer Ihrer Bestellung, und andere Leute haben andere Nummern. + +Also warten Sie darauf, dass Ihr Schwarm ihre Geschichte zu Ende erzählt (die aktuelle Arbeit ⏯ / bearbeitete Aufgabe beendet 🤓), lächeln sanft und sagen, dass Sie die Burger holen ⏸. + +Dann gehen Sie zur Theke 🔀, zur ursprünglichen Aufgabe, die nun erledigt ist ⏯, nehmen die Burger auf, sagen Danke, und bringen sie zum Tisch. Damit ist dieser Schritt / diese Aufgabe der Interaktion mit der Theke abgeschlossen ⏹. Das wiederum schafft eine neue Aufgabe, „Burger essen“ 🔀 ⏯, aber die vorherige Aufgabe „Burger holen“ ist erledigt ⏹. + +### Parallele Hamburger + +Stellen wir uns jetzt vor, dass es sich hierbei nicht um „nebenläufige Hamburger“, sondern um „parallele Hamburger“ handelt. + +Sie gehen los mit Ihrem Schwarm, um paralleles Fast Food zu bekommen. + +Sie stehen in der Schlange, während mehrere (sagen wir acht) Kassierer, die gleichzeitig Köche sind, die Bestellungen der Leute vor Ihnen entgegennehmen. + +Alle vor Ihnen warten darauf, dass ihre Burger fertig sind, bevor sie die Theke verlassen, denn jeder der 8 Kassierer geht los und bereitet den Burger sofort zu, bevor er die nächste Bestellung entgegennimmt. + +<img src="/img/async/parallel-burgers/parallel-burgers-01.png" class="illustration"> + +Dann sind Sie endlich an der Reihe und bestellen zwei sehr leckere Burger für Ihren Schwarm und Sie. + +Sie zahlen 💸. + +<img src="/img/async/parallel-burgers/parallel-burgers-02.png" class="illustration"> + +Der Kassierer geht in die Küche. + +Sie warten, vor der Theke stehend 🕙, damit niemand außer Ihnen Ihre Burger entgegennimmt, da es keine Nummern für die Reihenfolge gibt. + +<img src="/img/async/parallel-burgers/parallel-burgers-03.png" class="illustration"> + +Da Sie und Ihr Schwarm damit beschäftigt sind, niemanden vor sich zu lassen, der Ihre Burger nimmt, wenn sie ankommen, können Sie Ihrem Schwarm keine Aufmerksamkeit schenken. 😞 + +Das ist „synchrone“ Arbeit, Sie sind mit dem Kassierer/Koch „synchronisiert“ 👨🍳. Sie müssen warten 🕙 und genau in dem Moment da sein, in dem der Kassierer/Koch 👨🍳 die Burger zubereitet hat und Ihnen gibt, sonst könnte jemand anderes sie nehmen. + +<img src="/img/async/parallel-burgers/parallel-burgers-04.png" class="illustration"> + +Dann kommt Ihr Kassierer/Koch 👨🍳 endlich mit Ihren Burgern zurück, nachdem Sie lange vor der Theke gewartet 🕙 haben. + +<img src="/img/async/parallel-burgers/parallel-burgers-05.png" class="illustration"> + +Sie nehmen Ihre Burger und gehen mit Ihrem Schwarm an den Tisch. + +Sie essen sie und sind fertig. ⏹ + +<img src="/img/async/parallel-burgers/parallel-burgers-06.png" class="illustration"> + +Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞 + +!!! info + Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +--- + +In diesem Szenario der parallelen Hamburger sind Sie ein Computersystem / Programm 🤖 mit zwei Prozessoren (Sie und Ihr Schwarm), die beide warten 🕙 und ihre Aufmerksamkeit darauf verwenden, „lange Zeit vor der Theke zu warten“ 🕙. + +Der Fast-Food-Laden verfügt über 8 Prozessoren (Kassierer/Köche). Während der nebenläufige Burger-Laden nur zwei hatte (einen Kassierer und einen Koch). + +Dennoch ist das schlussendliche Benutzererlebnis nicht das Beste. 😞 + +--- + +Dies wäre die parallele äquivalente Geschichte für Hamburger. 🍔 + +Für ein „realeres“ Beispiel hierfür, stellen Sie sich eine Bank vor. + +Bis vor kurzem hatten die meisten Banken mehrere Kassierer 👨💼👨💼👨💼👨💼 und eine große Warteschlange 🕙🕙🕙🕙🕙🕙🕙🕙. + +Alle Kassierer erledigen die ganze Arbeit mit einem Kunden nach dem anderen 👨💼⏯. + +Und man muss lange in der Schlange warten 🕙 sonst kommt man nicht an die Reihe. + +Sie würden Ihren Schwarm 😍 wahrscheinlich nicht mitnehmen wollen, um Besorgungen bei der Bank zu erledigen 🏦. + +### Hamburger Schlussfolgerung + +In diesem Szenario „Fast Food Burger mit Ihrem Schwarm“ ist es viel sinnvoller, ein nebenläufiges System zu haben ⏸🔀⏯, da viel gewartet wird 🕙. + +Das ist auch bei den meisten Webanwendungen der Fall. + +Viele, viele Benutzer, aber Ihr Server wartet 🕙 darauf, dass deren nicht so gute Internetverbindungen die Requests übermitteln. + +Und dann warten 🕙, bis die Responses zurückkommen. + +Dieses „Warten“ 🕙 wird in Mikrosekunden gemessen, aber zusammenfassend lässt sich sagen, dass am Ende eine Menge gewartet wird. + +Deshalb ist es sehr sinnvoll, asynchronen ⏸🔀⏯ Code für Web-APIs zu verwenden. + +Diese Art der Asynchronität hat NodeJS populär gemacht (auch wenn NodeJS nicht parallel ist) und darin liegt die Stärke von Go als Programmiersprache. + +Und das ist das gleiche Leistungsniveau, das Sie mit **FastAPI** erhalten. + +Und da Sie Parallelität und Asynchronität gleichzeitig haben können, erzielen Sie eine höhere Performanz als die meisten getesteten NodeJS-Frameworks und sind mit Go auf Augenhöhe, einer kompilierten Sprache, die näher an C liegt <a href="https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1" class="external-link" target="_blank">(alles dank Starlette)</a>. + +### Ist Nebenläufigkeit besser als Parallelität? + +Nein! Das ist nicht die Moral der Geschichte. + +Nebenläufigkeit unterscheidet sich von Parallelität. Und sie ist besser bei **bestimmten** Szenarien, die viel Warten erfordern. Aus diesem Grund ist sie im Allgemeinen viel besser als Parallelität für die Entwicklung von Webanwendungen. Aber das stimmt nicht für alle Anwendungen. + +Um die Dinge auszugleichen, stellen Sie sich die folgende Kurzgeschichte vor: + +> Sie müssen ein großes, schmutziges Haus aufräumen. + +*Yup, das ist die ganze Geschichte*. + +--- + +Es gibt kein Warten 🕙, nur viel Arbeit an mehreren Stellen im Haus. + +Sie könnten wie im Hamburger-Beispiel hin- und herspringen, zuerst das Wohnzimmer, dann die Küche, aber da Sie auf nichts warten 🕙, sondern nur putzen und putzen, hätte das Hin- und Herspringen keine Auswirkungen. + +Es würde mit oder ohne Hin- und Herspringen (Nebenläufigkeit) die gleiche Zeit in Anspruch nehmen, um fertig zu werden, und Sie hätten die gleiche Menge an Arbeit erledigt. + +Aber wenn Sie in diesem Fall die acht Ex-Kassierer/Köche/jetzt Reinigungskräfte mitbringen würden und jeder von ihnen (plus Sie) würde einen Bereich des Hauses reinigen, könnten Sie die ganze Arbeit **parallel** erledigen, und würden mit dieser zusätzlichen Hilfe viel schneller fertig werden. + +In diesem Szenario wäre jede einzelne Reinigungskraft (einschließlich Ihnen) ein Prozessor, der seinen Teil der Arbeit erledigt. + +Und da die meiste Ausführungszeit durch tatsächliche Arbeit (anstatt durch Warten) in Anspruch genommen wird und die Arbeit in einem Computer von einer <abbr title="Central Processing Unit – Zentrale Recheneinheit">CPU</abbr> erledigt wird, werden diese Probleme als „CPU-lastig“ („CPU bound“) bezeichnet. + +--- + +Typische Beispiele für CPU-lastige Vorgänge sind Dinge, die komplexe mathematische Berechnungen erfordern. + +Zum Beispiel: + +* **Audio-** oder **Bildbearbeitung**. +* **Computer Vision**: Ein Bild besteht aus Millionen von Pixeln, jedes Pixel hat 3 Werte / Farben, die Verarbeitung erfordert normalerweise, Berechnungen mit diesen Pixeln durchzuführen, alles zur gleichen Zeit. +* **Maschinelles Lernen**: Normalerweise sind viele „Matrix“- und „Vektor“-Multiplikationen erforderlich. Stellen Sie sich eine riesige Tabelle mit Zahlen vor, in der Sie alle Zahlen gleichzeitig multiplizieren. +* **Deep Learning**: Dies ist ein Teilgebiet des maschinellen Lernens, daher gilt das Gleiche. Es ist nur so, dass es nicht eine einzige Tabelle mit Zahlen zum Multiplizieren gibt, sondern eine riesige Menge davon, und in vielen Fällen verwendet man einen speziellen Prozessor, um diese Modelle zu erstellen und / oder zu verwenden. + +### Nebenläufigkeit + Parallelität: Web + maschinelles Lernen + +Mit **FastAPI** können Sie die Vorteile der Nebenläufigkeit nutzen, die in der Webentwicklung weit verbreitet ist (derselbe Hauptvorteil von NodeJS). + +Sie können aber auch die Vorteile von Parallelität und Multiprocessing (Mehrere Prozesse werden parallel ausgeführt) für **CPU-lastige** Workloads wie in Systemen für maschinelles Lernen nutzen. + +Dies und die einfache Tatsache, dass Python die Hauptsprache für **Data Science**, maschinelles Lernen und insbesondere Deep Learning ist, machen FastAPI zu einem sehr passenden Werkzeug für Web-APIs und Anwendungen für Data Science / maschinelles Lernen (neben vielen anderen). + +Wie Sie diese Parallelität in der Produktion erreichen, erfahren Sie im Abschnitt über [Deployment](deployment/index.md){.internal-link target=_blank}. + +## `async` und `await`. + +Moderne Versionen von Python verfügen über eine sehr intuitive Möglichkeit, asynchronen Code zu schreiben. Dadurch sieht es wie normaler „sequentieller“ Code aus und übernimmt im richtigen Moment das „Warten“ für Sie. + +Wenn es einen Vorgang gibt, der erfordert, dass gewartet wird, bevor die Ergebnisse zurückgegeben werden, und der diese neue Python-Funktionalität unterstützt, können Sie ihn wie folgt schreiben: + +```Python +burgers = await get_burgers(2) +``` + +Der Schlüssel hier ist das `await`. Es teilt Python mit, dass es warten ⏸ muss, bis `get_burgers(2)` seine Aufgabe erledigt hat 🕙, bevor die Ergebnisse in `burgers` gespeichert werden. Damit weiß Python, dass es in der Zwischenzeit etwas anderes tun kann 🔀 ⏯ (z. B. einen weiteren Request empfangen). + +Damit `await` funktioniert, muss es sich in einer Funktion befinden, die diese Asynchronität unterstützt. Dazu deklarieren Sie sie einfach mit `async def`: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Mach Sie hier etwas Asynchrones, um die Burger zu erstellen + return burgers +``` + +... statt mit `def`: + +```Python hl_lines="2" +# Die ist nicht asynchron +def get_sequential_burgers(number: int): + # Mach Sie hier etwas Sequentielles, um die Burger zu erstellen + return burgers +``` + +Mit `async def` weiß Python, dass es innerhalb dieser Funktion auf `await`-Ausdrücke achten muss und dass es die Ausführung dieser Funktion „anhalten“ ⏸ und etwas anderes tun kann 🔀, bevor es zurückkommt. + +Wenn Sie eine `async def`-Funktion aufrufen möchten, müssen Sie sie „erwarten“ („await“). Das folgende wird also nicht funktionieren: + +```Python +# Das funktioniert nicht, weil get_burgers definiert wurde mit: async def +burgers = get_burgers(2) +``` + +--- + +Wenn Sie also eine Bibliothek verwenden, die Ihnen sagt, dass Sie sie mit `await` aufrufen können, müssen Sie die *Pfadoperation-Funktionen*, die diese Bibliothek verwenden, mittels `async def` erstellen, wie in: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### Weitere technische Details + +Ihnen ist wahrscheinlich aufgefallen, dass `await` nur innerhalb von Funktionen verwendet werden kann, die mit `async def` definiert sind. + +Gleichzeitig müssen aber mit `async def` definierte Funktionen „erwartet“ („awaited“) werden. Daher können Funktionen mit `async def` nur innerhalb von Funktionen aufgerufen werden, die auch mit `async def` definiert sind. + +Daraus resultiert das Ei-und-Huhn-Problem: Wie ruft man die erste `async` Funktion auf? + +Wenn Sie mit **FastAPI** arbeiten, müssen Sie sich darüber keine Sorgen machen, da diese „erste“ Funktion Ihre *Pfadoperation-Funktion* sein wird und FastAPI weiß, was zu tun ist. + +Wenn Sie jedoch `async` / `await` ohne FastAPI verwenden möchten, können Sie dies auch tun. + +### Schreiben Sie Ihren eigenen asynchronen Code + +Starlette (und **FastAPI**) basiert auf <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a>, was bedeutet, es ist sowohl kompatibel mit der Python-Standardbibliothek <a href="https://docs.python.org/3/library/asyncio-task.html" class="external-link" target="_blank">asyncio</a>, als auch mit <a href="https://trio.readthedocs.io/en/stable/" class="external-link" target="_blank">Trio</a>. + +Insbesondere können Sie <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> direkt verwenden für Ihre fortgeschritten nebenläufigen und parallelen Anwendungsfälle, die fortgeschrittenere Muster in Ihrem eigenen Code erfordern. + +Und selbst wenn Sie FastAPI nicht verwenden würden, könnten Sie auch Ihre eigenen asynchronen Anwendungen mit <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> so schreiben, dass sie hoch kompatibel sind und Sie dessen Vorteile nutzen können (z. B. *strukturierte Nebenläufigkeit*). + +### Andere Formen von asynchronem Code + +Diese Art der Verwendung von `async` und `await` ist in der Sprache relativ neu. + +Aber sie erleichtert die Arbeit mit asynchronem Code erheblich. + +Die gleiche Syntax (oder fast identisch) wurde kürzlich auch in moderne Versionen von JavaScript (im Browser und in NodeJS) aufgenommen. + +Davor war der Umgang mit asynchronem Code jedoch deutlich komplexer und schwieriger. + +In früheren Versionen von Python hätten Sie Threads oder <a href="https://www.gevent.org/" class="external-link" target="_blank">Gevent</a> verwenden können. Der Code ist jedoch viel komplexer zu verstehen, zu debuggen und nachzuvollziehen. + +In früheren Versionen von NodeJS / Browser JavaScript hätten Sie „Callbacks“ verwendet. Was zur <a href="http://callbackhell.com/" class="external-link" target="_blank">Callback-Hölle</a> führt. + +## Coroutinen + +**Coroutine** ist nur ein schicker Begriff für dasjenige, was von einer `async def`-Funktion zurückgegeben wird. Python weiß, dass es so etwas wie eine Funktion ist, die es starten kann und die irgendwann endet, aber auch dass sie pausiert ⏸ werden kann, wann immer darin ein `await` steht. + +Aber all diese Funktionalität der Verwendung von asynchronem Code mit `async` und `await` wird oft als Verwendung von „Coroutinen“ zusammengefasst. Es ist vergleichbar mit dem Hauptmerkmal von Go, den „Goroutinen“. + +## Fazit + +Sehen wir uns den gleichen Satz von oben noch mal an: + +> Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async`** und **`await`**. + +Das sollte jetzt mehr Sinn ergeben. ✨ + +All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindruckende Performanz haben lässt. + +## Sehr technische Details + +!!! warning "Achtung" + Das folgende können Sie wahrscheinlich überspringen. + + Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. + + Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. + +### Pfadoperation-Funktionen + +Wenn Sie eine *Pfadoperation-Funktion* mit normalem `def` anstelle von `async def` deklarieren, wird sie in einem externen Threadpool ausgeführt, der dann `await`et wird, anstatt direkt aufgerufen zu werden (da dies den Server blockieren würde). + +Wenn Sie von einem anderen asynchronen Framework kommen, das nicht auf die oben beschriebene Weise funktioniert, und Sie es gewohnt sind, triviale, nur-berechnende *Pfadoperation-Funktionen* mit einfachem `def` zu definieren, um einen geringfügigen Geschwindigkeitsgewinn (etwa 100 Nanosekunden) zu erzielen, beachten Sie bitte, dass der Effekt in **FastAPI** genau gegenteilig wäre. In solchen Fällen ist es besser, `async def` zu verwenden, es sei denn, Ihre *Pfadoperation-Funktionen* verwenden Code, der blockierende <abbr title="Input/Output – Eingabe/Ausgabe: Lesen oder Schreiben von/auf Festplatte, Netzwerkkommunikation.">I/O</abbr>-Operationen durchführt. + +Dennoch besteht in beiden Fällen eine gute Chance, dass **FastAPI** [immer noch schneller](index.md#performanz){.internal-link target=_blank} als Ihr bisheriges Framework (oder zumindest damit vergleichbar) ist. + +### Abhängigkeiten + +Das Gleiche gilt für [Abhängigkeiten](tutorial/dependencies/index.md){.internal-link target=_blank}. Wenn eine Abhängigkeit eine normale `def`-Funktion ist, anstelle einer `async def`-Funktion, dann wird sie im externen Threadpool ausgeführt. + +### Unterabhängigkeiten + +Sie können mehrere Abhängigkeiten und [Unterabhängigkeiten](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} haben, die einander bedingen (als Parameter der Funktionsdefinitionen), einige davon könnten erstellt werden mit `async def` und einige mit normalem `def`. Es würde immer noch funktionieren und diejenigen, die mit normalem `def` erstellt wurden, würden in einem externen Thread (vom Threadpool stammend) aufgerufen werden, anstatt `await`et zu werden. + +### Andere Hilfsfunktionen + +Jede andere Hilfsfunktion, die Sie direkt aufrufen, kann mit normalem `def` oder `async def` erstellt werden, und FastAPI beeinflusst nicht die Art und Weise, wie Sie sie aufrufen. + +Dies steht im Gegensatz zu den Funktionen, die FastAPI für Sie aufruft: *Pfadoperation-Funktionen* und Abhängigkeiten. + +Wenn Ihre Hilfsfunktion eine normale Funktion mit `def` ist, wird sie direkt aufgerufen (so wie Sie es in Ihrem Code schreiben), nicht in einem Threadpool. Wenn die Funktion mit `async def` erstellt wurde, sollten Sie sie `await`en, wenn Sie sie in Ihrem Code aufrufen. + +--- + +Nochmal, es handelt sich hier um sehr technische Details, die Ihnen helfen, falls Sie danach gesucht haben. + +Andernfalls liegen Sie richtig, wenn Sie sich an die Richtlinien aus dem obigen Abschnitt halten: <a href="#in-eile">In Eile?</a>. From f1a97505211ecf455b9263e6245c305577ecde95 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:06:23 +0000 Subject: [PATCH 112/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 940650431..63953a0c8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/cookie-params.md`. PR [#10323](https://github.com/tiangolo/fastapi/pull/10323) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10407](https://github.com/tiangolo/fastapi/pull/10407) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/index.md`. PR [#10399](https://github.com/tiangolo/fastapi/pull/10399) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/header-params.md`. PR [#10326](https://github.com/tiangolo/fastapi/pull/10326) by [@nilslindemann](https://github.com/nilslindemann). From 13f6d97c77330fb0d1e63812a2523d067980db14 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:06:38 +0100 Subject: [PATCH 113/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/versions.md`=20(#10491)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/versions.md | 86 +++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 docs/de/docs/deployment/versions.md diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md new file mode 100644 index 000000000..d71aded22 --- /dev/null +++ b/docs/de/docs/deployment/versions.md @@ -0,0 +1,86 @@ +# Über FastAPI-Versionen + +**FastAPI** wird bereits in vielen Anwendungen und Systemen produktiv eingesetzt. Und die Testabdeckung wird bei 100 % gehalten. Aber seine Entwicklung geht immer noch schnell voran. + +Es werden regelmäßig neue Funktionen hinzugefügt, Fehler werden regelmäßig behoben und der Code wird weiterhin kontinuierlich verbessert. + +Aus diesem Grund sind die aktuellen Versionen immer noch `0.x.x`, was darauf hindeutet, dass jede Version möglicherweise nicht abwärtskompatible Änderungen haben könnte. Dies folgt den Konventionen der <a href="https://semver.org/" class="external-link" target="_blank">semantischen Versionierung</a>. + +Sie können jetzt Produktionsanwendungen mit **FastAPI** erstellen (und das tun Sie wahrscheinlich schon seit einiger Zeit), Sie müssen nur sicherstellen, dass Sie eine Version verwenden, die korrekt mit dem Rest Ihres Codes funktioniert. + +## `fastapi`-Version pinnen + +Als Erstes sollten Sie die Version von **FastAPI**, die Sie verwenden, an die höchste Version „pinnen“, von der Sie wissen, dass sie für Ihre Anwendung korrekt funktioniert. + +Angenommen, Sie verwenden in Ihrer Anwendung die Version `0.45.0`. + +Wenn Sie eine `requirements.txt`-Datei verwenden, können Sie die Version wie folgt angeben: + +```txt +fastapi==0.45.0 +``` + +Das würde bedeuten, dass Sie genau die Version `0.45.0` verwenden. + +Oder Sie können sie auch anpinnen mit: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Das würde bedeuten, dass Sie eine Version `0.45.0` oder höher verwenden würden, aber kleiner als `0.46.0`, beispielsweise würde eine Version `0.45.2` immer noch akzeptiert. + +Wenn Sie zum Verwalten Ihrer Installationen andere Tools wie Poetry, Pipenv oder andere verwenden, sie verfügen alle über eine Möglichkeit, bestimmte Versionen für Ihre Packages zu definieren. + +## Verfügbare Versionen + +Die verfügbaren Versionen können Sie in den [Release Notes](../release-notes.md){.internal-link target=_blank} einsehen (z. B. um zu überprüfen, welches die neueste Version ist). + +## Über Versionen + +Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unter `1.0.0` potenziell nicht abwärtskompatible Änderungen hinzufügen. + +FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. + +!!! tip "Tipp" + Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. + +Sie sollten also in der Lage sein, eine Version wie folgt anzupinnen: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. + +!!! tip "Tipp" + „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. + +## Upgrade der FastAPI-Versionen + +Sie sollten Tests für Ihre Anwendung hinzufügen. + +Mit **FastAPI** ist das sehr einfach (dank Starlette), schauen Sie sich die Dokumentation an: [Testen](../tutorial/testing.md){.internal-link target=_blank} + +Nachdem Sie Tests erstellt haben, können Sie die **FastAPI**-Version auf eine neuere Version aktualisieren und sicherstellen, dass Ihr gesamter Code ordnungsgemäß funktioniert, indem Sie Ihre Tests ausführen. + +Wenn alles funktioniert oder nachdem Sie die erforderlichen Änderungen vorgenommen haben und alle Ihre Tests bestehen, können Sie Ihr `fastapi` an die neue aktuelle Version pinnen. + +## Über Starlette + +Sie sollten die Version von `starlette` nicht pinnen. + +Verschiedene Versionen von **FastAPI** verwenden eine bestimmte neuere Version von Starlette. + +Sie können **FastAPI** also einfach die korrekte Starlette-Version verwenden lassen. + +## Über Pydantic + +Pydantic integriert die Tests für **FastAPI** in seine eigenen Tests, sodass neue Versionen von Pydantic (über `1.0.0`) immer mit FastAPI kompatibel sind. + +Sie können Pydantic an jede für Sie geeignete Version über `1.0.0` und unter `2.0.0` anpinnen. + +Zum Beispiel: +```txt +pydantic>=1.2.0,<2.0.0 +``` From 474d6bc07b6cb5403417fd10532692fb0c7d507c Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:06:54 +0100 Subject: [PATCH 114/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/request-forms.md`=20(#10361)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/request-forms.md | 92 ++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 docs/de/docs/tutorial/request-forms.md diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md new file mode 100644 index 000000000..6c029b5fe --- /dev/null +++ b/docs/de/docs/tutorial/request-forms.md @@ -0,0 +1,92 @@ +# Formulardaten + +Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden. + +!!! info + Um Formulare zu verwenden, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + + Z. B. `pip install python-multipart`. + +## `Form` importieren + +Importieren Sie `Form` von `fastapi`: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +## `Form`-Parameter definieren + +Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt <abbr title='„Passwort-Fluss“'>„password flow“</abbr>), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. + +Die <abbr title="Specification – Spezifikation">Spec</abbr> erfordert, dass die Felder exakt `username` und `password` genannt werden und als Formularfelder, nicht JSON, gesendet werden. + +Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw. + +!!! info + `Form` ist eine Klasse, die direkt von `Body` erbt. + +!!! 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. + +## Über „Formularfelder“ + +HTML-Formulare (`<form></form>`) senden die Daten in einer „speziellen“ Kodierung zum Server, welche sich von JSON unterscheidet. + +**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. + +!!! note "Technische Details" + Daten aus Formularen werden normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert. + + Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien. + + Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>. + +!!! warning "Achtung" + Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. + + Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +## Zusammenfassung + +Verwenden Sie `Form`, um Eingabe-Parameter für Formulardaten zu deklarieren. From 537b7addafc14cf4e528c44c30600c5ed4a19c12 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:07:08 +0100 Subject: [PATCH 115/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/security/first-steps.md`=20(#?= =?UTF-8?q?10432)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/security/first-steps.md | 233 ++++++++++++++++++ 1 file changed, 233 insertions(+) create mode 100644 docs/de/docs/tutorial/security/first-steps.md diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md new file mode 100644 index 000000000..1e75fa8d9 --- /dev/null +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -0,0 +1,233 @@ +# Sicherheit – Erste Schritte + +Stellen wir uns vor, dass Sie Ihre **Backend**-API auf einer Domain haben. + +Und Sie haben ein **Frontend** auf einer anderen Domain oder in einem anderen Pfad derselben Domain (oder in einer mobilen Anwendung). + +Und Sie möchten eine Möglichkeit haben, dass sich das Frontend mithilfe eines **Benutzernamens** und eines **Passworts** beim Backend authentisieren kann. + +Wir können **OAuth2** verwenden, um das mit **FastAPI** zu erstellen. + +Aber ersparen wir Ihnen die Zeit, die gesamte lange Spezifikation zu lesen, nur um die kleinen Informationen zu finden, die Sie benötigen. + +Lassen Sie uns die von **FastAPI** bereitgestellten Tools verwenden, um Sicherheit zu gewährleisten. + +## Wie es aussieht + +Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktioniert, und dann kommen wir zurück, um zu verstehen, was passiert. + +## `main.py` erstellen + +Kopieren Sie das Beispiel in eine Datei `main.py`: + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +## Ausführen + +!!! info + Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + + Z. B. `pip install python-multipart`. + + Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet. + +Führen Sie das Beispiel aus mit: + +<div class="termy"> + +```console +$ uvicorn main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +## Überprüfen + +Gehen Sie zu der interaktiven Dokumentation unter: <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Sie werden etwa Folgendes sehen: + +<img src="/img/tutorial/security/image01.png"> + +!!! check "Authorize-Button!" + Sie haben bereits einen glänzenden, neuen „Authorize“-Button. + + Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können. + +Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder): + +<img src="/img/tutorial/security/image02.png"> + +!!! note "Hinweis" + Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. + +Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren. + +Es kann vom Frontend-Team verwendet werden (das auch Sie selbst sein können). + +Es kann von Anwendungen und Systemen Dritter verwendet werden. + +Und es kann auch von Ihnen selbst verwendet werden, um dieselbe Anwendung zu debuggen, zu prüfen und zu testen. + +## Der `password`-Flow + +Lassen Sie uns nun etwas zurückgehen und verstehen, was das alles ist. + +Der `password`-„Flow“ ist eine der in OAuth2 definierten Wege („Flows“) zur Handhabung von Sicherheit und Authentifizierung. + +OAuth2 wurde so konzipiert, dass das Backend oder die API unabhängig vom Server sein kann, der den Benutzer authentifiziert. + +In diesem Fall handhabt jedoch dieselbe **FastAPI**-Anwendung sowohl die API als auch die Authentifizierung. + +Betrachten wir es also aus dieser vereinfachten Sicht: + +* Der Benutzer gibt den `username` und das `password` im Frontend ein und drückt `Enter`. +* Das Frontend (das im Browser des Benutzers läuft) sendet diesen `username` und das `password` an eine bestimmte URL in unserer API (deklariert mit `tokenUrl="token"`). +* Die API überprüft den `username` und das `password` und antwortet mit einem „Token“ (wir haben davon noch nichts implementiert). + * Ein „Token“ ist lediglich ein String mit einem Inhalt, den wir später verwenden können, um diesen Benutzer zu verifizieren. + * Normalerweise läuft ein Token nach einiger Zeit ab. + * Daher muss sich der Benutzer irgendwann später erneut anmelden. + * Und wenn der Token gestohlen wird, ist das Risiko geringer. Es handelt sich nicht um einen dauerhaften Schlüssel, der (in den meisten Fällen) für immer funktioniert. +* Das Frontend speichert diesen Token vorübergehend irgendwo. +* Der Benutzer klickt im Frontend, um zu einem anderen Abschnitt der Frontend-Web-Anwendung zu gelangen. +* Das Frontend muss weitere Daten von der API abrufen. + * Es benötigt jedoch eine Authentifizierung für diesen bestimmten Endpunkt. + * Um sich also bei unserer API zu authentifizieren, sendet es einen Header `Authorization` mit dem Wert `Bearer` plus dem Token. + * Wenn der Token `foobar` enthielte, wäre der Inhalt des `Authorization`-Headers: `Bearer foobar`. + +## **FastAPI**s `OAuth2PasswordBearer` + +**FastAPI** bietet mehrere Tools auf unterschiedlichen Abstraktionsebenen zur Implementierung dieser Sicherheitsfunktionen. + +In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`. + +!!! info + Ein „Bearer“-Token ist nicht die einzige Option. + + Aber es ist die beste für unseren Anwendungsfall. + + Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht. + + In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen. + +Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. + +=== "Python 3.9+" + + ```Python hl_lines="8" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +!!! tip "Tipp" + Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. + + Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen. + + Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert. + +Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet. + +Wir werden demnächst auch die eigentliche Pfadoperation erstellen. + +!!! info + Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`. + + Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten. + +Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“. + +Es könnte wie folgt aufgerufen werden: + +```Python +oauth2_scheme(some, parameters) +``` + +Es kann also mit `Depends` verwendet werden. + +### Verwendung + +Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. + +**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren. + +!!! info "Technische Details" + **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. + + Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss. + +## Was es macht + +FastAPI wird im Request nach diesem `Authorization`-Header suchen, prüfen, ob der Wert `Bearer` plus ein Token ist, und den Token als `str` zurückgeben. + +Wenn es keinen `Authorization`-Header sieht, oder der Wert keinen `Bearer`-Token hat, antwortet es direkt mit einem 401-Statuscode-Error (`UNAUTHORIZED`). + +Sie müssen nicht einmal prüfen, ob der Token existiert, um einen Fehler zurückzugeben. Seien Sie sicher, dass Ihre Funktion, wenn sie ausgeführt wird, ein `str` in diesem Token enthält. + +Sie können das bereits in der interaktiven Dokumentation ausprobieren: + +<img src="/img/tutorial/security/image03.png"> + +Wir überprüfen im Moment noch nicht die Gültigkeit des Tokens, aber das ist bereits ein Anfang. + +## Zusammenfassung + +Mit nur drei oder vier zusätzlichen Zeilen haben Sie also bereits eine primitive Form der Sicherheit. From b9eeede27343fdb1aff86bd6584570b284a80ffc Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:07:21 +0100 Subject: [PATCH 116/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/encoder.md`=20(#10385)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/encoder.md | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 docs/de/docs/tutorial/encoder.md diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md new file mode 100644 index 000000000..12f73bd12 --- /dev/null +++ b/docs/de/docs/tutorial/encoder.md @@ -0,0 +1,42 @@ +# JSON-kompatibler Encoder + +Es gibt Fälle, da möchten Sie einen Datentyp (etwa ein Pydantic-Modell) in etwas konvertieren, das kompatibel mit JSON ist (etwa ein `dict`, eine `list`e, usw.). + +Zum Beispiel, wenn Sie es in einer Datenbank speichern möchten. + +Dafür bietet **FastAPI** eine Funktion `jsonable_encoder()`. + +## `jsonable_encoder` verwenden + +Stellen wir uns vor, Sie haben eine Datenbank `fake_db`, die nur JSON-kompatible Daten entgegennimmt. + +Sie akzeptiert zum Beispiel keine `datetime`-Objekte, da die nicht kompatibel mit JSON sind. + +Ein `datetime`-Objekt müsste also in einen `str` umgewandelt werden, der die Daten im <a href="https://en.wikipedia.org/wiki/ISO_8601" class="external-link" target="_blank">ISO-Format</a> enthält. + +Genauso würde die Datenbank kein Pydantic-Modell (ein Objekt mit Attributen) akzeptieren, sondern nur ein `dict`. + +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: + +=== "Python 3.10+" + + ```Python hl_lines="4 21" + {!> ../../../docs_src/encoder/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 22" + {!> ../../../docs_src/encoder/tutorial001.py!} + ``` + +In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. + +Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard-<a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a> kodiert werden kann. + +Es wird also kein großer `str` zurückgegeben, der die Daten im JSON-Format (als String) enthält. Es wird eine Python-Standarddatenstruktur (z. B. ein `dict`) zurückgegeben, mit Werten und Unterwerten, die alle mit JSON kompatibel sind. + +!!! note "Hinweis" + `jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich. From 1628e96a0fa077c1e34593d7f4cea089839427eb Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:07:35 +0100 Subject: [PATCH 117/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/request-forms-and-files.md`?= =?UTF-8?q?=20(#10368)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/tutorial/request-forms-and-files.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 docs/de/docs/tutorial/request-forms-and-files.md diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..86b1406e6 --- /dev/null +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,69 @@ +# Formulardaten und Dateien im Request + +Sie können gleichzeitig Dateien und Formulardaten mit `File` und `Form` definieren. + +!!! info + Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + + Z. B. `pip install python-multipart`. + +## `File` und `Form` importieren + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +## `File` und `Form`-Parameter definieren + +Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: + +=== "Python 3.9+" + + ```Python hl_lines="10-12" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. + +Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren. + +!!! warning "Achtung" + Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + + Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +## Zusammenfassung + +Verwenden Sie `File` und `Form` zusammen, wenn Sie Daten und Dateien zusammen im selben Request empfangen müssen. From 1a6ba6690757f92f4cc78071a30c611d13f63d04 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:07:48 +0100 Subject: [PATCH 118/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/path-operation-configuration.?= =?UTF-8?q?md`=20(#10383)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/path-operation-configuration.md | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 docs/de/docs/tutorial/path-operation-configuration.md diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..80a4fadc9 --- /dev/null +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,179 @@ +# Pfadoperation-Konfiguration + +Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können. + +!!! warning "Achtung" + Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. + +## Response-Statuscode + +Sie können den (HTTP-)`status_code` definieren, den die Response Ihrer *Pfadoperation* verwenden soll. + +Sie können direkt den `int`-Code übergeben, etwa `404`. + +Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="1 15" + {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3 17" + {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3 17" + {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} + ``` + +Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt. + +!!! note "Technische Details" + Sie können auch `from starlette import status` verwenden. + + **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. + +## Tags + +Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`): + +=== "Python 3.10+" + + ```Python hl_lines="15 20 25" + {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17 22 27" + {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 22 27" + {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} + ``` + +Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet: + +<img src="/img/tutorial/path-operation-configuration/image01.png"> + +### Tags mittels Enumeration + +Wenn Sie eine große Anwendung haben, können sich am Ende **viele Tags** anhäufen, und Sie möchten sicherstellen, dass Sie für verwandte *Pfadoperationen* immer den **gleichen Tag** nehmen. + +In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern. + +**FastAPI** unterstützt diese genauso wie einfache Strings: + +```Python hl_lines="1 8-10 13 18" +{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +``` + +## Zusammenfassung und Beschreibung + +Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen: + +=== "Python 3.10+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="20-21" + {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20-21" + {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} + ``` + +## Beschreibung mittels Docstring + +Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der *Pfadoperation* im <abbr title="Ein mehrzeiliger String (keiner Variable zugewiesen) als erster Ausdruck in einer Funktion, wird für die Dokumentation derselben verwendet">Docstring</abbr> der Funktion deklarieren, und **FastAPI** wird sie daraus auslesen. + +Sie können im Docstring <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend). + +=== "Python 3.10+" + + ```Python hl_lines="17-25" + {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19-27" + {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-27" + {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} + ``` + +In der interaktiven Dokumentation sieht das dann so aus: + +<img src="/img/tutorial/path-operation-configuration/image02.png"> + +## Beschreibung der Response + +Die Response können Sie mit dem Parameter `response_description` beschreiben: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="21" + {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} + ``` + +!!! info + beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht. + +!!! check + OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt. + + Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen. + +<img src="/img/tutorial/path-operation-configuration/image03.png"> + +## Eine *Pfadoperation* deprecaten + +Wenn Sie eine *Pfadoperation* als <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr> kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu: + +```Python hl_lines="16" +{!../../../docs_src/path_operation_configuration/tutorial006.py!} +``` + +Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden: + +<img src="/img/tutorial/path-operation-configuration/image04.png"> + +Vergleichen Sie, wie deprecatete und nicht-deprecatete *Pfadoperationen* aussehen: + +<img src="/img/tutorial/path-operation-configuration/image05.png"> + +## Zusammenfassung + +Sie können auf einfache Weise Metadaten für Ihre *Pfadoperationen* definieren, indem Sie den *Pfadoperation-Dekoratoren* Parameter hinzufügen. From 9899a074d346a54b95ba7198fc1d09486509a4df Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:08:05 +0100 Subject: [PATCH 119/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/security/get-current-user.md`?= =?UTF-8?q?=20(#10439)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/security/get-current-user.md | 288 ++++++++++++++++++ 1 file changed, 288 insertions(+) create mode 100644 docs/de/docs/tutorial/security/get-current-user.md diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..09b55a20e --- /dev/null +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -0,0 +1,288 @@ +# Aktuellen Benutzer abrufen + +Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/security/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/security/tutorial001_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/security/tutorial001.py!} + ``` + +Aber das ist immer noch nicht so nützlich. + +Lassen wir es uns den aktuellen Benutzer überreichen. + +## Ein Benutzermodell erstellen + +Erstellen wir zunächst ein Pydantic-Benutzermodell. + +So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="5 12-16" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="5 12-16" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 13-17" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Eine `get_current_user`-Abhängigkeit erstellen + +Erstellen wir eine Abhängigkeit `get_current_user`. + +Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? + +`get_current_user` wird seinerseits von `oauth2_scheme` abhängen, das wir zuvor erstellt haben. + +So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: + +=== "Python 3.10+" + + ```Python hl_lines="25" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="25" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="26" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="25" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +## Den Benutzer holen + +`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: + +=== "Python 3.10+" + + ```Python hl_lines="19-22 26-27" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19-22 26-27" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20-23 27-28" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19-22 26-27" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +## Den aktuellen Benutzer einfügen + +Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="31" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="31" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="32" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="31" + {!> ../../../docs_src/security/tutorial002.py!} + ``` + +Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. + +Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen. + +!!! tip "Tipp" + Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. + + Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt. + +!!! check + Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben. + + Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann. + +## Andere Modelle + +Sie können jetzt den aktuellen Benutzer direkt in den *Pfadoperation-Funktionen* abrufen und die Sicherheitsmechanismen auf **Dependency Injection** Ebene handhaben, mittels `Depends`. + +Und Sie können alle Modelle und Daten für die Sicherheitsanforderungen verwenden (in diesem Fall ein Pydantic-Modell `User`). + +Sie sind jedoch nicht auf die Verwendung von bestimmten Datenmodellen, Klassen, oder Typen beschränkt. + +Möchten Sie eine `id` und eine `email` und keinen `username` in Ihrem Modell haben? Kein Problem. Sie können dieselben Tools verwenden. + +Möchten Sie nur ein `str` haben? Oder nur ein `dict`? Oder direkt eine Instanz eines Modells einer Datenbank-Klasse? Es funktioniert alles auf die gleiche Weise. + +Sie haben eigentlich keine Benutzer, die sich bei Ihrer Anwendung anmelden, sondern Roboter, Bots oder andere Systeme, die nur über einen Zugriffstoken verfügen? Auch hier funktioniert alles gleich. + +Verwenden Sie einfach jede Art von Modell, jede Art von Klasse, jede Art von Datenbank, die Sie für Ihre Anwendung benötigen. **FastAPI** deckt das alles mit seinem Dependency Injection System ab. + +## Codegröße + +Dieses Beispiel mag ausführlich erscheinen. Bedenken Sie, dass wir Sicherheit, Datenmodelle, Hilfsfunktionen und *Pfadoperationen* in derselben Datei vermischen. + +Aber hier ist der entscheidende Punkt. + +Der Code für Sicherheit und Dependency Injection wird einmal geschrieben. + +Sie können es so komplex gestalten, wie Sie möchten. Und dennoch haben Sie es nur einmal geschrieben, an einer einzigen Stelle. Mit all der Flexibilität. + +Aber Sie können Tausende von Endpunkten (*Pfadoperationen*) haben, die dasselbe Sicherheitssystem verwenden. + +Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwendung dieser und anderer von Ihnen erstellter Abhängigkeiten. + +Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: + +=== "Python 3.10+" + + ```Python hl_lines="30-32" + {!> ../../../docs_src/security/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-32" + {!> ../../../docs_src/security/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31-33" + {!> ../../../docs_src/security/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Zusammenfassung + +Sie können jetzt den aktuellen Benutzer direkt in Ihrer *Pfadoperation-Funktion* abrufen. + +Wir haben bereits die Hälfte geschafft. + +Wir müssen jetzt nur noch eine *Pfadoperation* hinzufügen, mittels der der Benutzer/Client tatsächlich seinen `username` und `password` senden kann. + +Das kommt als nächstes. From 504fb2a64f832cee01950a4081c8ea91092be579 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:08:44 +0100 Subject: [PATCH 120/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/security/simple-oauth2.md`=20?= =?UTF-8?q?(#10504)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/tutorial/security/simple-oauth2.md | 435 ++++++++++++++++++ 1 file changed, 435 insertions(+) create mode 100644 docs/de/docs/tutorial/security/simple-oauth2.md diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..ed280d486 --- /dev/null +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,435 @@ +# Einfaches OAuth2 mit Password und Bearer + +Lassen Sie uns nun auf dem vorherigen Kapitel aufbauen und die fehlenden Teile hinzufügen, um einen vollständigen Sicherheits-Flow zu erhalten. + +## `username` und `password` entgegennehmen + +Wir werden **FastAPIs** Sicherheits-Werkzeuge verwenden, um den `username` und das `password` entgegenzunehmen. + +OAuth2 spezifiziert, dass der Client/Benutzer bei Verwendung des „Password Flow“ (den wir verwenden) die Felder `username` und `password` als Formulardaten senden muss. + +Und die Spezifikation sagt, dass die Felder so benannt werden müssen. `user-name` oder `email` würde also nicht funktionieren. + +Aber keine Sorge, Sie können sie Ihren Endbenutzern im Frontend so anzeigen, wie Sie möchten. + +Und Ihre Datenbankmodelle können beliebige andere Namen verwenden. + +Aber für die Login-*Pfadoperation* müssen wir diese Namen verwenden, um mit der Spezifikation kompatibel zu sein (und beispielsweise das integrierte API-Dokumentationssystem verwenden zu können). + +Die Spezifikation besagt auch, dass `username` und `password` als Formulardaten gesendet werden müssen (hier also kein JSON). + +### <abbr title="Geltungsbereich">`scope`</abbr> + +Ferner sagt die Spezifikation, dass der Client ein weiteres Formularfeld "`scope`" („Geltungsbereich“) senden kann. + +Der Name des Formularfelds lautet `scope` (im Singular), tatsächlich handelt es sich jedoch um einen langen String mit durch Leerzeichen getrennten „Scopes“. + +Jeder „Scope“ ist nur ein String (ohne Leerzeichen). + +Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel: + +* `users:read` oder `users:write` sind gängige Beispiele. +* `instagram_basic` wird von Facebook / Instagram verwendet. +* `https://www.googleapis.com/auth/drive` wird von Google verwendet. + +!!! info + In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + + Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. + + Diese Details sind implementierungsspezifisch. + + Für OAuth2 sind es einfach nur Strings. + +## Code, um `username` und `password` entgegenzunehmen. + +Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um das zu erledigen. + +### `OAuth2PasswordRequestForm` + +Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: + +=== "Python 3.10+" + + ```Python hl_lines="4 78" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 78" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 79" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +`OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: + +* Dem `username`. +* Dem `password`. +* Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings. +* Einem optionalen `grant_type` („Art der Anmeldung“). + +!!! tip "Tipp" + Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. + + Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`. + +* Eine optionale `client_id` (benötigen wir für unser Beispiel nicht). +* Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht). + +!!! info + `OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`. + + `OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt. + + Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können. + + Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt. + +### Die Formulardaten verwenden + +!!! tip "Tipp" + Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. + + In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen. + +Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld. + +Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect username or password“ zurück. + +Für den Fehler verwenden wir die Exception `HTTPException`: + +=== "Python 3.10+" + + ```Python hl_lines="3 79-81" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3 79-81" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3 80-82" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +### Das Passwort überprüfen + +Zu diesem Zeitpunkt liegen uns die Benutzerdaten aus unserer Datenbank vor, das Passwort haben wir jedoch noch nicht überprüft. + +Lassen Sie uns diese Daten zunächst in das Pydantic-Modell `UserInDB` einfügen. + +Sie sollten niemals Klartext-Passwörter speichern, daher verwenden wir ein (gefaktes) Passwort-Hashing-System. + +Wenn die Passwörter nicht übereinstimmen, geben wir denselben Fehler zurück. + +#### Passwort-Hashing + +„Hashing“ bedeutet: Konvertieren eines Inhalts (in diesem Fall eines Passworts) in eine Folge von Bytes (ein schlichter String), die wie Kauderwelsch aussieht. + +Immer wenn Sie genau den gleichen Inhalt (genau das gleiche Passwort) übergeben, erhalten Sie genau den gleichen Kauderwelsch. + +Sie können jedoch nicht vom Kauderwelsch zurück zum Passwort konvertieren. + +##### Warum Passwort-Hashing verwenden? + +Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Ihrer Benutzer, sondern nur die Hashes. + +Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). + +=== "Python 3.10+" + + ```Python hl_lines="82-85" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="82-85" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="83-86" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +#### Über `**user_dict` + +`UserInDB(**user_dict)` bedeutet: + +*Übergib die Schlüssel und Werte des `user_dict` direkt als Schlüssel-Wert-Argumente, äquivalent zu:* + +```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 + Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}. + +## Den Token zurückgeben + +Die Response des `token`-Endpunkts muss ein JSON-Objekt sein. + +Es sollte einen `token_type` haben. Da wir in unserem Fall „Bearer“-Token verwenden, sollte der Token-Typ "`bearer`" sein. + +Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffstoken enthält. + +In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück. + +!!! tip "Tipp" + Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und <abbr title="JSON Web Tokens">JWT</abbr>-Tokens. + + Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen. + +=== "Python 3.10+" + + ```Python hl_lines="87" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="87" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="88" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="83" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="85" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +!!! tip "Tipp" + Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. + + Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden. + + Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten. + + Den Rest erledigt **FastAPI** für Sie. + +## Die Abhängigkeiten aktualisieren + +Jetzt werden wir unsere Abhängigkeiten aktualisieren. + +Wir möchten den `current_user` *nur* erhalten, wenn dieser Benutzer aktiv ist. + +Daher erstellen wir eine zusätzliche Abhängigkeit `get_current_active_user`, die wiederum `get_current_user` als Abhängigkeit verwendet. + +Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer nicht existiert oder inaktiv ist. + +In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: + +=== "Python 3.10+" + + ```Python hl_lines="58-66 69-74 94" + {!> ../../../docs_src/security/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="58-66 69-74 94" + {!> ../../../docs_src/security/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="59-67 70-75 95" + {!> ../../../docs_src/security/tutorial003_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! info + Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation. + + Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben. + + Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten. + + Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren. + + Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen. + + Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein. + + Das ist der Vorteil von Standards ... + +## Es in Aktion sehen + +Öffnen Sie die interaktive Dokumentation: <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +### Authentifizieren + +Klicken Sie auf den Button „Authorize“. + +Verwenden Sie die Anmeldedaten: + +Benutzer: `johndoe` + +Passwort: `secret`. + +<img src="/img/tutorial/security/image04.png"> + +Nach der Authentifizierung im System sehen Sie Folgendes: + +<img src="/img/tutorial/security/image05.png"> + +### Die eigenen Benutzerdaten ansehen + +Verwenden Sie nun die Operation `GET` mit dem Pfad `/users/me`. + +Sie erhalten Ihre Benutzerdaten: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + +<img src="/img/tutorial/security/image06.png"> + +Wenn Sie auf das Schlosssymbol klicken und sich abmelden und dann den gleichen Vorgang nochmal versuchen, erhalten Sie einen HTTP 401 Error: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Inaktiver Benutzer + +Versuchen Sie es nun mit einem inaktiven Benutzer und authentisieren Sie sich mit: + +Benutzer: `alice`. + +Passwort: `secret2`. + +Und versuchen Sie, die Operation `GET` mit dem Pfad `/users/me` zu verwenden. + +Sie erhalten die Fehlermeldung „Inactive user“: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Zusammenfassung + +Sie verfügen jetzt über die Tools, um ein vollständiges Sicherheitssystem basierend auf `username` und `password` für Ihre API zu implementieren. + +Mit diesen Tools können Sie das Sicherheitssystem mit jeder Datenbank und jedem Benutzer oder Datenmodell kompatibel machen. + +Das einzige fehlende Detail ist, dass es noch nicht wirklich „sicher“ ist. + +Im nächsten Kapitel erfahren Sie, wie Sie eine sichere Passwort-Hashing-Bibliothek und <abbr title="JSON Web Tokens">JWT</abbr>-Token verwenden. From 2228740177caaebcd9020e4709ab31bc053263cc Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:08:55 +0100 Subject: [PATCH 121/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/extra-data-types.md`=20(#1053?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/extra-data-types.md | 130 ++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 docs/de/docs/tutorial/extra-data-types.md diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..0fcb20683 --- /dev/null +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -0,0 +1,130 @@ +# Zusätzliche Datentypen + +Bisher haben Sie gängige Datentypen verwendet, wie zum Beispiel: + +* `int` +* `float` +* `str` +* `bool` + +Sie können aber auch komplexere Datentypen verwenden. + +Und Sie haben immer noch dieselbe Funktionalität wie bisher gesehen: + +* Großartige Editor-Unterstützung. +* Datenkonvertierung bei eingehenden Requests. +* Datenkonvertierung für Response-Daten. +* Datenvalidierung. +* Automatische Annotation und Dokumentation. + +## Andere Datentypen + +Hier sind einige der zusätzlichen Datentypen, die Sie verwenden können: + +* `UUID`: + * Ein standardmäßiger „universell eindeutiger Bezeichner“ („Universally Unique Identifier“), der in vielen Datenbanken und Systemen als ID üblich ist. + * Wird in Requests und Responses als `str` dargestellt. +* `datetime.datetime`: + * Ein Python-`datetime.datetime`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15T15:53:00+05:00`. +* `datetime.date`: + * Python-`datetime.date`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15`. +* `datetime.time`: + * Ein Python-`datetime.time`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `14:23:55.003`. +* `datetime.timedelta`: + * Ein Python-`datetime.timedelta`. + * Wird in Requests und Responses als `float` der Gesamtsekunden dargestellt. + * Pydantic ermöglicht auch die Darstellung als „ISO 8601 Zeitdifferenz-Kodierung“, <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#json_encoders" class="external-link" target="_blank">Weitere Informationen finden Sie in der Dokumentation</a>. +* `frozenset`: + * Wird in Requests und Responses wie ein `set` behandelt: + * Bei Requests wird eine Liste gelesen, Duplikate entfernt und in ein `set` umgewandelt. + * Bei Responses wird das `set` in eine `list`e umgewandelt. + * Das generierte Schema zeigt an, dass die `set`-Werte eindeutig sind (unter Verwendung von JSON Schemas `uniqueItems`). +* `bytes`: + * Standard-Python-`bytes`. + * In Requests und Responses werden sie als `str` behandelt. + * Das generierte Schema wird anzeigen, dass es sich um einen `str` mit `binary` „Format“ handelt. +* `Decimal`: + * Standard-Python-`Decimal`. + * In Requests und Responses wird es wie ein `float` behandelt. +* Sie können alle gültigen Pydantic-Datentypen hier überprüfen: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic data types</a>. + +## Beispiel + +Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden. + +=== "Python 3.10+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 3 13-17" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 2 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` + +Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: + +=== "Python 3.10+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-20" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` From daecb67c1cf3679ee384d747145da5ad3ad4d819 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:09:16 +0100 Subject: [PATCH 122/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/dependencies/dependencies-in-?= =?UTF-8?q?path-operation-decorators.md`=20(#10411)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...pendencies-in-path-operation-decorators.md | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md 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 new file mode 100644 index 000000000..2919aebaf --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,139 @@ +# Abhängigkeiten in Pfadoperation-Dekoratoren + +Manchmal benötigen Sie den Rückgabewert einer Abhängigkeit innerhalb Ihrer *Pfadoperation-Funktion* nicht wirklich. + +Oder die Abhängigkeit gibt keinen Wert zurück. + +Aber Sie müssen Sie trotzdem ausführen/auflösen. + +In diesen Fällen können Sie, anstatt einen Parameter der *Pfadoperation-Funktion* mit `Depends` zu deklarieren, eine `list`e von `dependencies` zum *Pfadoperation-Dekorator* hinzufügen. + +## `dependencies` zum *Pfadoperation-Dekorator* hinzufügen + +Der *Pfadoperation-Dekorator* erhält ein optionales Argument `dependencies`. + +Es sollte eine `list`e von `Depends()` sein: + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +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" + Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an. + + Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben. + + Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten. + +!!! info + In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`. + + Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md){.internal-link target=_blank} erzielen. + +## Abhängigkeitsfehler und -Rückgabewerte + +Sie können dieselben Abhängigkeits-*Funktionen* verwenden, die Sie normalerweise verwenden. + +### Abhängigkeitsanforderungen + +Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhängigkeiten deklarieren: + +=== "Python 3.9+" + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7 12" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6 11" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### Exceptions auslösen + +Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeiten: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### Rückgabewerte + +Und sie können Werte zurückgeben oder nicht, die Werte werden nicht verwendet. + +Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Sie bereits an anderer Stelle verwenden, wiederverwenden, und auch wenn der Wert nicht verwendet wird, wird die Abhängigkeit ausgeführt: + +=== "Python 3.9+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +## Abhängigkeiten für eine Gruppe von *Pfadoperationen* + +Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Größere Anwendungen – Mehrere Dateien](../../tutorial/bigger-applications.md){.internal-link target=_blank}), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren. + +## Globale Abhängigkeiten + +Als Nächstes werden wir sehen, wie man Abhängigkeiten zur gesamten `FastAPI`-Anwendung hinzufügt, sodass sie für jede *Pfadoperation* gelten. From 4081ce3b29ece75bb8e1c23a12edce68cadc0636 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:09:35 +0100 Subject: [PATCH 123/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/security/index.md`=20(#10429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/security/index.md | 101 ++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 docs/de/docs/tutorial/security/index.md diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md new file mode 100644 index 000000000..7a11e704d --- /dev/null +++ b/docs/de/docs/tutorial/security/index.md @@ -0,0 +1,101 @@ +# Sicherheit + +Es gibt viele Wege, Sicherheit, Authentifizierung und Autorisierung zu handhaben. + +Und normalerweise ist es ein komplexes und „schwieriges“ Thema. + +In vielen Frameworks und Systemen erfordert allein die Handhabung von Sicherheit und Authentifizierung viel Aufwand und Code (in vielen Fällen kann er 50 % oder mehr des gesamten geschriebenen Codes ausmachen). + +**FastAPI** bietet mehrere Tools, die Ihnen helfen, schnell und auf standardisierte Weise mit **Sicherheit** umzugehen, ohne alle Sicherheits-Spezifikationen studieren und erlernen zu müssen. + +Aber schauen wir uns zunächst ein paar kleine Konzepte an. + +## In Eile? + +Wenn Ihnen diese Begriffe egal sind und Sie einfach *jetzt* Sicherheit mit Authentifizierung basierend auf Benutzername und Passwort hinzufügen müssen, fahren Sie mit den nächsten Kapiteln fort. + +## OAuth2 + +OAuth2 ist eine Spezifikation, die verschiedene Möglichkeiten zur Handhabung von Authentifizierung und Autorisierung definiert. + +Es handelt sich um eine recht umfangreiche Spezifikation, und sie deckt mehrere komplexe Anwendungsfälle ab. + +Sie umfasst Möglichkeiten zur Authentifizierung mithilfe eines „Dritten“ („third party“). + +Das ist es, was alle diese „Login mit Facebook, Google, Twitter, GitHub“-Systeme unter der Haube verwenden. + +### OAuth 1 + +Es gab ein OAuth 1, das sich stark von OAuth2 unterscheidet und komplexer ist, da es direkte Spezifikationen enthält, wie die Kommunikation verschlüsselt wird. + +Heutzutage ist es nicht sehr populär und wird kaum verwendet. + +OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird. + +!!! tip "Tipp" + Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. + + +## OpenID Connect + +OpenID Connect ist eine weitere Spezifikation, die auf **OAuth2** basiert. + +Sie erweitert lediglich OAuth2, indem sie einige Dinge spezifiziert, die in OAuth2 relativ mehrdeutig sind, um zu versuchen, es interoperabler zu machen. + +Beispielsweise verwendet der Google Login OpenID Connect (welches seinerseits OAuth2 verwendet). + +Aber der Facebook Login unterstützt OpenID Connect nicht. Es hat seine eigene Variante von OAuth2. + +### OpenID (nicht „OpenID Connect“) + +Es gab auch eine „OpenID“-Spezifikation. Sie versuchte das Gleiche zu lösen wie **OpenID Connect**, basierte aber nicht auf OAuth2. + +Es handelte sich also um ein komplett zusätzliches System. + +Heutzutage ist es nicht sehr populär und wird kaum verwendet. + +## OpenAPI + +OpenAPI (früher bekannt als Swagger) ist die offene Spezifikation zum Erstellen von APIs (jetzt Teil der Linux Foundation). + +**FastAPI** basiert auf **OpenAPI**. + +Das ist es, was erlaubt, mehrere automatische interaktive Dokumentations-Oberflächen, Codegenerierung, usw. zu haben. + +OpenAPI bietet die Möglichkeit, mehrere Sicherheits„systeme“ zu definieren. + +Durch deren Verwendung können Sie alle diese Standards-basierten Tools nutzen, einschließlich dieser interaktiven Dokumentationssysteme. + +OpenAPI definiert die folgenden Sicherheitsschemas: + +* `apiKey`: ein anwendungsspezifischer Schlüssel, der stammen kann von: + * Einem Query-Parameter. + * Einem Header. + * Einem Cookie. +* `http`: Standard-HTTP-Authentifizierungssysteme, einschließlich: + * `bearer`: ein Header `Authorization` mit dem Wert `Bearer` plus einem Token. Dies wird von OAuth2 geerbt. + * HTTP Basic Authentication. + * HTTP Digest, usw. +* `oauth2`: Alle OAuth2-Methoden zum Umgang mit Sicherheit (genannt „Flows“). + * Mehrere dieser Flows eignen sich zum Aufbau eines OAuth 2.0-Authentifizierungsanbieters (wie Google, Facebook, Twitter, GitHub usw.): + * `implicit` + * `clientCredentials` + * `authorizationCode` + * Es gibt jedoch einen bestimmten „Flow“, der perfekt für die direkte Abwicklung der Authentifizierung in derselben Anwendung verwendet werden kann: + * `password`: Einige der nächsten Kapitel werden Beispiele dafür behandeln. +* `openIdConnect`: bietet eine Möglichkeit, zu definieren, wie OAuth2-Authentifizierungsdaten automatisch ermittelt werden können. + * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist. + + +!!! tip "Tipp" + Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. + + Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird. + +## **FastAPI** Tools + +FastAPI stellt für jedes dieser Sicherheitsschemas im Modul `fastapi.security` verschiedene Tools bereit, die die Verwendung dieser Sicherheitsmechanismen vereinfachen. + +In den nächsten Kapiteln erfahren Sie, wie Sie mit diesen von **FastAPI** bereitgestellten Tools Sicherheit zu Ihrer API hinzufügen. + +Und Sie werden auch sehen, wie dies automatisch in das interaktive Dokumentationssystem integriert wird. From 544b5872c0ce283194b456942f37fe5d012d2ede Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:09:48 +0100 Subject: [PATCH 124/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/dependencies/sub-dependencies?= =?UTF-8?q?.md`=20(#10409)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/dependencies/sub-dependencies.md | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 docs/de/docs/tutorial/dependencies/sub-dependencies.md diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..0fa2af839 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,194 @@ +# Unterabhängigkeiten + +Sie können Abhängigkeiten erstellen, die **Unterabhängigkeiten** haben. + +Diese können so **tief** verschachtelt sein, wie nötig. + +**FastAPI** kümmert sich darum, sie aufzulösen. + +## Erste Abhängigkeit, „Dependable“ + +Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. + +Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Funktionsweise der Unterabhängigkeiten zu konzentrieren. + +## Zweite Abhängigkeit, „Dependable“ und „Dependant“ + +Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): + +=== "Python 3.10+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +Betrachten wir die deklarierten Parameter: + +* Obwohl diese Funktion selbst eine Abhängigkeit ist („Dependable“, etwas hängt von ihr ab), deklariert sie auch eine andere Abhängigkeit („Dependant“, sie hängt von etwas anderem ab). + * Sie hängt von `query_extractor` ab und weist den von diesem zurückgegebenen Wert dem Parameter `q` zu. +* Sie deklariert außerdem ein optionales `last_query`-Cookie, ein `str`. + * Wenn der Benutzer keine Query `q` übermittelt hat, verwenden wir die zuletzt übermittelte Query, die wir zuvor in einem Cookie gespeichert haben. + +## Die Abhängigkeit verwenden + +Diese Abhängigkeit verwenden wir nun wie folgt: + +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="22" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +!!! info + Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`. + + Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird. + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Dieselbe Abhängigkeit mehrmals verwenden + +Wenn eine Ihrer Abhängigkeiten mehrmals für dieselbe *Pfadoperation* deklariert wird, beispielsweise wenn mehrere Abhängigkeiten eine gemeinsame Unterabhängigkeit haben, wird **FastAPI** diese Unterabhängigkeit nur einmal pro Request aufrufen. + +Und es speichert den zurückgegebenen Wert in einem <abbr title="Mechanismus, der bereits berechnete/generierte Werte zwischenspeichert, um sie später wiederzuverwenden, anstatt sie erneut zu berechnen.">„Cache“</abbr> und übergibt diesen gecachten Wert an alle „Dependanten“, die ihn in diesem spezifischen Request benötigen, anstatt die Abhängigkeit mehrmals für denselben Request aufzurufen. + +In einem fortgeschrittenen Szenario, bei dem Sie wissen, dass die Abhängigkeit bei jedem Schritt (möglicherweise mehrmals) in derselben Anfrage aufgerufen werden muss, anstatt den zwischengespeicherten Wert zu verwenden, können Sie den Parameter `use_cache=False` festlegen, wenn Sie `Depends` verwenden: + +=== "Python 3.8+" + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} + ``` + +## Zusammenfassung + +Abgesehen von all den ausgefallenen Wörtern, die hier verwendet werden, ist das **Dependency Injection**-System recht simpel. + +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" + All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein. + + Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist. + + Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen. From 0262f1b9eb6933d393f2fcf381152ef405c95be8 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:10:01 +0100 Subject: [PATCH 125/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20German=20transl?= =?UTF-8?q?ation=20for=20`docs/de/docs/fastapi-people.md`=20(#10285)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/fastapi-people.md | 176 +++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 docs/de/docs/fastapi-people.md diff --git a/docs/de/docs/fastapi-people.md b/docs/de/docs/fastapi-people.md new file mode 100644 index 000000000..522a4bce5 --- /dev/null +++ b/docs/de/docs/fastapi-people.md @@ -0,0 +1,176 @@ +--- +hide: + - navigation +--- + +# FastAPI Leute + +FastAPI hat eine großartige Gemeinschaft, die Menschen mit unterschiedlichstem Hintergrund willkommen heißt. + +## Erfinder - Betreuer + +Hey! 👋 + +Das bin ich: + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.maintainers %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> +{% endfor %} + +</div> +{% endif %} + +Ich bin der Erfinder und Betreuer von **FastAPI**. Sie können mehr darüber in [FastAPI helfen – Hilfe erhalten – Mit dem Autor vernetzen](help-fastapi.md#mit-dem-autor-vernetzen){.internal-link target=_blank} erfahren. + +... Aber hier möchte ich Ihnen die Gemeinschaft vorstellen. + +--- + +**FastAPI** erhält eine Menge Unterstützung aus der Gemeinschaft. Und ich möchte ihre Beiträge hervorheben. + +Das sind die Menschen, die: + +* [Anderen bei Fragen auf GitHub helfen](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. +* [<abbr title='Pull Request – „Zieh-Anfrage“: Geänderten Quellcode senden, mit dem Vorschlag, ihn mit dem aktuellen Quellcode zu verschmelzen'>Pull Requests</abbr> erstellen](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank}. +* Pull Requests überprüfen (Review), [besonders wichtig für Übersetzungen](contributing.md#ubersetzungen){.internal-link target=_blank}. + +Eine Runde Applaus für sie. 👏 🙇 + +## Aktivste Benutzer im letzten Monat + +Hier die Benutzer, die im letzten Monat am meisten [anderen mit Fragen auf Github](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} geholfen haben. ☕ + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.last_month_active %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Fragen beantwortet: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Experten + +Hier die **FastAPI-Experten**. 🤓 + +Das sind die Benutzer, die *insgesamt* [anderen am meisten mit Fragen auf GitHub geholfen haben](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. + +Sie haben bewiesen, dass sie Experten sind, weil sie vielen anderen geholfen haben. ✨ + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.experts %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Fragen beantwortet: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Top-Mitwirkende + +Hier sind die **Top-Mitwirkenden**. 👷 + +Diese Benutzer haben [die meisten Pull Requests erstellt](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank} welche *<abbr title="Mergen – Zusammenführen: Unterschiedliche Versionen eines Quellcodes zusammenführen">gemerged</abbr>* wurden. + +Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_contributors %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors-Seite</a> sehen. 👷 + +## Top-Rezensenten + +Diese Benutzer sind die **Top-Rezensenten**. 🕵️ + +### Rezensionen für Übersetzungen + +Ich spreche nur ein paar Sprachen (und nicht sehr gut 😅). Daher bestätigen Reviewer [**Übersetzungen der Dokumentation**](contributing.md#ubersetzungen){.internal-link target=_blank}. Ohne sie gäbe es keine Dokumentation in mehreren anderen Sprachen. + +--- + +Die **Top-Reviewer** 🕵️ haben die meisten Pull Requests von anderen überprüft und stellen die Qualität des Codes, der Dokumentation und insbesondere der **Übersetzungen** sicher. + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_reviewers %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Sponsoren + +Dies sind die **Sponsoren**. 😎 + +Sie unterstützen meine Arbeit an **FastAPI** (und andere), hauptsächlich durch <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub-Sponsoren</a>. + +### Gold Sponsoren + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> +{% endfor %} +{% endif %} + +### Silber Sponsoren + +{% if sponsors %} +{% for sponsor in sponsors.silver -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> +{% endfor %} +{% endif %} + +{% if people %} +{% if people.sponsors_50 %} + +### Bronze Sponsoren + +<div class="user-list user-list-center"> +{% for user in people.sponsors_50 %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> +{% endfor %} + +</div> + +{% endif %} +{% endif %} + +### Individuelle Sponsoren + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.sponsors %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> +{% endfor %} + +</div> +{% endif %} + +## Über diese Daten - technische Details + +Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft. + +Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen. + +Diese Daten werden jeden Monat berechnet, Sie können den <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">Quellcode hier lesen</a>. + +Hier weise ich auch auf Beiträge von Sponsoren hin. + +Ich behalte mir auch das Recht vor, den Algorithmus, die Abschnitte, die Schwellenwerte usw. zu aktualisieren (nur für den Fall 🤷). From 92fe883a2c0f77675ce44650a024e4ffe2cd36a3 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:10:13 +0100 Subject: [PATCH 126/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/dependencies/global-dependenc?= =?UTF-8?q?ies.md`=20(#10420)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/global-dependencies.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/de/docs/tutorial/dependencies/global-dependencies.md diff --git a/docs/de/docs/tutorial/dependencies/global-dependencies.md b/docs/de/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..8aa0899b8 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,34 @@ +# Globale Abhängigkeiten + +Bei einigen Anwendungstypen möchten Sie möglicherweise Abhängigkeiten zur gesamten Anwendung hinzufügen. + +Ähnlich wie Sie [`dependencies` zu den *Pfadoperation-Dekoratoren* hinzufügen](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} können, können Sie sie auch zur `FastAPI`-Anwendung hinzufügen. + +In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet: + +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an.py!} + ``` + +=== "Python 3.8 nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial012.py!} + ``` + +Und alle Ideen aus dem Abschnitt über das [Hinzufügen von `dependencies` zu den *Pfadoperation-Dekoratoren*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} gelten weiterhin, aber in diesem Fall für alle *Pfadoperationen* in der Anwendung. + +## Abhängigkeiten für Gruppen von *Pfadoperationen* + +Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren. From f43ac35fe5d3f8b78e2f783ea092f078a326b069 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:10:29 +0100 Subject: [PATCH 127/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/dependencies/dependencies-wit?= =?UTF-8?q?h-yield.md`=20(#10422)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-with-yield.md | 284 ++++++++++++++++++ 1 file changed, 284 insertions(+) create mode 100644 docs/de/docs/tutorial/dependencies/dependencies-with-yield.md diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..e29e87156 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,284 @@ +# Abhängigkeiten mit yield + +FastAPI unterstützt Abhängigkeiten, die nach Abschluss einige <abbr title="Manchmal auch genannt „Exit Code“, „Cleanup Code“, „Teardown Code“, „Closing Code“, „Kontext Manager Exit Code“, usw.">zusätzliche Schritte ausführen</abbr>. + +Verwenden Sie dazu `yield` statt `return` und schreiben Sie die zusätzlichen Schritte / den zusätzlichen Code danach. + +!!! tip "Tipp" + Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden. + +!!! note "Technische Details" + Jede Funktion, die dekoriert werden kann mit: + + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + + kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden. + + Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern. + +## Eine Datenbank-Abhängigkeit mit `yield`. + +Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach Abschluss schließen. + +Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird: + +```Python hl_lines="2-4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird: + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +Der auf die `yield`-Anweisung folgende Code wird ausgeführt, nachdem die Response gesendet wurde: + +```Python hl_lines="5-6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! tip "Tipp" + Sie können `async`hrone oder reguläre Funktionen verwenden. + + **FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten. + +## Eine Abhängigkeit mit `yield` und `try`. + +Wenn Sie einen `try`-Block in einer Abhängigkeit mit `yield` verwenden, empfangen Sie alle Exceptions, die bei Verwendung der Abhängigkeit geworfen wurden. + +Wenn beispielsweise ein Code irgendwann in der Mitte, in einer anderen Abhängigkeit oder in einer *Pfadoperation*, ein „Rollback“ einer Datenbanktransaktion oder einen anderen Fehler verursacht, empfangen Sie die resultierende Exception in Ihrer Abhängigkeit. + +Sie können also mit `except SomeException` diese bestimmte Exception innerhalb der Abhängigkeit handhaben. + +Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht. + +```Python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +## Unterabhängigkeiten mit `yield`. + +Sie können Unterabhängigkeiten und „Bäume“ von Unterabhängigkeiten beliebiger Größe und Form haben, und einige oder alle davon können `yield` verwenden. + +**FastAPI** stellt sicher, dass der „Exit-Code“ in jeder Abhängigkeit mit `yield` in der richtigen Reihenfolge ausgeführt wird. + +Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `dependency_a` abhängen: + +=== "Python 3.9+" + + ```Python hl_lines="6 14 22" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 13 21" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="4 12 20" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +Und alle können `yield` verwenden. + +In diesem Fall benötigt `dependency_c` zum Ausführen seines Exit-Codes, dass der Wert von `dependency_b` (hier `dep_b` genannt) verfügbar ist. + +Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` genannt) für seinen Exit-Code. + +=== "Python 3.9+" + + ```Python hl_lines="18-19 26-27" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-18 25-26" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16-17 24-25" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +Auf die gleiche Weise könnten Sie einige Abhängigkeiten mit `yield` und einige andere Abhängigkeiten mit `return` haben, und alle können beliebig voneinander abhängen. + +Und Sie könnten eine einzelne Abhängigkeit haben, die auf mehreren ge`yield`eten Abhängigkeiten basiert, usw. + +Sie können beliebige Kombinationen von Abhängigkeiten haben. + +**FastAPI** stellt sicher, dass alles in der richtigen Reihenfolge ausgeführt wird. + +!!! note "Technische Details" + Dieses funktioniert dank Pythons <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Kontextmanager</a>. + + **FastAPI** verwendet sie intern, um das zu erreichen. + +## Abhängigkeiten mit `yield` und `HTTPException`. + +Sie haben gesehen, dass Ihre Abhängigkeiten `yield` verwenden können und `try`-Blöcke haben können, die Exceptions abfangen. + +Auf die gleiche Weise könnten Sie im Exit-Code nach dem `yield` eine `HTTPException` oder ähnliches auslösen. + +!!! 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*. + + Aber es ist für Sie da, wenn Sie es brauchen. 🤓 + +=== "Python 3.9+" + + ```Python hl_lines="18-22 31" + {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-21 30" + {!> ../../../docs_src/dependencies/tutorial008b_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16-20 29" + {!> ../../../docs_src/dependencies/tutorial008b.py!} + ``` + +Eine Alternative zum Abfangen von Exceptions (und möglicherweise auch zum Auslösen einer weiteren `HTTPException`) besteht darin, einen [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} zu erstellen. + +## Ausführung von Abhängigkeiten mit `yield` + +Die Ausführungsreihenfolge ähnelt mehr oder weniger dem folgenden Diagramm. Die Zeit verläuft von oben nach unten. Und jede Spalte ist einer der interagierenden oder Code-ausführenden Teilnehmer. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exceptionhandler +participant dep as Abhängigkeit mit yield +participant operation as Pfadoperation +participant tasks as Hintergrundtasks + + Note over client,operation: Kann Exceptions auslösen, inklusive HTTPException + client ->> dep: Startet den Request + Note over dep: Führt den Code bis zum yield aus + opt Löst Exception aus + dep -->> handler: Löst Exception aus + handler -->> client: HTTP-Error-Response + end + dep ->> operation: Führt Abhängigkeit aus, z. B. DB-Session + opt Löst aus + operation -->> dep: Löst Exception aus (z. B. HTTPException) + opt Handhabt + dep -->> dep: Kann Exception abfangen, eine neue HTTPException auslösen, andere Exceptions auslösen + dep -->> handler: Leitet Exception automatisch weiter + end + handler -->> client: HTTP-Error-Response + end + operation ->> client: Sendet Response an Client + Note over client,operation: Response wurde gesendet, kann nicht mehr geändert werden + opt Tasks + operation -->> tasks: Sendet Hintergrundtasks + end + opt Löst andere Exception aus + tasks -->> tasks: Handhabt Exception im Hintergrundtask-Code + end +``` + +!!! info + Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein. + + Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden. + +!!! 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. + + Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten übergeben, einschließlich `HTTPException`, und dann **erneut** an die Exceptionhandler. Wenn es für diese Exception keinen Exceptionhandler gibt, wird sie von der internen Default-`ServerErrorMiddleware` gehandhabt, was einen HTTP-Statuscode 500 zurückgibt, um den Client darüber zu informieren, dass ein Fehler auf dem Server aufgetreten ist. + +## Abhängigkeiten mit `yield`, `HTTPException` und Hintergrundtasks + +!!! warning "Achtung" + Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren. + + Diese Details sind vor allem dann nützlich, wenn Sie eine Version von FastAPI vor 0.106.0 verwendet haben und Ressourcen aus Abhängigkeiten mit `yield` in Hintergrundtasks verwendet haben. + +Vor FastAPI 0.106.0 war das Auslösen von Exceptions nach `yield` nicht möglich, der Exit-Code in Abhängigkeiten mit `yield` wurde ausgeführt, *nachdem* die Response gesendet wurde, die [Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} wären also bereits ausgeführt worden. + +Dies wurde hauptsächlich so konzipiert, damit die gleichen Objekte, die durch Abhängigkeiten ge`yield`et werden, innerhalb von Hintergrundtasks verwendet werden können, da der Exit-Code ausgeführt wird, nachdem die Hintergrundtasks abgeschlossen sind. + +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" + + 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). + + Auf diese Weise erhalten Sie wahrscheinlich saubereren Code. + +Wenn Sie sich früher auf dieses Verhalten verlassen haben, sollten Sie jetzt die Ressourcen für Hintergrundtasks innerhalb des Hintergrundtasks selbst erstellen und intern nur Daten verwenden, die nicht von den Ressourcen von Abhängigkeiten mit `yield` abhängen. + +Anstatt beispielsweise dieselbe Datenbanksitzung zu verwenden, würden Sie eine neue Datenbanksitzung innerhalb des Hintergrundtasks erstellen und die Objekte mithilfe dieser neuen Sitzung aus der Datenbank abrufen. Und anstatt das Objekt aus der Datenbank als Parameter an die Hintergrundtask-Funktion zu übergeben, würden Sie die ID dieses Objekts übergeben und das Objekt dann innerhalb der Hintergrundtask-Funktion erneut laden. + +## Kontextmanager + +### Was sind „Kontextmanager“ + +„Kontextmanager“ (Englisch „Context Manager“) sind bestimmte Python-Objekte, die Sie in einer `with`-Anweisung verwenden können. + +Beispielsweise können Sie <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" class="external-link" target="_blank">`with` verwenden, um eine Datei auszulesen</a>: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Im Hintergrund erstellt das `open("./somefile.txt")` ein Objekt, das als „Kontextmanager“ bezeichnet wird. + +Dieser stellt sicher dass, wenn der `with`-Block beendet ist, die Datei geschlossen wird, auch wenn Exceptions geworfen wurden. + +Wenn Sie eine Abhängigkeit mit `yield` erstellen, erstellt **FastAPI** dafür intern einen Kontextmanager und kombiniert ihn mit einigen anderen zugehörigen Tools. + +### Kontextmanager in Abhängigkeiten mit `yield` verwenden + +!!! warning "Achtung" + Dies ist mehr oder weniger eine „fortgeschrittene“ Idee. + + Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen. + +In Python können Sie Kontextmanager erstellen, indem Sie <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">eine Klasse mit zwei Methoden erzeugen: `__enter__()` und `__exit__()`</a>. + +Sie können solche auch innerhalb von **FastAPI**-Abhängigkeiten mit `yield` verwenden, indem Sie `with`- oder `async with`-Anweisungen innerhalb der Abhängigkeits-Funktion verwenden: + +```Python hl_lines="1-9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip "Tipp" + Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind: + + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + + Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat. + + Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet. + + Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht). + + FastAPI erledigt das intern für Sie. From 54513de411e943fe56b8eedb812c3732a36039ae Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:10:48 +0100 Subject: [PATCH 128/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/history-design-future.md`=20(#10865)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/history-design-future.md | 79 +++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 docs/de/docs/history-design-future.md diff --git a/docs/de/docs/history-design-future.md b/docs/de/docs/history-design-future.md new file mode 100644 index 000000000..22597b1f5 --- /dev/null +++ b/docs/de/docs/history-design-future.md @@ -0,0 +1,79 @@ +# Geschichte, Design und Zukunft + +Vor einiger Zeit fragte <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">ein **FastAPI**-Benutzer</a>: + +> Was ist die Geschichte dieses Projekts? Es scheint, als wäre es in ein paar Wochen aus dem Nichts zu etwas Großartigem geworden [...] + +Hier ist ein wenig über diese Geschichte. + +## Alternativen + +Ich habe seit mehreren Jahren APIs mit komplexen Anforderungen (maschinelles Lernen, verteilte Systeme, asynchrone Jobs, NoSQL-Datenbanken, usw.) erstellt und leitete mehrere Entwicklerteams. + +Dabei musste ich viele Alternativen untersuchen, testen und nutzen. + +Die Geschichte von **FastAPI** ist zu einem großen Teil die Geschichte seiner Vorgänger. + +Wie im Abschnitt [Alternativen](alternatives.md){.internal-link target=_blank} gesagt: + +<blockquote markdown="1"> + +**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren. + +Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten. + +Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen. + +Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise). + +</blockquote> + +## Investigation + +Durch die Nutzung all dieser vorherigen Alternativen hatte ich die Möglichkeit, von allen zu lernen, Ideen aufzunehmen und sie auf die beste Weise zu kombinieren, die ich für mich und die Entwicklerteams, mit denen ich zusammengearbeitet habe, finden konnte. + +Es war beispielsweise klar, dass es idealerweise auf Standard-Python-Typhinweisen basieren sollte. + +Der beste Ansatz bestand außerdem darin, bereits bestehende Standards zu nutzen. + +Bevor ich also überhaupt angefangen habe, **FastAPI** zu schreiben, habe ich mehrere Monate damit verbracht, die Spezifikationen für OpenAPI, JSON Schema, OAuth2, usw. zu studieren und deren Beziehungen, Überschneidungen und Unterschiede zu verstehen. + +## Design + +Dann habe ich einige Zeit damit verbracht, die Entwickler-„API“ zu entwerfen, die ich als Benutzer haben wollte (als Entwickler, welcher FastAPI verwendet). + +Ich habe mehrere Ideen in den beliebtesten Python-Editoren getestet: PyCharm, VS Code, Jedi-basierte Editoren. + +Laut der letzten <a href="https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools" class="external-link" target="_blank">Python-Entwickler-Umfrage</a>, deckt das etwa 80 % der Benutzer ab. + +Das bedeutet, dass **FastAPI** speziell mit den Editoren getestet wurde, die von 80 % der Python-Entwickler verwendet werden. Und da die meisten anderen Editoren in der Regel ähnlich funktionieren, sollten alle diese Vorteile für praktisch alle Editoren funktionieren. + +Auf diese Weise konnte ich die besten Möglichkeiten finden, die Codeverdoppelung so weit wie möglich zu reduzieren, überall Autovervollständigung, Typ- und Fehlerprüfungen, usw. zu gewährleisten. + +Alles auf eine Weise, die allen Entwicklern das beste Entwicklungserlebnis bot. + +## Anforderungen + +Nachdem ich mehrere Alternativen getestet hatte, entschied ich, dass ich <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">**Pydantic**</a> wegen seiner Vorteile verwenden würde. + +Dann habe ich zu dessen Code beigetragen, um es vollständig mit JSON Schema kompatibel zu machen, und so verschiedene Möglichkeiten zum Definieren von einschränkenden Deklarationen (Constraints) zu unterstützen, und die Editorunterstützung (Typprüfungen, Codevervollständigung) zu verbessern, basierend auf den Tests in mehreren Editoren. + +Während der Entwicklung habe ich auch zu <a href="https://www.starlette.io/" class="external-link" target="_blank">**Starlette**</a> beigetragen, der anderen Schlüsselanforderung. + +## Entwicklung + +Als ich mit der Erstellung von **FastAPI** selbst begann, waren die meisten Teile bereits vorhanden, das Design definiert, die Anforderungen und Tools bereit und das Wissen über die Standards und Spezifikationen klar und frisch. + +## Zukunft + +Zu diesem Zeitpunkt ist bereits klar, dass **FastAPI** mit seinen Ideen für viele Menschen nützlich ist. + +Es wird gegenüber früheren Alternativen gewählt, da es für viele Anwendungsfälle besser geeignet ist. + +Viele Entwickler und Teams verlassen sich bei ihren Projekten bereits auf **FastAPI** (einschließlich mir und meinem Team). + +Dennoch stehen uns noch viele Verbesserungen und Funktionen bevor. + +**FastAPI** hat eine große Zukunft vor sich. + +Und [Ihre Hilfe](help-fastapi.md){.internal-link target=_blank} wird sehr geschätzt. From f0281cde21dac0854c9b090c24755a4910032ef4 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:12:23 +0000 Subject: [PATCH 129/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 63953a0c8..a79e20ad1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/async.md`. PR [#10449](https://github.com/tiangolo/fastapi/pull/10449) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/cookie-params.md`. PR [#10323](https://github.com/tiangolo/fastapi/pull/10323) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10407](https://github.com/tiangolo/fastapi/pull/10407) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/index.md`. PR [#10399](https://github.com/tiangolo/fastapi/pull/10399) by [@nilslindemann](https://github.com/nilslindemann). From ba754f90110a18d6b9734dfdd51fc7a32f77b7d2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:13:46 +0000 Subject: [PATCH 130/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a79e20ad1..6ea659abd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/versions.md`. PR [#10491](https://github.com/tiangolo/fastapi/pull/10491) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/async.md`. PR [#10449](https://github.com/tiangolo/fastapi/pull/10449) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/cookie-params.md`. PR [#10323](https://github.com/tiangolo/fastapi/pull/10323) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10407](https://github.com/tiangolo/fastapi/pull/10407) by [@nilslindemann](https://github.com/nilslindemann). From 57708b2b401ea6fa79c2524c4cb5edf222e99e29 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:14:36 +0100 Subject: [PATCH 131/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/project-generation.md`=20(#10851)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/project-generation.md | 84 ++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 docs/de/docs/project-generation.md diff --git a/docs/de/docs/project-generation.md b/docs/de/docs/project-generation.md new file mode 100644 index 000000000..c1ae6512d --- /dev/null +++ b/docs/de/docs/project-generation.md @@ -0,0 +1,84 @@ +# Projektgenerierung – Vorlage + +Sie können einen Projektgenerator für den Einstieg verwenden, welcher einen Großteil der Ersteinrichtung, Sicherheit, Datenbank und einige API-Endpunkte bereits für Sie erstellt. + +Ein Projektgenerator verfügt immer über ein sehr spezifisches Setup, das Sie aktualisieren und an Ihre eigenen Bedürfnisse anpassen sollten, aber es könnte ein guter Ausgangspunkt für Ihr Projekt sein. + +## Full Stack FastAPI PostgreSQL + +GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> + +### Full Stack FastAPI PostgreSQL – Funktionen + +* Vollständige **Docker**-Integration (Docker-basiert). +* Docker-Schwarmmodus-Deployment. +* **Docker Compose**-Integration und Optimierung für die lokale Entwicklung. +* **Produktionsbereit** Python-Webserver, verwendet Uvicorn und Gunicorn. +* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a>-Backend: + * **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (dank Starlette und Pydantic). + * **Intuitiv**: Hervorragende Editor-Unterstützung. <abbr title="Auch bekannt als automatische Vervollständigung, IntelliSense">Codevervollständigung</abbr> überall. Weniger Zeitaufwand für das Debuggen. + * **Einfach**: Einfach zu bedienen und zu erlernen. Weniger Zeit für das Lesen von Dokumentationen. + * **Kurz**: Codeverdoppelung minimieren. Mehrere Funktionalitäten aus jeder Parameterdeklaration. + * **Robust**: Erhalten Sie produktionsbereiten Code. Mit automatischer, interaktiver Dokumentation. + * **Standards-basiert**: Basierend auf (und vollständig kompatibel mit) den offenen Standards für APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> und <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>. + * <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">**Viele weitere Funktionen**</a>, einschließlich automatischer Validierung, Serialisierung, interaktiver Dokumentation, Authentifizierung mit OAuth2-JWT-Tokens, usw. +* **Sicheres Passwort**-Hashing standardmäßig. +* **JWT-Token**-Authentifizierung. +* **SQLAlchemy**-Modelle (unabhängig von Flask-Erweiterungen, sodass sie direkt mit Celery-Workern verwendet werden können). +* Grundlegende Startmodelle für Benutzer (ändern und entfernen Sie nach Bedarf). +* **Alembic**-Migrationen. +* **CORS** (Cross Origin Resource Sharing). +* **Celery**-Worker, welche Modelle und Code aus dem Rest des Backends selektiv importieren und verwenden können. +* REST-Backend-Tests basierend auf **Pytest**, integriert in Docker, sodass Sie die vollständige API-Interaktion unabhängig von der Datenbank testen können. Da es in Docker ausgeführt wird, kann jedes Mal ein neuer Datenspeicher von Grund auf erstellt werden (Sie können also ElasticSearch, MongoDB, CouchDB oder was auch immer Sie möchten verwenden und einfach testen, ob die API funktioniert). +* Einfache Python-Integration mit **Jupyter-Kerneln** für Remote- oder In-Docker-Entwicklung mit Erweiterungen wie Atom Hydrogen oder Visual Studio Code Jupyter. +* **Vue**-Frontend: + * Mit Vue CLI generiert. + * Handhabung der **JWT-Authentifizierung**. + * Login-View. + * Nach der Anmeldung Hauptansicht des Dashboards. + * Haupt-Dashboard mit Benutzererstellung und -bearbeitung. + * Bearbeitung des eigenen Benutzers. + * **Vuex**. + * **Vue-Router**. + * **Vuetify** für schöne Material-Designkomponenten. + * **TypeScript**. + * Docker-Server basierend auf **Nginx** (konfiguriert, um gut mit Vue-Router zu funktionieren). + * Mehrstufigen Docker-Erstellung, sodass Sie kompilierten Code nicht speichern oder committen müssen. + * Frontend-Tests, welche zur Erstellungszeit ausgeführt werden (können auch deaktiviert werden). + * So modular wie möglich gestaltet, sodass es sofort einsatzbereit ist. Sie können es aber mit Vue CLI neu generieren oder es so wie Sie möchten erstellen und wiederverwenden, was Sie möchten. +* **PGAdmin** für die PostgreSQL-Datenbank, können Sie problemlos ändern, sodass PHPMyAdmin und MySQL verwendet wird. +* **Flower** für die Überwachung von Celery-Jobs. +* Load Balancing zwischen Frontend und Backend mit **Traefik**, sodass Sie beide unter derselben Domain haben können, getrennt durch den Pfad, aber von unterschiedlichen Containern ausgeliefert. +* Traefik-Integration, einschließlich automatischer Generierung von Let's Encrypt-**HTTPS**-Zertifikaten. +* GitLab **CI** (kontinuierliche Integration), einschließlich Frontend- und Backend-Testen. + +## Full Stack FastAPI Couchbase + +GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a> + +⚠️ **WARNUNG** ⚠️ + +Wenn Sie ein neues Projekt von Grund auf starten, prüfen Sie die Alternativen hier. + +Zum Beispiel könnte der Projektgenerator <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">Full Stack FastAPI PostgreSQL</a> eine bessere Alternative sein, da er aktiv gepflegt und genutzt wird. Und er enthält alle neuen Funktionen und Verbesserungen. + +Es steht Ihnen weiterhin frei, den Couchbase-basierten Generator zu verwenden, wenn Sie möchten. Er sollte wahrscheinlich immer noch gut funktionieren, und wenn Sie bereits ein Projekt damit erstellt haben, ist das auch in Ordnung (und Sie haben es wahrscheinlich bereits an Ihre Bedürfnisse angepasst). + +Weitere Informationen hierzu finden Sie in der Dokumentation des Repos. + +## Full Stack FastAPI MongoDB + +... könnte später kommen, abhängig von meiner verfügbaren Zeit und anderen Faktoren. 😅 🎉 + +## Modelle für maschinelles Lernen mit spaCy und FastAPI + +GitHub: <a href="https://github.com/microsoft/cookiecutter-spacy-fastapi" class="external-link" target="_blank">https://github.com/microsoft/cookiecutter-spacy-fastapi</a> + +### Modelle für maschinelles Lernen mit spaCy und FastAPI – Funktionen + +* **spaCy** NER-Modellintegration. +* **Azure Cognitive Search**-Anforderungsformat integriert. +* **Produktionsbereit** Python-Webserver, verwendet Uvicorn und Gunicorn. +* **Azure DevOps** Kubernetes (AKS) CI/CD-Deployment integriert. +* **Mehrsprachig** Wählen Sie bei der Projekteinrichtung ganz einfach eine der integrierten Sprachen von spaCy aus. +* **Einfach erweiterbar** auf andere Modellframeworks (Pytorch, Tensorflow), nicht nur auf SpaCy. From fbf3af6a1ac55a2d53349da0b94a1b6f4fb87610 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:14:49 +0100 Subject: [PATCH 132/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/testclient.md`=20(#10843)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/testclient.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/de/docs/reference/testclient.md diff --git a/docs/de/docs/reference/testclient.md b/docs/de/docs/reference/testclient.md new file mode 100644 index 000000000..5bc089c05 --- /dev/null +++ b/docs/de/docs/reference/testclient.md @@ -0,0 +1,13 @@ +# Testclient – `TestClient` + +Sie können die `TestClient`-Klasse verwenden, um FastAPI-Anwendungen zu testen, ohne eine tatsächliche HTTP- und Socket-Verbindung zu erstellen, Sie kommunizieren einfach direkt mit dem FastAPI-Code. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Testen](../tutorial/testing.md). + +Sie können sie direkt von `fastapi.testclient` importieren: + +```python +from fastapi.testclient import TestClient +``` + +::: fastapi.testclient.TestClient From 26db167121237685a6efb1f339c9c0cb140492ab Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:14:58 +0100 Subject: [PATCH 133/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/staticfiles.md`=20(#10841)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/staticfiles.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/de/docs/reference/staticfiles.md diff --git a/docs/de/docs/reference/staticfiles.md b/docs/de/docs/reference/staticfiles.md new file mode 100644 index 000000000..5629854c6 --- /dev/null +++ b/docs/de/docs/reference/staticfiles.md @@ -0,0 +1,13 @@ +# Statische Dateien – `StaticFiles` + +Sie können die `StaticFiles`-Klasse verwenden, um statische Dateien wie JavaScript, CSS, Bilder, usw. bereitzustellen. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu statischen Dateien](../tutorial/static-files.md). + +Sie können sie direkt von `fastapi.staticfiles` importieren: + +```python +from fastapi.staticfiles import StaticFiles +``` + +::: fastapi.staticfiles.StaticFiles From 8238c6738fe3f64dfd95c99c199d124a9da4e18d Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:15:05 +0100 Subject: [PATCH 134/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/security/index.md`=20(#10839?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/security/index.md | 73 ++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 docs/de/docs/reference/security/index.md diff --git a/docs/de/docs/reference/security/index.md b/docs/de/docs/reference/security/index.md new file mode 100644 index 000000000..4c2375f2f --- /dev/null +++ b/docs/de/docs/reference/security/index.md @@ -0,0 +1,73 @@ +# Sicherheitstools + +Wenn Sie Abhängigkeiten mit OAuth2-Scopes deklarieren müssen, verwenden Sie `Security()`. + +Aber Sie müssen immer noch definieren, was das <abbr title="Das von dem abhängt, die zu verwendende Abhängigkeit">Dependable</abbr>, das Callable ist, welches Sie als Parameter an `Depends()` oder `Security()` übergeben. + +Es gibt mehrere Tools, mit denen Sie diese Dependables erstellen können, und sie werden in OpenAPI integriert, sodass sie in der Oberfläche der automatischen Dokumentation angezeigt werden und von automatisch generierten Clients und SDKs, usw., verwendet werden können. + +Sie können sie von `fastapi.security` importieren: + +```python +from fastapi.security import ( + APIKeyCookie, + APIKeyHeader, + APIKeyQuery, + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, + HTTPDigest, + OAuth2, + OAuth2AuthorizationCodeBearer, + OAuth2PasswordBearer, + OAuth2PasswordRequestForm, + OAuth2PasswordRequestFormStrict, + OpenIdConnect, + SecurityScopes, +) +``` + +## API-Schlüssel-Sicherheitsschemas + +::: fastapi.security.APIKeyCookie + +::: fastapi.security.APIKeyHeader + +::: fastapi.security.APIKeyQuery + +## HTTP-Authentifizierungsschemas + +::: fastapi.security.HTTPBasic + +::: fastapi.security.HTTPBearer + +::: fastapi.security.HTTPDigest + +## HTTP-Anmeldeinformationen + +::: fastapi.security.HTTPAuthorizationCredentials + +::: fastapi.security.HTTPBasicCredentials + +## OAuth2-Authentifizierung + +::: fastapi.security.OAuth2 + +::: fastapi.security.OAuth2AuthorizationCodeBearer + +::: fastapi.security.OAuth2PasswordBearer + +## OAuth2-Passwortformulare + +::: fastapi.security.OAuth2PasswordRequestForm + +::: fastapi.security.OAuth2PasswordRequestFormStrict + +## OAuth2-Sicherheitsscopes in Abhängigkeiten + +::: fastapi.security.SecurityScopes + +## OpenID Connect + +::: fastapi.security.OpenIdConnect From da193665ee6ed51543e7a898437e0ea59bca3060 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:15:17 +0100 Subject: [PATCH 135/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/openapi/*.md`=20(#10838)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/openapi/docs.md | 11 +++++++++++ docs/de/docs/reference/openapi/index.md | 5 +++++ docs/de/docs/reference/openapi/models.md | 5 +++++ 3 files changed, 21 insertions(+) create mode 100644 docs/de/docs/reference/openapi/docs.md create mode 100644 docs/de/docs/reference/openapi/index.md create mode 100644 docs/de/docs/reference/openapi/models.md diff --git a/docs/de/docs/reference/openapi/docs.md b/docs/de/docs/reference/openapi/docs.md new file mode 100644 index 000000000..3c19ba917 --- /dev/null +++ b/docs/de/docs/reference/openapi/docs.md @@ -0,0 +1,11 @@ +# OpenAPI `docs` + +Werkzeuge zur Verwaltung der automatischen OpenAPI-UI-Dokumentation, einschließlich Swagger UI (standardmäßig unter `/docs`) und ReDoc (standardmäßig unter `/redoc`). + +::: fastapi.openapi.docs.get_swagger_ui_html + +::: fastapi.openapi.docs.get_redoc_html + +::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html + +::: fastapi.openapi.docs.swagger_ui_default_parameters diff --git a/docs/de/docs/reference/openapi/index.md b/docs/de/docs/reference/openapi/index.md new file mode 100644 index 000000000..0ae3d67c6 --- /dev/null +++ b/docs/de/docs/reference/openapi/index.md @@ -0,0 +1,5 @@ +# OpenAPI + +Es gibt mehrere Werkzeuge zur Handhabung von OpenAPI. + +Normalerweise müssen Sie diese nicht verwenden, es sei denn, Sie haben einen bestimmten fortgeschrittenen Anwendungsfall, welcher das erfordert. diff --git a/docs/de/docs/reference/openapi/models.md b/docs/de/docs/reference/openapi/models.md new file mode 100644 index 000000000..64306b15f --- /dev/null +++ b/docs/de/docs/reference/openapi/models.md @@ -0,0 +1,5 @@ +# OpenAPI-`models` + +OpenAPI Pydantic-Modelle, werden zum Generieren und Validieren der generierten OpenAPI verwendet. + +::: fastapi.openapi.models From cebb68d6047ae70d1bd1c7a1560f6a7aa3173f4f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:15:29 +0000 Subject: [PATCH 136/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6ea659abd..4eb14f0e5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/request-forms.md`. PR [#10361](https://github.com/tiangolo/fastapi/pull/10361) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/versions.md`. PR [#10491](https://github.com/tiangolo/fastapi/pull/10491) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/async.md`. PR [#10449](https://github.com/tiangolo/fastapi/pull/10449) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/cookie-params.md`. PR [#10323](https://github.com/tiangolo/fastapi/pull/10323) by [@nilslindemann](https://github.com/nilslindemann). From 40ace5dc60eb2d80d84741d9c66a3000eb8e1e18 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:15:39 +0100 Subject: [PATCH 137/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/middleware.md`=20(#10837)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/middleware.md | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 docs/de/docs/reference/middleware.md diff --git a/docs/de/docs/reference/middleware.md b/docs/de/docs/reference/middleware.md new file mode 100644 index 000000000..d8d2d50fc --- /dev/null +++ b/docs/de/docs/reference/middleware.md @@ -0,0 +1,45 @@ +# Middleware + +Es gibt mehrere Middlewares, die direkt von Starlette bereitgestellt werden. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Middleware](../advanced/middleware.md). + +::: fastapi.middleware.cors.CORSMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.cors import CORSMiddleware +``` + +::: fastapi.middleware.gzip.GZipMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.gzip import GZipMiddleware +``` + +::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware +``` + +::: fastapi.middleware.trustedhost.TrustedHostMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.trustedhost import TrustedHostMiddleware +``` + +::: fastapi.middleware.wsgi.WSGIMiddleware + +Kann von `fastapi` importiert werden: + +```python +from fastapi.middleware.wsgi import WSGIMiddleware +``` From 2a9aa8d70defbf06b4a4be11196a83817d223cdf Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:16:03 +0100 Subject: [PATCH 138/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/response.md`=20(#10824)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/response.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/de/docs/reference/response.md diff --git a/docs/de/docs/reference/response.md b/docs/de/docs/reference/response.md new file mode 100644 index 000000000..215918931 --- /dev/null +++ b/docs/de/docs/reference/response.md @@ -0,0 +1,13 @@ +# `Response`-Klasse + +Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als `Response` deklarieren und dann Daten für die Response wie Header oder Cookies festlegen. + +Diese können Sie auch direkt verwenden, um eine Instanz davon zu erstellen und diese von Ihren *Pfadoperationen* zurückzugeben. + +Sie können sie direkt von `fastapi` importieren: + +```python +from fastapi import Response +``` + +::: fastapi.Response From 8a01c8dbd0a93c2cebb8c523f8e6163a0ca6252d Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:16:16 +0100 Subject: [PATCH 139/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/httpconnection.md`=20(#10823?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/httpconnection.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 docs/de/docs/reference/httpconnection.md diff --git a/docs/de/docs/reference/httpconnection.md b/docs/de/docs/reference/httpconnection.md new file mode 100644 index 000000000..32a9696fa --- /dev/null +++ b/docs/de/docs/reference/httpconnection.md @@ -0,0 +1,11 @@ +# `HTTPConnection`-Klasse + +Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +Sie können diese von `fastapi.requests` importieren: + +```python +from fastapi.requests import HTTPConnection +``` + +::: fastapi.requests.HTTPConnection From 30912da5e543df6e313c4a1624d7e0568cac2070 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:16:27 +0100 Subject: [PATCH 140/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/websockets.md`=20(#10822)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/websockets.md | 64 ++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 docs/de/docs/reference/websockets.md diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md new file mode 100644 index 000000000..35657172c --- /dev/null +++ b/docs/de/docs/reference/websockets.md @@ -0,0 +1,64 @@ +# WebSockets + +Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter vom Typ `WebSocket` und können damit Daten vom Client lesen und an ihn senden. Er wird direkt von Starlette bereitgestellt, Sie können ihn aber von `fastapi` importieren: + +```python +from fastapi import WebSocket +``` + +!!! tip "Tipp" + Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +::: fastapi.WebSocket + options: + members: + - scope + - app + - url + - base_url + - headers + - query_params + - path_params + - cookies + - client + - state + - url_for + - client_state + - application_state + - receive + - send + - accept + - receive_text + - receive_bytes + - receive_json + - iter_text + - iter_bytes + - iter_json + - send_text + - send_bytes + - send_json + - close + +Wenn ein Client die Verbindung trennt, wird eine `WebSocketDisconnect`-Exception ausgelöst, die Sie abfangen können. + +Sie können diese direkt von `fastapi` importieren: + +```python +from fastapi import WebSocketDisconnect +``` + +::: fastapi.WebSocketDisconnect + +## WebSockets – zusätzliche Klassen + +Zusätzliche Klassen für die Handhabung von WebSockets. + +Werden direkt von Starlette bereitgestellt, Sie können sie jedoch von `fastapi` importieren: + +```python +from fastapi.websockets import WebSocketDisconnect, WebSocketState +``` + +::: fastapi.websockets.WebSocketDisconnect + +::: fastapi.websockets.WebSocketState From e2e1c2de9c26aa414b15193231096f4b1911cbe1 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:16:35 +0100 Subject: [PATCH 141/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/apirouter.md`=20(#10819)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/apirouter.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 docs/de/docs/reference/apirouter.md diff --git a/docs/de/docs/reference/apirouter.md b/docs/de/docs/reference/apirouter.md new file mode 100644 index 000000000..b0728b7df --- /dev/null +++ b/docs/de/docs/reference/apirouter.md @@ -0,0 +1,24 @@ +# `APIRouter`-Klasse + +Hier sind die Referenzinformationen für die Klasse `APIRouter` mit all ihren Parametern, Attributen und Methoden. + +Sie können die `APIRouter`-Klasse direkt von `fastapi` importieren: + +```python +from fastapi import APIRouter +``` + +::: fastapi.APIRouter + options: + members: + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event From 6c9f5a3e2de072f54285736d920ec21e843da664 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:16:45 +0100 Subject: [PATCH 142/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/dependencies.md`=20(#10818)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/dependencies.md | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 docs/de/docs/reference/dependencies.md diff --git a/docs/de/docs/reference/dependencies.md b/docs/de/docs/reference/dependencies.md new file mode 100644 index 000000000..2ed5b5050 --- /dev/null +++ b/docs/de/docs/reference/dependencies.md @@ -0,0 +1,29 @@ +# Abhängigkeiten – `Depends()` und `Security()` + +## `Depends()` + +Abhängigkeiten werden hauptsächlich mit der speziellen Funktion `Depends()` behandelt, die ein Callable entgegennimmt. + +Hier finden Sie deren Referenz und Parameter. + +Sie können sie direkt von `fastapi` importieren: + +```python +from fastapi import Depends +``` + +::: fastapi.Depends + +## `Security()` + +In vielen Szenarien können Sie die Sicherheit (Autorisierung, Authentifizierung usw.) mit Abhängigkeiten handhaben, indem Sie `Depends()` verwenden. + +Wenn Sie jedoch auch OAuth2-Scopes deklarieren möchten, können Sie `Security()` anstelle von `Depends()` verwenden. + +Sie können `Security()` direkt von `fastapi` importieren: + +```python +from fastapi import Security +``` + +::: fastapi.Security From 769d737682ab73423c040c012c4e1a334c86c35e Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:16:53 +0100 Subject: [PATCH 143/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/exceptions.md`=20(#10817)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/exceptions.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 docs/de/docs/reference/exceptions.md diff --git a/docs/de/docs/reference/exceptions.md b/docs/de/docs/reference/exceptions.md new file mode 100644 index 000000000..230f902a9 --- /dev/null +++ b/docs/de/docs/reference/exceptions.md @@ -0,0 +1,20 @@ +# Exceptions – `HTTPException` und `WebSocketException` + +Dies sind die <abbr title="Exception – Ausnahme, Fehler: Python-Objekt, das einen Fehler nebst Metadaten repräsentiert">Exceptions</abbr>, die Sie auslösen können, um dem Client Fehler zu berichten. + +Wenn Sie eine Exception auslösen, wird, wie es bei normalem Python der Fall wäre, der Rest der Ausführung abgebrochen. Auf diese Weise können Sie diese Exceptions von überall im Code werfen, um einen Request abzubrechen und den Fehler dem Client anzuzeigen. + +Sie können Folgendes verwenden: + +* `HTTPException` +* `WebSocketException` + +Diese Exceptions können direkt von `fastapi` importiert werden: + +```python +from fastapi import HTTPException, WebSocketException +``` + +::: fastapi.HTTPException + +::: fastapi.WebSocketException From ccd189bfd4e830120a75066b96a2948fb9276938 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:16:58 +0000 Subject: [PATCH 144/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4eb14f0e5..0db237e43 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/encoder.md`. PR [#10385](https://github.com/tiangolo/fastapi/pull/10385) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-forms.md`. PR [#10361](https://github.com/tiangolo/fastapi/pull/10361) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/versions.md`. PR [#10491](https://github.com/tiangolo/fastapi/pull/10491) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/async.md`. PR [#10449](https://github.com/tiangolo/fastapi/pull/10449) by [@nilslindemann](https://github.com/nilslindemann). From 2033aacd962dd041336f43a51cf8c7c856c32563 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:17:09 +0100 Subject: [PATCH 145/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/uploadfile.md`=20(#10816)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/uploadfile.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 docs/de/docs/reference/uploadfile.md diff --git a/docs/de/docs/reference/uploadfile.md b/docs/de/docs/reference/uploadfile.md new file mode 100644 index 000000000..8556edf82 --- /dev/null +++ b/docs/de/docs/reference/uploadfile.md @@ -0,0 +1,22 @@ +# `UploadFile`-Klasse + +Sie können *Pfadoperation-Funktionsparameter* als Parameter vom Typ `UploadFile` definieren, um Dateien aus dem Request zu erhalten. + +Sie können es direkt von `fastapi` importieren: + +```python +from fastapi import UploadFile +``` + +::: fastapi.UploadFile + options: + members: + - file + - filename + - size + - headers + - content_type + - read + - write + - seek + - close From 38ac7445ef3f7c54d1764846acbf5798512e75c5 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:17:17 +0100 Subject: [PATCH 146/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/status.md`=20(#10815)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/status.md | 36 ++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 docs/de/docs/reference/status.md diff --git a/docs/de/docs/reference/status.md b/docs/de/docs/reference/status.md new file mode 100644 index 000000000..1d9458ee9 --- /dev/null +++ b/docs/de/docs/reference/status.md @@ -0,0 +1,36 @@ +# Statuscodes + +Sie können das Modul `status` von `fastapi` importieren: + +```python +from fastapi import status +``` + +`status` wird direkt von Starlette bereitgestellt. + +Es enthält eine Gruppe benannter Konstanten (Variablen) mit ganzzahligen Statuscodes. + +Zum Beispiel: + +* 200: `status.HTTP_200_OK` +* 403: `status.HTTP_403_FORBIDDEN` +* usw. + +Es kann praktisch sein, schnell auf HTTP- (und WebSocket-)Statuscodes in Ihrer Anwendung zuzugreifen, indem Sie die automatische Vervollständigung für den Namen verwenden, ohne sich die Zahlen für die Statuscodes merken zu müssen. + +Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Response-Statuscodes](../tutorial/response-status-code.md). + +## Beispiel + +```python +from fastapi import FastAPI, status + +app = FastAPI() + + +@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT) +def read_items(): + return [{"name": "Plumbus"}, {"name": "Portal Gun"}] +``` + +::: fastapi.status From cd54748cea1b18a06ae94c81b5e9d6165898b794 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:17:26 +0100 Subject: [PATCH 147/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/reference/parameters.md`=20(#10814)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/reference/parameters.md | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/de/docs/reference/parameters.md diff --git a/docs/de/docs/reference/parameters.md b/docs/de/docs/reference/parameters.md new file mode 100644 index 000000000..2638eaf48 --- /dev/null +++ b/docs/de/docs/reference/parameters.md @@ -0,0 +1,35 @@ +# Request-Parameter + +Hier die Referenzinformationen für die Request-Parameter. + +Dies sind die Sonderfunktionen, die Sie mittels `Annotated` in *Pfadoperation-Funktion*-Parameter oder Abhängigkeitsfunktionen einfügen können, um Daten aus dem Request abzurufen. + +Dies beinhaltet: + +* `Query()` +* `Path()` +* `Body()` +* `Cookie()` +* `Header()` +* `Form()` +* `File()` + +Sie können diese alle direkt von `fastapi` importieren: + +```python +from fastapi import Body, Cookie, File, Form, Header, Path, Query +``` + +::: fastapi.Query + +::: fastapi.Path + +::: fastapi.Body + +::: fastapi.Cookie + +::: fastapi.Header + +::: fastapi.Form + +::: fastapi.File From 871a23427fb4d226a7941382b9caa8cd92f693ae Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:17:36 +0100 Subject: [PATCH 148/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/custom-docs-ui-assets.md`=20(#1?= =?UTF-8?q?0803)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/custom-docs-ui-assets.md | 199 +++++++++++++++++++ 1 file changed, 199 insertions(+) create mode 100644 docs/de/docs/how-to/custom-docs-ui-assets.md diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 000000000..991eaf269 --- /dev/null +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,199 @@ +# Statische Assets der Dokumentationsoberfläche (selbst hosten) + +Die API-Dokumentation verwendet **Swagger UI** und **ReDoc**, und jede dieser Dokumentationen benötigt einige JavaScript- und CSS-Dateien. + +Standardmäßig werden diese Dateien von einem <abbr title="Content Delivery Network – Inhalte-Auslieferungs-Netzwerk: Ein Dienst, der normalerweise aus mehreren Servern besteht und statische Dateien wie JavaScript und CSS bereitstellt. Er wird normalerweise verwendet, um diese Dateien von einem Server bereitzustellen, der näher am Client liegt, wodurch die Leistung verbessert wird.">CDN</abbr> bereitgestellt. + +Es ist jedoch möglich, das anzupassen, ein bestimmtes CDN festzulegen oder die Dateien selbst bereitzustellen. + +## Benutzerdefiniertes CDN für JavaScript und CSS + +Nehmen wir an, Sie möchten ein anderes <abbr title="Content Delivery Network">CDN</abbr> verwenden, zum Beispiel möchten Sie `https://unpkg.com/` verwenden. + +Das kann nützlich sein, wenn Sie beispielsweise in einem Land leben, in dem bestimmte URLs eingeschränkt sind. + +### Die automatischen Dokumentationen deaktivieren + +Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivieren, da diese standardmäßig das Standard-CDN verwenden. + +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!} +``` + +### Die benutzerdefinierten Dokumentationen hinzufügen + +Jetzt können Sie die *Pfadoperationen* für die benutzerdefinierten Dokumentationen erstellen. + +Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentation zu erstellen und ihnen die erforderlichen Argumente zu übergeben: + +* `openapi_url`: die URL, unter welcher die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden. +* `title`: der Titel Ihrer API. +* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden. +* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL. +* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL. + +Und genau so für ReDoc ... + +```Python hl_lines="2-6 11-19 22-24 27-33" +{!../../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +!!! tip "Tipp" + Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + + Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + + Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +### Eine *Pfadoperation* erstellen, um es zu testen + +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!} +``` + +### Es ausprobieren + +Jetzt sollten Sie in der Lage sein, zu Ihrer Dokumentation auf <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> zu gehen und die Seite neu zuladen, die Assets werden nun vom neuen CDN geladen. + +## JavaScript und CSS für die Dokumentation selbst hosten + +Das Selbst Hosten von JavaScript und CSS kann nützlich sein, wenn Sie beispielsweise möchten, dass Ihre Anwendung auch offline, ohne bestehenden Internetzugang oder in einem lokalen Netzwerk weiter funktioniert. + +Hier erfahren Sie, wie Sie diese Dateien selbst in derselben FastAPI-App bereitstellen und die Dokumentation für deren Verwendung konfigurieren. + +### Projektdateistruktur + +Nehmen wir an, die Dateistruktur Ihres Projekts sieht folgendermaßen aus: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Erstellen Sie jetzt ein Verzeichnis zum Speichern dieser statischen Dateien. + +Ihre neue Dateistruktur könnte so aussehen: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +└── static/ +``` + +### Die Dateien herunterladen + +Laden Sie die für die Dokumentation benötigten statischen Dateien herunter und legen Sie diese im Verzeichnis `static/` ab. + +Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und eine Option wie etwa `Link speichern unter...` auswählen. + +**Swagger UI** verwendet folgende Dateien: + +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a> +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a> + +Und **ReDoc** verwendet diese Datei: + +* <a href="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js" class="external-link" target="_blank">`redoc.standalone.js`</a> + +Danach könnte Ihre Dateistruktur wie folgt aussehen: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Die statischen Dateien bereitstellen + +* Importieren Sie `StaticFiles`. +* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. + +```Python hl_lines="7 11" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Die statischen Dateien testen + +Starten Sie Ihre Anwendung und gehen Sie auf <a href="http://127.0.0.1:8000/static/redoc.standalone.js" class="external-link" target="_blank">http://127.0.0.1:8000/static/redoc.standalone.js</a>. + +Sie sollten eine sehr lange JavaScript-Datei für **ReDoc** sehen. + +Sie könnte beginnen mit etwas wie: + +```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 + +... +``` + +Das zeigt, dass Sie statische Dateien aus Ihrer Anwendung bereitstellen können und dass Sie die statischen Dateien für die Dokumentation an der richtigen Stelle platziert haben. + +Jetzt können wir die Anwendung so konfigurieren, dass sie diese statischen Dateien für die Dokumentation verwendet. + +### Die automatischen Dokumentationen deaktivieren, für statische Dateien + +Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt darin, die automatischen Dokumentationen zu deaktivieren, da diese standardmäßig das CDN verwenden. + +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!} +``` + +### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen + +Und genau wie bei einem benutzerdefinierten CDN können Sie jetzt die *Pfadoperationen* für die benutzerdefinierten Dokumentationen erstellen. + +Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentationen zu erstellen, und diesen die erforderlichen Argumente übergeben: + +* `openapi_url`: die URL, unter der die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden. +* `title`: der Titel Ihrer API. +* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden. +* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**. +* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**. + +Und genau so für ReDoc ... + +```Python hl_lines="2-6 14-22 25-27 30-36" +{!../../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +!!! tip "Tipp" + Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + + Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + + Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +### Eine *Pfadoperation* erstellen, um statische Dateien zu testen + +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!} +``` + +### Benutzeroberfläche, mit statischen Dateien, testen + +Jetzt sollten Sie in der Lage sein, Ihr WLAN zu trennen, gehen Sie zu Ihrer Dokumentation unter <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> und laden Sie die Seite neu. + +Und selbst ohne Internet könnten Sie die Dokumentation für Ihre API sehen und damit interagieren. From eaa472bcee422cb10afe05b42b15e30c466a3c0f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:17:42 +0000 Subject: [PATCH 149/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0db237e43..2705bc208 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/request-forms-and-files.md`. PR [#10368](https://github.com/tiangolo/fastapi/pull/10368) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/encoder.md`. PR [#10385](https://github.com/tiangolo/fastapi/pull/10385) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-forms.md`. PR [#10361](https://github.com/tiangolo/fastapi/pull/10361) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/versions.md`. PR [#10491](https://github.com/tiangolo/fastapi/pull/10491) by [@nilslindemann](https://github.com/nilslindemann). From 33329ecb02384b45e0cf22e50b7cc624865b7afb Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:17:49 +0100 Subject: [PATCH 150/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/configure-swagger-ui.md`=20(#10?= =?UTF-8?q?804)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/configure-swagger-ui.md | 78 +++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/de/docs/how-to/configure-swagger-ui.md diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..c18091efd --- /dev/null +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# Swagger-Oberfläche konfigurieren + +Sie können einige zusätzliche <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">Parameter der Swagger-Oberfläche</a> konfigurieren. + +Um diese zu konfigurieren, übergeben Sie das Argument `swagger_ui_parameters` beim Erstellen des `FastAPI()`-App-Objekts oder an die Funktion `get_swagger_ui_html()`. + +`swagger_ui_parameters` empfängt ein Dict mit den Konfigurationen, die direkt an die Swagger-Oberfläche übergeben werden. + +FastAPI konvertiert die Konfigurationen nach **JSON**, um diese mit JavaScript kompatibel zu machen, da die Swagger-Oberfläche das benötigt. + +## Syntaxhervorhebung deaktivieren + +Sie könnten beispielsweise die Syntaxhervorhebung in der Swagger-Oberfläche deaktivieren. + +Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig aktiviert: + +<img src="/img/tutorial/extending-openapi/image02.png"> + +Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: + +<img src="/img/tutorial/extending-openapi/image03.png"> + +## Das Theme ändern + +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!} +``` + +Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: + +<img src="/img/tutorial/extending-openapi/image04.png"> + +## Defaultparameter der Swagger-Oberfläche ändern + +FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anwendungsfälle geeignet sind. + +Es umfasst die folgenden Defaultkonfigurationen: + +```Python +{!../../../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!} +``` + +## Andere Parameter der Swagger-Oberfläche + +Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">Dokumentation für die Parameter der Swagger-Oberfläche</a>. + +## JavaScript-basierte Einstellungen + +Die Swagger-Oberfläche erlaubt, dass andere Konfigurationen auch **JavaScript**-Objekte sein können (z. B. JavaScript-Funktionen). + +FastAPI umfasst auch diese Nur-JavaScript-`presets`-Einstellungen: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +Dabei handelt es sich um **JavaScript**-Objekte, nicht um Strings, daher können Sie diese nicht direkt vom Python-Code aus übergeben. + +Wenn Sie solche JavaScript-Konfigurationen verwenden müssen, können Sie einen der früher genannten Wege verwenden. Überschreiben Sie alle *Pfadoperationen* der Swagger-Oberfläche und schreiben Sie manuell jedes benötigte JavaScript. From cab028842ff60a4fda85f18b685e996874387cae Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:18:03 +0100 Subject: [PATCH 151/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/separate-openapi-schemas.md`=20?= =?UTF-8?q?(#10796)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/how-to/separate-openapi-schemas.md | 231 ++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 docs/de/docs/how-to/separate-openapi-schemas.md diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 000000000..000bcf633 --- /dev/null +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,231 @@ +# Separate OpenAPI-Schemas für Eingabe und Ausgabe oder nicht + +Bei Verwendung von **Pydantic v2** ist die generierte OpenAPI etwas genauer und **korrekter** als zuvor. 😎 + +Tatsächlich gibt es in einigen Fällen sogar **zwei JSON-Schemas** in OpenAPI für dasselbe Pydantic-Modell für Eingabe und Ausgabe, je nachdem, ob sie **Defaultwerte** haben. + +Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können. + +## Pydantic-Modelle für Eingabe und Ausgabe + +Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} + + # Code unterhalb weggelassen 👇 + ``` + + <details> + <summary>👀 Vollständige Dateivorschau</summary> + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + + </details> + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} + + # Code unterhalb weggelassen 👇 + ``` + + <details> + <summary>👀 Vollständige Dateivorschau</summary> + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + + </details> + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} + + # Code unterhalb weggelassen 👇 + ``` + + <details> + <summary>👀 Vollständige Dateivorschau</summary> + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + + </details> + +### Modell für Eingabe + +Wenn Sie dieses Modell wie hier als Eingabe verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="14" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} + + # Code unterhalb weggelassen 👇 + ``` + + <details> + <summary>👀 Vollständige Dateivorschau</summary> + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + + </details> + +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} + + # Code unterhalb weggelassen 👇 + ``` + + <details> + <summary>👀 Vollständige Dateivorschau</summary> + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + + </details> + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} + + # Code unterhalb weggelassen 👇 + ``` + + <details> + <summary>👀 Vollständige Dateivorschau</summary> + + ```Python + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + + </details> + +... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. + +### Eingabemodell in der Dokumentation + +Sie können überprüfen, dass das Feld `description` in der Dokumentation kein **rotes Sternchen** enthält, es ist nicht als erforderlich markiert: + +<div class="screenshot"> +<img src="/img/tutorial/separate-openapi-schemas/image01.png"> +</div> + +### Modell für die Ausgabe + +Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="21" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} + ``` + +... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. + +### Modell für Ausgabe-Responsedaten + +Wenn Sie mit der Dokumentation interagieren und die Response überprüfen, enthält die JSON-Response den Defaultwert (`null`), obwohl der Code nichts in eines der `description`-Felder geschrieben hat: + +<div class="screenshot"> +<img src="/img/tutorial/separate-openapi-schemas/image02.png"> +</div> + +Das bedeutet, dass es **immer einen Wert** hat, der Wert kann jedoch manchmal `None` sein (oder `null` in JSON). + +Das bedeutet, dass Clients, die Ihre API verwenden, nicht prüfen müssen, ob der Wert vorhanden ist oder nicht. Sie können davon ausgehen, dass das Feld immer vorhanden ist. In einigen Fällen hat es jedoch nur den Defaultwert `None`. + +Um dies in OpenAPI zu kennzeichnen, markieren Sie dieses Feld als **erforderlich**, da es immer vorhanden sein wird. + +Aus diesem Grund kann das JSON-Schema für ein Modell unterschiedlich sein, je nachdem, ob es für **Eingabe oder Ausgabe** verwendet wird: + +* für die **Eingabe** ist `description` **nicht erforderlich** +* für die **Ausgabe** ist es **erforderlich** (und möglicherweise `None` oder, in JSON-Begriffen, `null`) + +### Ausgabemodell in der Dokumentation + +Sie können das Ausgabemodell auch in der Dokumentation überprüfen. **Sowohl** `name` **als auch** `description` sind mit einem **roten Sternchen** als **erforderlich** markiert: + +<div class="screenshot"> +<img src="/img/tutorial/separate-openapi-schemas/image03.png"> +</div> + +### Eingabe- und Ausgabemodell in der Dokumentation + +Und wenn Sie alle verfügbaren Schemas (JSON-Schemas) in OpenAPI überprüfen, werden Sie feststellen, dass es zwei gibt, ein `Item-Input` und ein `Item-Output`. + +Für `Item-Input` ist `description` **nicht erforderlich**, es hat kein rotes Sternchen. + +Aber für `Item-Output` ist `description` **erforderlich**, es hat ein rotes Sternchen. + +<div class="screenshot"> +<img src="/img/tutorial/separate-openapi-schemas/image04.png"> +</div> + +Mit dieser Funktion von **Pydantic v2** ist Ihre API-Dokumentation **präziser**, und wenn Sie über automatisch generierte Clients und SDKs verfügen, sind diese auch präziser, mit einer besseren **Entwicklererfahrung** und Konsistenz. 🎉 + +## Schemas nicht trennen + +Nun gibt es einige Fälle, in denen Sie möglicherweise **dasselbe Schema für Eingabe und Ausgabe** haben möchten. + +Der Hauptanwendungsfall hierfür besteht wahrscheinlich darin, dass Sie das mal tun möchten, wenn Sie bereits über einige automatisch generierte Client-Codes/SDKs verfügen und im Moment nicht alle automatisch generierten Client-Codes/SDKs aktualisieren möchten, möglicherweise später, aber nicht jetzt. + +In diesem Fall können Sie diese Funktion in **FastAPI** mit dem Parameter `separate_input_output_schemas=False` deaktivieren. + +!!! info + Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} + ``` + +### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation + +Und jetzt wird es ein einziges Schema für die Eingabe und Ausgabe des Modells geben, nur `Item`, und es wird `description` als **nicht erforderlich** kennzeichnen: + +<div class="screenshot"> +<img src="/img/tutorial/separate-openapi-schemas/image05.png"> +</div> + +Dies ist das gleiche Verhalten wie in Pydantic v1. 🤓 From 0c96372b9f1954dab450dd1379c4c7e315507cb1 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:18:13 +0100 Subject: [PATCH 152/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/conditional-openapi.md`=20(#107?= =?UTF-8?q?90)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/conditional-openapi.md | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/de/docs/how-to/conditional-openapi.md diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..7f277bb88 --- /dev/null +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -0,0 +1,58 @@ +# Bedingte OpenAPI + +Bei Bedarf können Sie OpenAPI mithilfe von Einstellungen und Umgebungsvariablen abhängig von der Umgebung bedingt konfigurieren und sogar vollständig deaktivieren. + +## Über Sicherheit, APIs und Dokumentation + +Das Verstecken Ihrer Dokumentationsoberflächen in der Produktion *sollte nicht* die Methode sein, Ihre API zu schützen. + +Dadurch wird Ihrer API keine zusätzliche Sicherheit hinzugefügt, die *Pfadoperationen* sind weiterhin dort verfügbar, wo sie sich befinden. + +Wenn Ihr Code eine Sicherheitslücke aufweist, ist diese weiterhin vorhanden. + +Das Verstecken der Dokumentation macht es nur schwieriger zu verstehen, wie mit Ihrer API interagiert werden kann, und könnte es auch schwieriger machen, diese in der Produktion zu debuggen. Man könnte es einfach als eine Form von <a href="https://de.wikipedia.org/wiki/Security_through_obscurity" class="external-link" target="_blank">Security through obscurity</a> betrachten. + +Wenn Sie Ihre API sichern möchten, gibt es mehrere bessere Dinge, die Sie tun können, zum Beispiel: + +* Stellen Sie sicher, dass Sie über gut definierte Pydantic-Modelle für Ihre Requestbodys und Responses verfügen. +* Konfigurieren Sie alle erforderlichen Berechtigungen und Rollen mithilfe von Abhängigkeiten. +* Speichern Sie niemals Klartext-Passwörter, sondern nur Passwort-Hashes. +* Implementieren und verwenden Sie gängige kryptografische Tools wie Passlib und JWT-Tokens, usw. +* Fügen Sie bei Bedarf detailliertere Berechtigungskontrollen mit OAuth2-Scopes hinzu. +* ... usw. + +Dennoch kann es sein, dass Sie einen ganz bestimmten Anwendungsfall haben, bei dem Sie die API-Dokumentation für eine bestimmte Umgebung (z. B. für die Produktion) oder abhängig von Konfigurationen aus Umgebungsvariablen wirklich deaktivieren müssen. + +## Bedingte OpenAPI aus Einstellungen und Umgebungsvariablen + +Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre generierte OpenAPI und die Dokumentationsoberflächen zu konfigurieren. + +Zum Beispiel: + +```Python hl_lines="6 11" +{!../../../docs_src/conditional_openapi/tutorial001.py!} +``` + +Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. + +Und dann verwenden wir das beim Erstellen der `FastAPI`-App. + +Dann könnten Sie OpenAPI (einschließlich der Dokumentationsoberflächen) deaktivieren, indem Sie die Umgebungsvariable `OPENAPI_URL` auf einen leeren String setzen, wie zum Beispiel: + +<div class="termy"> + +```console +$ OPENAPI_URL= uvicorn main:app + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +Wenn Sie dann zu den URLs unter `/openapi.json`, `/docs` oder `/redoc` gehen, erhalten Sie lediglich einen `404 Not Found`-Fehler, wie: + +```JSON +{ + "detail": "Not Found" +} +``` From c3056bd2ffa36f2a9cc764d8c87ea862e7d67df6 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:18:23 +0100 Subject: [PATCH 153/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/custom-request-and-route.md`=20?= =?UTF-8?q?(#10789)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/how-to/custom-request-and-route.md | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 docs/de/docs/how-to/custom-request-and-route.md diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md new file mode 100644 index 000000000..b51a20bfc --- /dev/null +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -0,0 +1,109 @@ +# Benutzerdefinierte Request- und APIRoute-Klasse + +In einigen Fällen möchten Sie möglicherweise die von den Klassen `Request` und `APIRoute` verwendete Logik überschreiben. + +Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. + +Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. + +!!! danger "Gefahr" + Dies ist eine „fortgeschrittene“ Funktion. + + Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. + +## Anwendungsfälle + +Einige Anwendungsfälle sind: + +* Konvertieren von Nicht-JSON-Requestbodys nach JSON (z. B. <a href="https://msgpack.org/index.html" class="external-link" target="_blank">`msgpack`</a>). +* Dekomprimierung gzip-komprimierter Requestbodys. +* Automatisches Loggen aller Requestbodys. + +## Handhaben von benutzerdefinierten Requestbody-Kodierungen + +Sehen wir uns an, wie Sie eine benutzerdefinierte `Request`-Unterklasse verwenden, um gzip-Requests zu dekomprimieren. + +Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Requestklasse. + +### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen + +!!! tip "Tipp" + Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. + +Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren. + +Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprimieren. + +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!} +``` + +### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen + +Als Nächstes erstellen wir eine benutzerdefinierte Unterklasse von `fastapi.routing.APIRoute`, welche `GzipRequest` nutzt. + +Dieses Mal wird die Methode `APIRoute.get_route_handler()` überschrieben. + +Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Request und gibt eine Response zurück. + +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!} +``` + +!!! 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. + + Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. + + Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. + + Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. + + Um mehr über den `Request` zu erfahren, schauen Sie sich <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlettes Dokumentation zu Requests</a> an. + +Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`. + +Dabei kümmert sich unser `GzipRequest` um die Dekomprimierung der Daten (falls erforderlich), bevor diese an unsere *Pfadoperationen* weitergegeben werden. + +Danach ist die gesamte Verarbeitungslogik dieselbe. + +Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch bei Bedarf automatisch dekomprimiert, wenn er von **FastAPI** geladen wird. + +## Zugriff auf den Requestbody in einem Exceptionhandler + +!!! tip "Tipp" + Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). + + Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. + +Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen. + +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!} +``` + +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!} +``` + +## 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!} +``` + +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!} +``` From 790734d4d28cb80e3b2e842b443e1af93056752b Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:18:31 +0100 Subject: [PATCH 154/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/graphql.md`=20(#10788)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/graphql.md | 56 ++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 docs/de/docs/how-to/graphql.md diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md new file mode 100644 index 000000000..9b03e8e05 --- /dev/null +++ b/docs/de/docs/how-to/graphql.md @@ -0,0 +1,56 @@ +# GraphQL + +Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **GraphQL**-Bibliothek zu integrieren, die auch mit ASGI kompatibel ist. + +Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren. + +!!! tip "Tipp" + **GraphQL** löst einige sehr spezifische Anwendungsfälle. + + Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**. + + Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓 + +## GraphQL-Bibliotheken + +Hier sind einige der **GraphQL**-Bibliotheken, welche **ASGI** unterstützen. Diese könnten Sie mit **FastAPI** verwenden: + +* <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> 🍓 + * Mit <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">Dokumentation für FastAPI</a> +* <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">Ariadne</a> + * Mit <a href="https://ariadnegraphql.org/docs/starlette-integration" class="external-link" target="_blank">Dokumentation für Starlette</a> (welche auch für FastAPI gilt) +* <a href="https://tartiflette.io/" class="external-link" target="_blank">Tartiflette</a> + * Mit <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">Tartiflette ASGI</a>, für ASGI-Integration +* <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a> + * Mit <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a> + +## GraphQL mit Strawberry + +Wenn Sie mit **GraphQL** arbeiten möchten oder müssen, ist <a href="https://strawberry.rocks/" class="external-link" target="_blank">**Strawberry**</a> die **empfohlene** Bibliothek, da deren Design dem Design von **FastAPI** am nächsten kommt und alles auf **Typannotationen** basiert. + +Abhängig von Ihrem Anwendungsfall bevorzugen Sie vielleicht eine andere Bibliothek, aber wenn Sie mich fragen würden, würde ich Ihnen wahrscheinlich empfehlen, **Strawberry** auszuprobieren. + +Hier ist eine kleine Vorschau, wie Sie Strawberry mit FastAPI integrieren können: + +```Python hl_lines="3 22 25-26" +{!../../../docs_src/graphql/tutorial001.py!} +``` + +Weitere Informationen zu Strawberry finden Sie in der <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry-Dokumentation</a>. + +Und auch die Dokumentation zu <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">Strawberry mit FastAPI</a>. + +## Ältere `GraphQLApp` von Starlette + +Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integration mit <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a>. + +Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a> **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. + +!!! tip "Tipp" + Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. + +## Mehr darüber lernen + +Weitere Informationen zu **GraphQL** finden Sie in der <a href="https://graphql.org/" class="external-link" target="_blank">offiziellen GraphQL-Dokumentation</a>. + +Sie können auch mehr über jede der oben beschriebenen Bibliotheken in den jeweiligen Links lesen. From 68d49c05d5ec29328e92d473debc5c5741016c38 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:18:42 +0100 Subject: [PATCH 155/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/general.md`=20(#10770)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/general.md | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/de/docs/how-to/general.md diff --git a/docs/de/docs/how-to/general.md b/docs/de/docs/how-to/general.md new file mode 100644 index 000000000..b38b5fabf --- /dev/null +++ b/docs/de/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Allgemeines – How-To – Rezepte + +Hier finden Sie mehrere Verweise auf andere Stellen in der Dokumentation, für allgemeine oder häufige Fragen. + +## Daten filtern – Sicherheit + +Um sicherzustellen, dass Sie nicht mehr Daten zurückgeben, als Sie sollten, lesen Sie die Dokumentation unter [Tutorial – Responsemodell – Rückgabetyp](../tutorial/response-model.md){.internal-link target=_blank}. + +## Dokumentations-Tags – OpenAPI + +Um Tags zu Ihren *Pfadoperationen* hinzuzufügen und diese in der Oberfläche der Dokumentation zu gruppieren, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Zusammenfassung und Beschreibung in der Dokumentation – OpenAPI + +Um Ihren *Pfadoperationen* eine Zusammenfassung und Beschreibung hinzuzufügen und diese in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Zusammenfassung und Beschreibung](../tutorial/path-operation-configuration.md#zusammenfassung-und-beschreibung){.internal-link target=_blank}. + +## Beschreibung der Response in der Dokumentation – OpenAPI + +Um die Beschreibung der Response zu definieren, welche in der Oberfläche der Dokumentation angezeigt wird, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Beschreibung der Response](../tutorial/path-operation-configuration.md#beschreibung-der-response){.internal-link target=_blank}. + +## *Pfadoperation* in der Dokumentation deprecaten – OpenAPI + +Um eine *Pfadoperation* zu deprecaten – sie als veraltet zu markieren – und das in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Deprecaten](../tutorial/path-operation-configuration.md#eine-pfadoperation-deprecaten){.internal-link target=_blank}. + +## Daten in etwas JSON-kompatibles konvertieren + +Um Daten in etwas JSON-kompatibles zu konvertieren, lesen Sie die Dokumentation unter [Tutorial – JSON-kompatibler Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +## OpenAPI-Metadaten – Dokumentation + +Um Metadaten zu Ihrem OpenAPI-Schema hinzuzufügen, einschließlich einer Lizenz, Version, Kontakt, usw., lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md){.internal-link target=_blank}. + +## Benutzerdefinierte OpenAPI-URL + +Um die OpenAPI-URL anzupassen (oder zu entfernen), lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## URLs der OpenAPI-Dokumentationen + +Um die URLs zu aktualisieren, die für die automatisch generierten Dokumentations-Oberflächen verwendet werden, lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md#urls-der-dokumentationen){.internal-link target=_blank}. From 57a75793371a8f48cba89c3c1941d1b1fcebf4ec Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:18:53 +0100 Subject: [PATCH 156/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/how-to/index.md`=20(#10769)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/index.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 docs/de/docs/how-to/index.md diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md new file mode 100644 index 000000000..101829ff8 --- /dev/null +++ b/docs/de/docs/how-to/index.md @@ -0,0 +1,10 @@ +# How-To – Rezepte + +Hier finden Sie verschiedene Rezepte und „How-To“-Anleitungen zu **verschiedenen Themen**. + +Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meisten Fällen müssen Sie diese nur studieren, wenn sie direkt auf **Ihr Projekt** anwendbar sind. + +Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. + +!!! tip "Tipp" + Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. From 221a3ae59c2f8ab4293f20f09c4abe79cb09740d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:19:03 +0000 Subject: [PATCH 157/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2705bc208..df82cd9ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/security/get-current-user.md`. PR [#10439](https://github.com/tiangolo/fastapi/pull/10439) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-forms-and-files.md`. PR [#10368](https://github.com/tiangolo/fastapi/pull/10368) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/encoder.md`. PR [#10385](https://github.com/tiangolo/fastapi/pull/10385) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-forms.md`. PR [#10361](https://github.com/tiangolo/fastapi/pull/10361) by [@nilslindemann](https://github.com/nilslindemann). From 8fd447e0e690de2c292ee44dd8890c5191fca5dd Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:19:17 +0100 Subject: [PATCH 158/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/docker.md`=20(#10759)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/docker.md | 698 ++++++++++++++++++++++++++++++ 1 file changed, 698 insertions(+) create mode 100644 docs/de/docs/deployment/docker.md diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md new file mode 100644 index 000000000..b86cf92a4 --- /dev/null +++ b/docs/de/docs/deployment/docker.md @@ -0,0 +1,698 @@ +# FastAPI in Containern – Docker + +Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein **Linux-Containerimage** zu erstellen. Normalerweise erfolgt dies mit <a href="https://www.docker.com/" class="external-link" target="_blank">**Docker**</a>. Sie können dieses Containerimage dann auf eine von mehreren möglichen Arten bereitstellen. + +Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. + +!!! tip "Tipp" + Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). + +<Details> +<summary>Dockerfile-Vorschau 👀</summary> + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# Wenn Sie hinter einem Proxy wie Nginx oder Traefik sind, fügen Sie --proxy-headers hinzu +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +</details> + +## Was ist ein Container? + +Container (hauptsächlich Linux-Container) sind eine sehr **leichtgewichtige** Möglichkeit, Anwendungen einschließlich aller ihrer Abhängigkeiten und erforderlichen Dateien zu verpacken und sie gleichzeitig von anderen Containern (anderen Anwendungen oder Komponenten) im selben System isoliert zu halten. + +Linux-Container werden mit demselben Linux-Kernel des Hosts (Maschine, virtuellen Maschine, Cloud-Servers, usw.) ausgeführt. Das bedeutet einfach, dass sie sehr leichtgewichtig sind (im Vergleich zu vollständigen virtuellen Maschinen, die ein gesamtes Betriebssystem emulieren). + +Auf diese Weise verbrauchen Container **wenig Ressourcen**, eine Menge vergleichbar mit der direkten Ausführung der Prozesse (eine virtuelle Maschine würde viel mehr verbrauchen). + +Container verfügen außerdem über ihre eigenen **isoliert** laufenden Prozesse (üblicherweise nur einen Prozess), über ihr eigenes Dateisystem und ihr eigenes Netzwerk, was die Bereitstellung, Sicherheit, Entwicklung usw. vereinfacht. + +## Was ist ein Containerimage? + +Ein **Container** wird von einem **Containerimage** ausgeführt. + +Ein Containerimage ist eine **statische** Version aller Dateien, Umgebungsvariablen und des Standardbefehls/-programms, welche in einem Container vorhanden sein sollten. **Statisch** bedeutet hier, dass das Container-**Image** nicht läuft, nicht ausgeführt wird, sondern nur die gepackten Dateien und Metadaten enthält. + +Im Gegensatz zu einem „**Containerimage**“, bei dem es sich um den gespeicherten statischen Inhalt handelt, bezieht sich ein „**Container**“ normalerweise auf die laufende Instanz, das Ding, das **ausgeführt** wird. + +Wenn der **Container** gestartet und ausgeführt wird (gestartet von einem **Containerimage**), kann er Dateien, Umgebungsvariablen usw. erstellen oder ändern. Diese Änderungen sind nur in diesem Container vorhanden, nicht im zugrunde liegenden bestehen Containerimage (werden nicht auf der Festplatte gespeichert). + +Ein Containerimage ist vergleichbar mit der **Programmdatei** und ihrem Inhalt, z. B. `python` und eine Datei `main.py`. + +Und der **Container** selbst (im Gegensatz zum **Containerimage**) ist die tatsächlich laufende Instanz des Images, vergleichbar mit einem **Prozess**. Tatsächlich läuft ein Container nur, wenn er einen **laufenden Prozess** hat (und normalerweise ist es nur ein einzelner Prozess). Der Container stoppt, wenn kein Prozess darin ausgeführt wird. + +## Containerimages + +Docker ist eines der wichtigsten Tools zum Erstellen und Verwalten von **Containerimages** und **Containern**. + +Und es gibt einen öffentlichen <a href="https://hub.docker.com/" class="external-link" target="_blank">Docker <abbr title="Umschlagsplatz">Hub</abbr></a> mit vorgefertigten **offiziellen Containerimages** für viele Tools, Umgebungen, Datenbanken und Anwendungen. + +Beispielsweise gibt es ein offizielles <a href="https://hub.docker.com/_/python" class="external-link" target="_blank">Python-Image</a>. + +Und es gibt viele andere Images für verschiedene Dinge wie Datenbanken, zum Beispiel für: + +* <a href="https://hub.docker.com/_/postgres" class="external-link" target="_blank">PostgreSQL</a> +* <a href="https://hub.docker.com/_/mysql" class="external-link" target="_blank">MySQL</a> +* <a href="https://hub.docker.com/_/mongo" class="external-link" target="_blank">MongoDB</a> +* <a href="https://hub.docker.com/_/redis" class="external-link" target="_blank">Redis</a>, usw. + +Durch die Verwendung eines vorgefertigten Containerimages ist es sehr einfach, verschiedene Tools zu **kombinieren** und zu verwenden. Zum Beispiel, um eine neue Datenbank auszuprobieren. In den meisten Fällen können Sie die **offiziellen Images** verwenden und diese einfach mit Umgebungsvariablen konfigurieren. + +Auf diese Weise können Sie in vielen Fällen etwas über Container und Docker lernen und dieses Wissen mit vielen verschiedenen Tools und Komponenten wiederverwenden. + +Sie würden also **mehrere Container** mit unterschiedlichen Dingen ausführen, wie einer Datenbank, einer Python-Anwendung, einem Webserver mit einer React-Frontend-Anwendung, und diese über ihr internes Netzwerk miteinander verbinden. + +In alle Containerverwaltungssysteme (wie Docker oder Kubernetes) sind diese Netzwerkfunktionen integriert. + +## Container und Prozesse + +Ein **Containerimage** enthält normalerweise in seinen Metadaten das Standardprogramm oder den Standardbefehl, der ausgeführt werden soll, wenn der **Container** gestartet wird, sowie die Parameter, die an dieses Programm übergeben werden sollen. Sehr ähnlich zu dem, was wäre, wenn es über die Befehlszeile gestartet werden würde. + +Wenn ein **Container** gestartet wird, führt er diesen Befehl/dieses Programm aus (Sie können ihn jedoch überschreiben und einen anderen Befehl/ein anderes Programm ausführen lassen). + +Ein Container läuft, solange der **Hauptprozess** (Befehl oder Programm) läuft. + +Ein Container hat normalerweise einen **einzelnen Prozess**, aber es ist auch möglich, Unterprozesse vom Hauptprozess aus zu starten, und auf diese Weise haben Sie **mehrere Prozesse** im selben Container. + +Es ist jedoch nicht möglich, einen laufenden Container, ohne **mindestens einen laufenden Prozess** zu haben. Wenn der Hauptprozess stoppt, stoppt der Container. + +## Ein Docker-Image für FastAPI erstellen + +Okay, wollen wir jetzt etwas bauen! 🚀 + +Ich zeige Ihnen, wie Sie ein **Docker-Image** für FastAPI **von Grund auf** erstellen, basierend auf dem **offiziellen Python**-Image. + +Das ist, was Sie in **den meisten Fällen** tun möchten, zum Beispiel: + +* Bei Verwendung von **Kubernetes** oder ähnlichen Tools +* Beim Betrieb auf einem **Raspberry Pi** +* Bei Verwendung eines Cloud-Dienstes, der ein Containerimage für Sie ausführt, usw. + +### Paketanforderungen + +Normalerweise befinden sich die **Paketanforderungen** für Ihre Anwendung in einer Datei. + +Dies hängt hauptsächlich von dem Tool ab, mit dem Sie diese Anforderungen **installieren**. + +Die gebräuchlichste Methode besteht darin, eine Datei `requirements.txt` mit den Namen der Packages und deren Versionen zu erstellen, eine pro Zeile. + +Sie würden natürlich die gleichen Ideen verwenden, die Sie in [Über FastAPI-Versionen](versions.md){.internal-link target=_blank} gelesen haben, um die Versionsbereiche festzulegen. + +Ihre `requirements.txt` könnte beispielsweise so aussehen: + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +Und normalerweise würden Sie diese Paketabhängigkeiten mit `pip` installieren, zum Beispiel: + +<div class="termy"> + +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +</div> + +!!! info + Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. + + Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 + +### Den **FastAPI**-Code erstellen + +* Erstellen Sie ein `app`-Verzeichnis und betreten Sie es. +* Erstellen Sie eine leere Datei `__init__.py`. +* Erstellen Sie eine `main.py`-Datei mit: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +### Dockerfile + +Erstellen Sie nun im selben Projektverzeichnis eine Datei `Dockerfile` mit: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Beginne mit dem offiziellen Python-Basisimage. + +2. Setze das aktuelle Arbeitsverzeichnis auf `/code`. + + Hier plazieren wir die Datei `requirements.txt` und das Verzeichnis `app`. + +3. Kopiere die Datei mit den Paketanforderungen in das Verzeichnis `/code`. + + Kopieren Sie zuerst **nur** die Datei mit den Anforderungen, nicht den Rest des Codes. + + Da sich diese Datei **nicht oft ändert**, erkennt Docker das und verwendet den **Cache** für diesen Schritt, wodurch der Cache auch für den nächsten Schritt aktiviert wird. + +4. Installiere die Paketabhängigkeiten aus der Anforderungsdatei. + + Die Option `--no-cache-dir` weist `pip` an, die heruntergeladenen Pakete nicht lokal zu speichern, da dies nur benötigt wird, sollte `pip` erneut ausgeführt werden, um dieselben Pakete zu installieren, aber das ist beim Arbeiten mit Containern nicht der Fall. + + !!! note "Hinweis" + Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + + Die Option `--upgrade` weist `pip` an, die Packages zu aktualisieren, wenn sie bereits installiert sind. + + Da der vorherige Schritt des Kopierens der Datei vom **Docker-Cache** erkannt werden konnte, wird dieser Schritt auch **den Docker-Cache verwenden**, sofern verfügbar. + + Durch die Verwendung des Caches in diesem Schritt **sparen** Sie viel **Zeit**, wenn Sie das Image während der Entwicklung immer wieder erstellen, anstatt **jedes Mal** alle Abhängigkeiten **herunterzuladen und zu installieren**. + +5. Kopiere das Verzeichnis `./app` in das Verzeichnis `/code`. + + Da hier der gesamte Code enthalten ist, der sich **am häufigsten ändert**, wird der Docker-**Cache** nicht ohne weiteres für diesen oder andere **folgende Schritte** verwendet. + + Daher ist es wichtig, dies **nahe dem Ende** des `Dockerfile`s zu platzieren, um die Erstellungszeiten des Containerimages zu optimieren. + +6. Lege den **Befehl** fest, um den `uvicorn`-Server zu starten. + + `CMD` nimmt eine Liste von Zeichenfolgen entgegen. Jede dieser Zeichenfolgen entspricht dem, was Sie durch Leerzeichen getrennt in die Befehlszeile eingeben würden. + + Dieser Befehl wird aus dem **aktuellen Arbeitsverzeichnis** ausgeführt, dem gleichen `/code`-Verzeichnis, das Sie oben mit `WORKDIR /code` festgelegt haben. + + Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. + +!!! tip "Tipp" + Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 + +Sie sollten jetzt eine Verzeichnisstruktur wie diese haben: + +``` +. +├── app +│ ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + +#### Hinter einem TLS-Terminierungsproxy + +Wenn Sie Ihren Container hinter einem TLS-Terminierungsproxy (Load Balancer) wie Nginx oder Traefik ausführen, fügen Sie die Option `--proxy-headers` hinzu. Das sagt Uvicorn, den von diesem Proxy gesendeten Headern zu vertrauen und dass die Anwendung hinter HTTPS ausgeführt wird, usw. + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### Docker-Cache + +In diesem `Dockerfile` gibt es einen wichtigen Trick: Wir kopieren zuerst die **Datei nur mit den Abhängigkeiten**, nicht den Rest des Codes. Lassen Sie mich Ihnen erklären, warum. + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Docker und andere Tools **erstellen** diese Containerimages **inkrementell**, fügen **eine Ebene über der anderen** hinzu, beginnend am Anfang des `Dockerfile`s und fügen alle durch die einzelnen Anweisungen des `Dockerfile`s erstellten Dateien hinzu. + +Docker und ähnliche Tools verwenden beim Erstellen des Images auch einen **internen Cache**. Wenn sich eine Datei seit der letzten Erstellung des Containerimages nicht geändert hat, wird **dieselbe Ebene wiederverwendet**, die beim letzten Mal erstellt wurde, anstatt die Datei erneut zu kopieren und eine neue Ebene von Grund auf zu erstellen. + +Das bloße Vermeiden des Kopierens von Dateien führt nicht unbedingt zu einer großen Verbesserung, aber da der Cache für diesen Schritt verwendet wurde, kann **der Cache für den nächsten Schritt verwendet werden**. Beispielsweise könnte der Cache verwendet werden für die Anweisung, welche die Abhängigkeiten installiert mit: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + +Die Datei mit den Paketanforderungen wird sich **nicht häufig ändern**. Wenn Docker also nur diese Datei kopiert, kann es für diesen Schritt **den Cache verwenden**. + +Und dann kann Docker **den Cache für den nächsten Schritt verwenden**, der diese Abhängigkeiten herunterlädt und installiert. Und hier **sparen wir viel Zeit**. ✨ ... und vermeiden die Langeweile beim Warten. 😪😆 + +Das Herunterladen und Installieren der Paketabhängigkeiten **könnte Minuten dauern**, aber die Verwendung des **Cache** würde höchstens **Sekunden** dauern. + +Und da Sie das Containerimage während der Entwicklung immer wieder erstellen würden, um zu überprüfen, ob Ihre Codeänderungen funktionieren, würde dies viel Zeit sparen. + +Dann, gegen Ende des `Dockerfile`s, kopieren wir den gesamten Code. Da sich der **am häufigsten ändert**, platzieren wir das am Ende, da fast immer alles nach diesem Schritt nicht mehr in der Lage sein wird, den Cache zu verwenden. + +```Dockerfile +COPY ./app /code/app +``` + +### Das Docker-Image erstellen + +Nachdem nun alle Dateien vorhanden sind, erstellen wir das Containerimage. + +* Gehen Sie zum Projektverzeichnis (dort, wo sich Ihr `Dockerfile` und Ihr `app`-Verzeichnis befindet). +* Erstellen Sie Ihr FastAPI-Image: + +<div class="termy"> + +```console +$ docker build -t myimage . + +---> 100% +``` + +</div> + +!!! tip "Tipp" + Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. + + In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). + +### Den Docker-Container starten + +* Führen Sie einen Container basierend auf Ihrem Image aus: + +<div class="termy"> + +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +</div> + +## Es überprüfen + +Sie sollten es in der URL Ihres Docker-Containers überprüfen können, zum Beispiel: <a href="http://192.168.99.100/items/5?q=somequery" class="external-link" target="_blank">http://192.168.99.100/items/5?q=somequery</a> oder <a href="http://127.0.0.1/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1/items/5?q=somequery</a> (oder gleichwertig, unter Verwendung Ihres Docker-Hosts). + +Sie werden etwas sehen wie: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## Interaktive API-Dokumentation + +Jetzt können Sie auf <a href="http://192.168.99.100/docs" class="external-link" target="_blank">http://192.168.99.100/docs</a> oder <a href="http://127.0.0.1/docs" class="external-link" target="_blank">http://127.0.0.1/docs</a> gehen (oder ähnlich, unter Verwendung Ihres Docker-Hosts). + +Sie sehen die automatische interaktive API-Dokumentation (bereitgestellt von <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>): + + + +## Alternative API-Dokumentation + +Sie können auch auf <a href="http://192.168.99.100/redoc" class="external-link" target="_blank">http://192.168.99.100/redoc</a> oder <a href="http://127.0.0.1/redoc" class="external-link" target="_blank">http://127.0.0.1/redoc</a> gehen (oder ähnlich, unter Verwendung Ihres Docker-Hosts). + +Sie sehen die alternative automatische Dokumentation (bereitgestellt von <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>): + + + +## Ein Docker-Image mit einem Single-File-FastAPI erstellen + +Wenn Ihr FastAPI eine einzelne Datei ist, zum Beispiel `main.py` ohne ein `./app`-Verzeichnis, könnte Ihre Dateistruktur wie folgt aussehen: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +Dann müssten Sie nur noch die entsprechenden Pfade ändern, um die Datei im `Dockerfile` zu kopieren: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Kopiere die Datei `main.py` direkt in das Verzeichnis `/code` (ohne ein Verzeichnis `./app`). + +2. Führe Uvicorn aus und weisen es an, das `app`-Objekt von `main` zu importieren (anstatt von `app.main` zu importieren). + +Passen Sie dann den Uvicorn-Befehl an, um das neue Modul `main` anstelle von `app.main` zu verwenden, um das FastAPI-Objekt `app` zu importieren. + +## Deployment-Konzepte + +Lassen Sie uns noch einmal über einige der gleichen [Deployment-Konzepte](concepts.md){.internal-link target=_blank} in Bezug auf Container sprechen. + +Container sind hauptsächlich ein Werkzeug, um den Prozess des **Erstellens und Deployments** einer Anwendung zu vereinfachen, sie erzwingen jedoch keinen bestimmten Ansatz für die Handhabung dieser **Deployment-Konzepte**, und es gibt mehrere mögliche Strategien. + +Die **gute Nachricht** ist, dass es mit jeder unterschiedlichen Strategie eine Möglichkeit gibt, alle Deployment-Konzepte abzudecken. 🎉 + +Sehen wir uns diese **Deployment-Konzepte** im Hinblick auf Container noch einmal an: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +## HTTPS + +Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und später auf den laufenden **Container**) konzentrieren, würde HTTPS normalerweise **extern** von einem anderen Tool verarbeitet. + +Es könnte sich um einen anderen Container handeln, zum Beispiel mit <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. + +!!! tip "Tipp" + Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. + +Alternativ könnte HTTPS von einem Cloud-Anbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird). + +## Beim Hochfahren ausführen und Neustarts + +Normalerweise gibt es ein anderes Tool, das für das **Starten und Ausführen** Ihres Containers zuständig ist. + +Es könnte sich um **Docker** direkt, **Docker Compose**, **Kubernetes**, einen **Cloud-Dienst**, usw. handeln. + +In den meisten (oder allen) Fällen gibt es eine einfache Option, um die Ausführung des Containers beim Hochfahren und Neustarts bei Fehlern zu ermöglichen. In Docker ist es beispielsweise die Befehlszeilenoption `--restart`. + +Ohne die Verwendung von Containern kann es umständlich und schwierig sein, Anwendungen beim Hochfahren auszuführen und neu zu starten. Bei der **Arbeit mit Containern** ist diese Funktionalität jedoch in den meisten Fällen standardmäßig enthalten. ✨ + +## Replikation – Anzahl der Prozesse + +Wenn Sie einen <abbr title="Eine Gruppe von Maschinen, die so konfiguriert sind, dass sie verbunden sind und auf irgendeine Weise zusammenarbeiten.">Cluster</abbr> von Maschinen mit **Kubernetes**, Docker Swarm Mode, Nomad verwenden, oder einem anderen, ähnlich komplexen System zur Verwaltung verteilter Container auf mehreren Maschinen, möchten Sie wahrscheinlich die **Replikation auf Cluster-Ebene abwickeln**, anstatt in jedem Container einen **Prozessmanager** (wie Gunicorn mit Workern) zu verwenden. + +Diese verteilten Containerverwaltungssysteme wie Kubernetes verfügen normalerweise über eine integrierte Möglichkeit, die **Replikation von Containern** zu handhaben und gleichzeitig **Load Balancing** für die eingehenden Requests zu unterstützen. Alles auf **Cluster-Ebene**. + +In diesen Fällen möchten Sie wahrscheinlich ein **Docker-Image von Grund auf** erstellen, wie [oben erklärt](#dockerfile), Ihre Abhängigkeiten installieren und **einen einzelnen Uvicorn-Prozess** ausführen, anstatt etwas wie Gunicorn mit Uvicorn-Workern auszuführen. + +### Load Balancer + +Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, **die am Hauptport lauscht**. Es könnte sich um einen anderen Container handeln, der auch ein **TLS-Terminierungsproxy** ist, um **HTTPS** zu verarbeiten, oder ein ähnliches Tool. + +Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. + +!!! tip "Tipp" + Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. + +Und wenn Sie mit Containern arbeiten, verfügt das gleiche System, mit dem Sie diese starten und verwalten, bereits über interne Tools, um die **Netzwerkkommunikation** (z. B. HTTP-Requests) von diesem **Load Balancer** (das könnte auch ein **TLS-Terminierungsproxy** sein) zu den Containern mit Ihrer Anwendung weiterzuleiten. + +### Ein Load Balancer – mehrere Workercontainer + +Bei der Arbeit mit **Kubernetes** oder ähnlichen verteilten Containerverwaltungssystemen würde die Verwendung ihrer internen Netzwerkmechanismen es dem einzelnen **Load Balancer**, der den Haupt-**Port** überwacht, ermöglichen, Kommunikation (Requests) an möglicherweise **mehrere Container** weiterzuleiten, in denen Ihre Anwendung ausgeführt wird. + +Jeder dieser Container, in denen Ihre Anwendung ausgeführt wird, verfügt normalerweise über **nur einen Prozess** (z. B. einen Uvicorn-Prozess, der Ihre FastAPI-Anwendung ausführt). Es wären alles **identische Container**, die das Gleiche ausführen, welche aber jeweils über einen eigenen Prozess, Speicher, usw. verfügen. Auf diese Weise würden Sie die **Parallelisierung** in **verschiedenen Kernen** der CPU nutzen. Oder sogar in **verschiedenen Maschinen**. + +Und das verteilte Containersystem mit dem **Load Balancer** würde **die Requests abwechselnd** an jeden einzelnen Container mit Ihrer Anwendung verteilen. Jeder Request könnte also von einem der mehreren **replizierten Container** verarbeitet werden, in denen Ihre Anwendung ausgeführt wird. + +Und normalerweise wäre dieser **Load Balancer** in der Lage, Requests zu verarbeiten, die an *andere* Anwendungen in Ihrem Cluster gerichtet sind (z. B. eine andere Domain oder unter einem anderen URL-Pfad-Präfix), und würde diese Kommunikation an die richtigen Container weiterleiten für *diese andere* Anwendung, die in Ihrem Cluster ausgeführt wird. + +### Ein Prozess pro Container + +In einem solchen Szenario möchten Sie wahrscheinlich **einen einzelnen (Uvicorn-)Prozess pro Container** haben, da Sie die Replikation bereits auf Cluster ebene durchführen würden. + +In diesem Fall möchten Sie also **nicht** einen Prozessmanager wie Gunicorn mit Uvicorn-Workern oder Uvicorn mit seinen eigenen Uvicorn-Workern haben. Sie möchten nur einen **einzelnen Uvicorn-Prozess** pro Container haben (wahrscheinlich aber mehrere Container). + +Ein weiterer Prozessmanager im Container (wie es bei Gunicorn oder Uvicorn der Fall wäre, welche Uvicorn-Worker verwalten) würde nur **unnötige Komplexität** hinzufügen, um welche Sie sich höchstwahrscheinlich bereits mit Ihrem Clustersystem kümmern. + +### Container mit mehreren Prozessen und Sonderfälle + +Natürlich gibt es **Sonderfälle**, in denen Sie **einen Container** mit einem **Gunicorn-Prozessmanager** haben möchten, welcher mehrere **Uvicorn-Workerprozesse** darin startet. + +In diesen Fällen können Sie das **offizielle Docker-Image** verwenden, welches **Gunicorn** als Prozessmanager enthält, welcher mehrere **Uvicorn-Workerprozesse** ausführt, sowie einige Standardeinstellungen, um die Anzahl der Worker basierend auf den verfügbaren CPU-Kernen automatisch anzupassen. Ich erzähle Ihnen weiter unten in [Offizielles Docker-Image mit Gunicorn – Uvicorn](#offizielles-docker-image-mit-gunicorn-uvicorn) mehr darüber. + +Hier sind einige Beispiele, wann das sinnvoll sein könnte: + +#### Eine einfache Anwendung + +Sie könnten einen Prozessmanager im Container haben wollen, wenn Ihre Anwendung **einfach genug** ist, sodass Sie die Anzahl der Prozesse nicht (zumindest noch nicht) zu stark tunen müssen und Sie einfach einen automatisierten Standard verwenden können (mit dem offiziellen Docker-Image), und Sie führen es auf einem **einzelnen Server** aus, nicht auf einem Cluster. + +#### Docker Compose + +Sie könnten das Deployment auf einem **einzelnen Server** (kein Cluster) mit **Docker Compose** durchführen, sodass Sie keine einfache Möglichkeit hätten, die Replikation von Containern (mit Docker Compose) zu verwalten und gleichzeitig das gemeinsame Netzwerk mit **Load Balancing** zu haben. + +Dann möchten Sie vielleicht **einen einzelnen Container** mit einem **Prozessmanager** haben, der darin **mehrere Workerprozesse** startet. + +#### Prometheus und andere Gründe + +Sie könnten auch **andere Gründe** haben, die es einfacher machen würden, einen **einzelnen Container** mit **mehreren Prozessen** zu haben, anstatt **mehrere Container** mit **einem einzelnen Prozess** in jedem von ihnen. + +Beispielsweise könnten Sie (abhängig von Ihrem Setup) ein Tool wie einen Prometheus-Exporter im selben Container haben, welcher Zugriff auf **jeden der eingehenden Requests** haben sollte. + +Wenn Sie in hier **mehrere Container** hätten, würde Prometheus beim **Lesen der Metriken** standardmäßig jedes Mal diejenigen für **einen einzelnen Container** abrufen (für den Container, der den spezifischen Request verarbeitet hat), anstatt die **akkumulierten Metriken** für alle replizierten Container abzurufen. + +In diesem Fall könnte einfacher sein, **einen Container** mit **mehreren Prozessen** und ein lokales Tool (z. B. einen Prometheus-Exporter) in demselben Container zu haben, welches Prometheus-Metriken für alle internen Prozesse sammelt und diese Metriken für diesen einzelnen Container offenlegt. + +--- + +Der Hauptpunkt ist, dass **keine** dieser Regeln **in Stein gemeißelt** ist, der man blind folgen muss. Sie können diese Ideen verwenden, um **Ihren eigenen Anwendungsfall zu evaluieren**, zu entscheiden, welcher Ansatz für Ihr System am besten geeignet ist und herauszufinden, wie Sie folgende Konzepte verwalten: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +## Arbeitsspeicher + +Wenn Sie **einen einzelnen Prozess pro Container** ausführen, wird von jedem dieser Container (mehr als einer, wenn sie repliziert werden) eine mehr oder weniger klar definierte, stabile und begrenzte Menge an Arbeitsspeicher verbraucht. + +Und dann können Sie dieselben Speichergrenzen und -anforderungen in Ihren Konfigurationen für Ihr Container-Management-System festlegen (z. B. in **Kubernetes**). Auf diese Weise ist es in der Lage, die Container auf den **verfügbaren Maschinen** zu replizieren, wobei die von denen benötigte Speichermenge und die auf den Maschinen im Cluster verfügbare Menge berücksichtigt werden. + +Wenn Ihre Anwendung **einfach** ist, wird dies wahrscheinlich **kein Problem darstellen** und Sie müssen möglicherweise keine festen Speichergrenzen angeben. Wenn Sie jedoch **viel Speicher verbrauchen** (z. B. bei **Modellen für maschinelles Lernen**), sollten Sie überprüfen, wie viel Speicher Sie verbrauchen, und die **Anzahl der Container** anpassen, die in **jeder Maschine** ausgeführt werden. (und möglicherweise weitere Maschinen zu Ihrem Cluster hinzufügen). + +Wenn Sie **mehrere Prozesse pro Container** ausführen (zum Beispiel mit dem offiziellen Docker-Image), müssen Sie sicherstellen, dass die Anzahl der gestarteten Prozesse nicht **mehr Speicher verbraucht** als verfügbar ist. + +## Schritte vor dem Start und Container + +Wenn Sie Container (z. B. Docker, Kubernetes) verwenden, können Sie hauptsächlich zwei Ansätze verwenden. + +### Mehrere Container + +Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnenen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden. + +!!! info + Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init-Container</a>. + +Wenn es in Ihrem Anwendungsfall kein Problem darstellt, diese vorherigen Schritte **mehrmals parallel** auszuführen (z. B. wenn Sie keine Datenbankmigrationen ausführen, sondern nur prüfen, ob die Datenbank bereits bereit ist), können Sie sie auch einfach in jedem Container direkt vor dem Start des Hauptprozesses einfügen. + +### Einzelner Container + +Wenn Sie ein einfaches Setup mit einem **einzelnen Container** haben, welcher dann mehrere **Workerprozesse** (oder auch nur einen Prozess) startet, können Sie die Vorab-Schritte im selben Container direkt vor dem Starten des Prozesses mit der Anwendung ausführen. Das offizielle Docker-Image unterstützt das intern. + +## Offizielles Docker-Image mit Gunicorn – Uvicorn + +Es gibt ein offizielles Docker-Image, in dem Gunicorn mit Uvicorn-Workern ausgeführt wird, wie in einem vorherigen Kapitel beschrieben: [Serverworker – Gunicorn mit Uvicorn](server-workers.md){.internal-link target=_blank}. + +Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [Container mit mehreren Prozessen und Sonderfälle](#container-mit-mehreren-prozessen-und-sonderfalle). + +* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +!!! warning "Achtung" + Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +Dieses Image verfügt über einen **Auto-Tuning**-Mechanismus, um die **Anzahl der Arbeitsprozesse** basierend auf den verfügbaren CPU-Kernen festzulegen. + +Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotzdem alle Konfigurationen mit **Umgebungsvariablen** oder Konfigurationsdateien ändern und aktualisieren. + +Es unterstützt auch die Ausführung von <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**Vorab-Schritten vor dem Start** </a> mit einem Skript. + +!!! tip "Tipp" + Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +### Anzahl der Prozesse auf dem offiziellen Docker-Image + +Die **Anzahl der Prozesse** auf diesem Image wird **automatisch** anhand der verfügbaren CPU-**Kerne** berechnet. + +Das bedeutet, dass versucht wird, so viel **Leistung** wie möglich aus der CPU herauszuquetschen. + +Sie können das auch in der Konfiguration anpassen, indem Sie **Umgebungsvariablen**, usw. verwenden. + +Das bedeutet aber auch, da die Anzahl der Prozesse von der CPU abhängt, welche der Container ausführt, dass die **Menge des verbrauchten Speichers** ebenfalls davon abhängt. + +Wenn Ihre Anwendung also viel Speicher verbraucht (z. B. bei Modellen für maschinelles Lernen) und Ihr Server über viele CPU-Kerne, **aber wenig Speicher** verfügt, könnte Ihr Container am Ende versuchen, mehr Speicher als vorhanden zu verwenden, was zu erheblichen Leistungseinbußen (oder sogar zum Absturz) führen kann. 🚨 + +### Ein `Dockerfile` erstellen + +So würden Sie ein `Dockerfile` basierend auf diesem Image erstellen: + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### Größere Anwendungen + +Wenn Sie dem Abschnitt zum Erstellen von [größeren Anwendungen mit mehreren Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gefolgt sind, könnte Ihr `Dockerfile` stattdessen wie folgt aussehen: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### Wann verwenden + +Sie sollten dieses offizielle Basisimage (oder ein ähnliches) wahrscheinlich **nicht** benutzen, wenn Sie **Kubernetes** (oder andere) verwenden und Sie bereits **Replikation** auf Cluster ebene mit mehreren **Containern** eingerichtet haben. In diesen Fällen ist es besser, **ein Image von Grund auf zu erstellen**, wie oben beschrieben: [Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +Dieses Image wäre vor allem in den oben in [Container mit mehreren Prozessen und Sonderfälle](#container-mit-mehreren-prozessen-und-sonderfalle) beschriebenen Sonderfällen nützlich. Wenn Ihre Anwendung beispielsweise **einfach genug** ist, dass das Festlegen einer Standardanzahl von Prozessen basierend auf der CPU gut funktioniert, möchten Sie sich nicht mit der manuellen Konfiguration der Replikation auf Cluster ebene herumschlagen und führen nicht mehr als einen Container mit Ihrer Anwendung aus. Oder wenn Sie das Deployment mit **Docker Compose** durchführen und auf einem einzelnen Server laufen, usw. + +## Deployment des Containerimages + +Nachdem Sie ein Containerimage (Docker) haben, gibt es mehrere Möglichkeiten, es bereitzustellen. + +Zum Beispiel: + +* Mit **Docker Compose** auf einem einzelnen Server +* Mit einem **Kubernetes**-Cluster +* Mit einem Docker Swarm Mode-Cluster +* Mit einem anderen Tool wie Nomad +* Mit einem Cloud-Dienst, der Ihr Containerimage nimmt und es bereitstellt + +## Docker-Image mit Poetry + +Wenn Sie <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> verwenden, um die Abhängigkeiten Ihres Projekts zu verwalten, können Sie Dockers mehrphasige Builds verwenden: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Dies ist die erste Phase, genannt `requirements-stage` – „Anforderungsphase“. + +2. Setze `/tmp` als aktuelles Arbeitsverzeichnis. + + Hier werden wir die Datei `requirements.txt` generieren. + +3. Installiere Poetry in dieser Docker-Phase. + +4. Kopiere die Dateien `pyproject.toml` und `poetry.lock` in das Verzeichnis `/tmp`. + + Da es `./poetry.lock*` verwendet (endet mit einem `*`), stürzt es nicht ab, wenn diese Datei noch nicht verfügbar ist. + +5. Generiere die Datei `requirements.txt`. + +6. Dies ist die letzte Phase. Alles hier bleibt im endgültigen Containerimage erhalten. + +7. Setze das aktuelle Arbeitsverzeichnis auf `/code`. + +8. Kopiere die Datei `requirements.txt` in das Verzeichnis `/code`. + + Diese Datei existiert nur in der vorherigen Docker-Phase, deshalb verwenden wir `--from-requirements-stage`, um sie zu kopieren. + +9. Installiere die Paketabhängigkeiten von der generierten Datei `requirements.txt`. + +10. Kopiere das Verzeichnis `app` in das Verzeichnis `/code`. + +11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. + +!!! tip "Tipp" + Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. + +Eine **Docker-Phase** ist ein Teil eines `Dockerfile`s, welcher als **temporäres Containerimage** fungiert und nur zum Generieren einiger Dateien für die spätere Verwendung verwendet wird. + +Die erste Phase wird nur zur **Installation von Poetry** und zur **Generierung der `requirements.txt`** mit deren Projektabhängigkeiten aus der Datei `pyproject.toml` von Poetry verwendet. + +Diese `requirements.txt`-Datei wird später in der **nächsten Phase** mit `pip` verwendet. + +Im endgültigen Containerimage bleibt **nur die letzte Stufe** erhalten. Die vorherigen Stufen werden verworfen. + +Bei der Verwendung von Poetry wäre es sinnvoll, **mehrstufige Docker-Builds** zu verwenden, da Poetry und seine Abhängigkeiten nicht wirklich im endgültigen Containerimage installiert sein müssen, sondern Sie brauchen **nur** die Datei `requirements.txt`, um Ihre Projektabhängigkeiten zu installieren. + +Dann würden Sie im nächsten (und letzten) Schritt das Image mehr oder weniger auf die gleiche Weise wie zuvor beschrieben erstellen. + +### Hinter einem TLS-Terminierungsproxy – Poetry + +Auch hier gilt: Wenn Sie Ihren Container hinter einem TLS-Terminierungsproxy (Load Balancer) wie Nginx oder Traefik ausführen, fügen Sie dem Befehl die Option `--proxy-headers` hinzu: + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## Zusammenfassung + +Mithilfe von Containersystemen (z. B. mit **Docker** und **Kubernetes**) ist es ziemlich einfach, alle **Deployment-Konzepte** zu handhaben: + +* HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +In den meisten Fällen möchten Sie wahrscheinlich kein Basisimage verwenden und stattdessen **ein Containerimage von Grund auf erstellen**, eines basierend auf dem offiziellen Python-Docker-Image. + +Indem Sie auf die **Reihenfolge** der Anweisungen im `Dockerfile` und den **Docker-Cache** achten, können Sie **die Build-Zeiten minimieren**, um Ihre Produktivität zu erhöhen (und Langeweile zu vermeiden). 😎 + +In bestimmten Sonderfällen möchten Sie möglicherweise das offizielle Docker-Image für FastAPI verwenden. 🤓 From 632655a9bcd755d47dd7e3305c8abfc2a12807ab Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 19:19:25 +0100 Subject: [PATCH 159/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/server-workers.md`=20(#1074?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/server-workers.md | 180 ++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 docs/de/docs/deployment/server-workers.md diff --git a/docs/de/docs/deployment/server-workers.md b/docs/de/docs/deployment/server-workers.md new file mode 100644 index 000000000..04d48dc6c --- /dev/null +++ b/docs/de/docs/deployment/server-workers.md @@ -0,0 +1,180 @@ +# Serverworker – Gunicorn mit Uvicorn + +Schauen wir uns die Deployment-Konzepte von früher noch einmal an: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* **Replikation (die Anzahl der laufenden Prozesse)** +* Arbeitsspeicher +* Schritte vor dem Start + +Bis zu diesem Punkt, in allen Tutorials in der Dokumentation, haben Sie wahrscheinlich ein **Serverprogramm** wie Uvicorn ausgeführt, in einem **einzelnen Prozess**. + +Wenn Sie Anwendungen bereitstellen, möchten Sie wahrscheinlich eine gewisse **Replikation von Prozessen**, um **mehrere CPU-Kerne** zu nutzen und mehr Requests bearbeiten zu können. + +Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md){.internal-link target=_blank} gesehen haben, gibt es mehrere Strategien, die Sie anwenden können. + +Hier zeige ich Ihnen, wie Sie <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> mit **Uvicorn Workerprozessen** verwenden. + +!!! info + Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + + Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. + +## Gunicorn mit Uvicorn-Workern + +**Gunicorn** ist hauptsächlich ein Anwendungsserver, der den **WSGI-Standard** verwendet. Das bedeutet, dass Gunicorn Anwendungen wie Flask und Django ausliefern kann. Gunicorn selbst ist nicht mit **FastAPI** kompatibel, da FastAPI den neuesten **<a href="https://asgi.readthedocs.io/en/latest/" class="external-link" target="_blank">ASGI-Standard</a>** verwendet. + +Aber Gunicorn kann als **Prozessmanager** arbeiten und Benutzer können ihm mitteilen, welche bestimmte **Workerprozessklasse** verwendet werden soll. Dann würde Gunicorn einen oder mehrere **Workerprozesse** starten, diese Klasse verwendend. + +Und **Uvicorn** hat eine **Gunicorn-kompatible Workerklasse**. + +Mit dieser Kombination würde Gunicorn als **Prozessmanager** fungieren und den **Port** und die **IP** abhören. Und er würde die Kommunikation an die Workerprozesse **weiterleiten**, welche die **Uvicorn-Klasse** ausführen. + +Und dann wäre die Gunicorn-kompatible **Uvicorn-Worker**-Klasse dafür verantwortlich, die von Gunicorn gesendeten Daten in den ASGI-Standard zu konvertieren, damit FastAPI diese verwenden kann. + +## Gunicorn und Uvicorn installieren + +<div class="termy"> + +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +</div> + +Dadurch wird sowohl Uvicorn mit zusätzlichen `standard`-Packages (um eine hohe Leistung zu erzielen) als auch Gunicorn installiert. + +## Gunicorn mit Uvicorn-Workern ausführen + +Dann können Sie Gunicorn ausführen mit: + +<div class="termy"> + +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +</div> + +Sehen wir uns an, was jede dieser Optionen bedeutet: + +* `main:app`: Das ist die gleiche Syntax, die auch von Uvicorn verwendet wird. `main` bedeutet das Python-Modul mit dem Namen `main`, also eine Datei `main.py`. Und `app` ist der Name der Variable, welche die **FastAPI**-Anwendung ist. + * Stellen Sie sich einfach vor, dass `main:app` einer Python-`import`-Anweisung wie der folgenden entspricht: + + ```Python + from main import app + ``` + + * Der Doppelpunkt in `main:app` entspricht also dem Python-`import`-Teil in `from main import app`. + +* `--workers`: Die Anzahl der zu verwendenden Workerprozesse, jeder führt einen Uvicorn-Worker aus, in diesem Fall 4 Worker. + +* `--worker-class`: Die Gunicorn-kompatible Workerklasse zur Verwendung in den Workerprozessen. + * Hier übergeben wir die Klasse, die Gunicorn etwa so importiert und verwendet: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`: Das teilt Gunicorn die IP und den Port mit, welche abgehört werden sollen, wobei ein Doppelpunkt (`:`) verwendet wird, um die IP und den Port zu trennen. + * Wenn Sie Uvicorn direkt ausführen würden, würden Sie anstelle von `--bind 0.0.0.0:80` (die Gunicorn-Option) stattdessen `--host 0.0.0.0` und `--port 80` verwenden. + +In der Ausgabe können Sie sehen, dass die **PID** (Prozess-ID) jedes Prozesses angezeigt wird (es ist nur eine Zahl). + +Sie können sehen, dass: + +* Der Gunicorn **Prozessmanager** beginnt, mit der PID `19499` (in Ihrem Fall ist es eine andere Nummer). +* Dann beginnt er zu lauschen: `Listening at: http://0.0.0.0:80`. +* Dann erkennt er, dass er die Workerklasse `uvicorn.workers.UvicornWorker` verwenden muss. +* Und dann werden **4 Worker** gestartet, jeder mit seiner eigenen PID: `19511`, `19513`, `19514` und `19515`. + +Gunicorn würde sich bei Bedarf auch um die Verwaltung **beendeter Prozesse** und den **Neustart** von Prozessen kümmern, um die Anzahl der Worker aufrechtzuerhalten. Das hilft also teilweise beim **Neustarts**-Konzept aus der obigen Liste. + +Dennoch möchten Sie wahrscheinlich auch etwas außerhalb haben, um sicherzustellen, dass Gunicorn bei Bedarf **neu gestartet wird**, und er auch **beim Hochfahren ausgeführt wird**, usw. + +## Uvicorn mit Workern + +Uvicorn bietet ebenfalls die Möglichkeit, mehrere **Workerprozesse** zu starten und auszuführen. + +Dennoch sind die Fähigkeiten von Uvicorn zur Abwicklung von Workerprozessen derzeit eingeschränkter als die von Gunicorn. Wenn Sie also einen Prozessmanager auf dieser Ebene (auf der Python-Ebene) haben möchten, ist es vermutlich besser, es mit Gunicorn als Prozessmanager zu versuchen. + +Wie auch immer, Sie würden es so ausführen: + +<div class="termy"> + +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +<font color="#A6E22E">INFO</font>: Uvicorn running on <b>http://0.0.0.0:8080</b> (Press CTRL+C to quit) +<font color="#A6E22E">INFO</font>: Started parent process [<font color="#A1EFE4"><b>27365</b></font>] +<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27368</font>] +<font color="#A6E22E">INFO</font>: Waiting for application startup. +<font color="#A6E22E">INFO</font>: Application startup complete. +<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27369</font>] +<font color="#A6E22E">INFO</font>: Waiting for application startup. +<font color="#A6E22E">INFO</font>: Application startup complete. +<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27370</font>] +<font color="#A6E22E">INFO</font>: Waiting for application startup. +<font color="#A6E22E">INFO</font>: Application startup complete. +<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27367</font>] +<font color="#A6E22E">INFO</font>: Waiting for application startup. +<font color="#A6E22E">INFO</font>: Application startup complete. +``` + +</div> + +Die einzige neue Option hier ist `--workers`, die Uvicorn anweist, 4 Workerprozesse zu starten. + +Sie können auch sehen, dass die **PID** jedes Prozesses angezeigt wird, `27365` für den übergeordneten Prozess (dies ist der **Prozessmanager**) und eine für jeden Workerprozess: `27368`, `27369`, `27370` und `27367`. + +## Deployment-Konzepte + +Hier haben Sie gesehen, wie Sie mit **Gunicorn** (oder Uvicorn) **Uvicorn-Workerprozesse** verwalten, um die Ausführung der Anwendung zu **parallelisieren**, **mehrere Kerne** der CPU zu nutzen und in der Lage zu sein, **mehr Requests** zu bedienen. + +In der Liste der Deployment-Konzepte von oben würde die Verwendung von Workern hauptsächlich beim **Replikation**-Teil und ein wenig bei **Neustarts** helfen, aber Sie müssen sich trotzdem um die anderen kümmern: + +* **Sicherheit – HTTPS** +* **Beim Hochfahren ausführen** +* **Neustarts** +* Replikation (die Anzahl der laufenden Prozesse) +* **Arbeitsspeicher** +* **Schritte vor dem Start** + +## Container und Docker + +Im nächsten Kapitel über [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank} werde ich einige Strategien erläutern, die Sie für den Umgang mit den anderen **Deployment-Konzepten** verwenden können. + +Ich zeige Ihnen auch das **offizielle Docker-Image**, welches **Gunicorn mit Uvicorn-Workern** und einige Standardkonfigurationen enthält, die für einfache Fälle nützlich sein können. + +Dort zeige ich Ihnen auch, wie Sie **Ihr eigenes Image von Grund auf erstellen**, um einen einzelnen Uvicorn-Prozess (ohne Gunicorn) auszuführen. Es ist ein einfacher Vorgang und wahrscheinlich das, was Sie tun möchten, wenn Sie ein verteiltes Containerverwaltungssystem wie **Kubernetes** verwenden. + +## Zusammenfassung + +Sie können **Gunicorn** (oder auch Uvicorn) als Prozessmanager mit Uvicorn-Workern verwenden, um **Multikern-CPUs** zu nutzen und **mehrere Prozesse parallel** auszuführen. + +Sie können diese Tools und Ideen nutzen, wenn Sie **Ihr eigenes Deployment-System** einrichten und sich dabei selbst um die anderen Deployment-Konzepte kümmern. + +Schauen Sie sich das nächste Kapitel an, um mehr über **FastAPI** mit Containern (z. B. Docker und Kubernetes) zu erfahren. Sie werden sehen, dass diese Tools auch einfache Möglichkeiten bieten, die anderen **Deployment-Konzepte** zu lösen. ✨ From fd90e3541edcaae56eed1e2783e1fe12ea063c31 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:21:03 +0000 Subject: [PATCH 160/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index df82cd9ad..79d5da626 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/security/simple-oauth2.md`. PR [#10504](https://github.com/tiangolo/fastapi/pull/10504) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/get-current-user.md`. PR [#10439](https://github.com/tiangolo/fastapi/pull/10439) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-forms-and-files.md`. PR [#10368](https://github.com/tiangolo/fastapi/pull/10368) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/encoder.md`. PR [#10385](https://github.com/tiangolo/fastapi/pull/10385) by [@nilslindemann](https://github.com/nilslindemann). From 52f483c91c9ad91095daee049f5f475350cfae83 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:21:32 +0000 Subject: [PATCH 161/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 79d5da626..7272ebdfc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/extra-data-types.md`. PR [#10534](https://github.com/tiangolo/fastapi/pull/10534) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/simple-oauth2.md`. PR [#10504](https://github.com/tiangolo/fastapi/pull/10504) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/get-current-user.md`. PR [#10439](https://github.com/tiangolo/fastapi/pull/10439) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/request-forms-and-files.md`. PR [#10368](https://github.com/tiangolo/fastapi/pull/10368) by [@nilslindemann](https://github.com/nilslindemann). From 427acc0db37f82c71a6733e928a1a3f231ee4b4d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:22:18 +0000 Subject: [PATCH 162/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7272ebdfc..6df823c67 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#10411](https://github.com/tiangolo/fastapi/pull/10411) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/extra-data-types.md`. PR [#10534](https://github.com/tiangolo/fastapi/pull/10534) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/simple-oauth2.md`. PR [#10504](https://github.com/tiangolo/fastapi/pull/10504) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/get-current-user.md`. PR [#10439](https://github.com/tiangolo/fastapi/pull/10439) by [@nilslindemann](https://github.com/nilslindemann). From ac3e8da01c4675037f043591a2d057e99659789f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:22:53 +0000 Subject: [PATCH 163/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6df823c67..2cdd6ee24 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/security/index.md`. PR [#10429](https://github.com/tiangolo/fastapi/pull/10429) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#10411](https://github.com/tiangolo/fastapi/pull/10411) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/extra-data-types.md`. PR [#10534](https://github.com/tiangolo/fastapi/pull/10534) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/simple-oauth2.md`. PR [#10504](https://github.com/tiangolo/fastapi/pull/10504) by [@nilslindemann](https://github.com/nilslindemann). From 3d9f95cf78b95515f70e994209215e274332f8f7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:23:38 +0000 Subject: [PATCH 164/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2cdd6ee24..5deac8478 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10409](https://github.com/tiangolo/fastapi/pull/10409) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/index.md`. PR [#10429](https://github.com/tiangolo/fastapi/pull/10429) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#10411](https://github.com/tiangolo/fastapi/pull/10411) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/extra-data-types.md`. PR [#10534](https://github.com/tiangolo/fastapi/pull/10534) by [@nilslindemann](https://github.com/nilslindemann). From 143fd39756a469335724554cfeaa05595a2e1e2d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:24:12 +0000 Subject: [PATCH 165/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5deac8478..24a7a0b01 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update German translation for `docs/de/docs/fastapi-people.md`. PR [#10285](https://github.com/tiangolo/fastapi/pull/10285) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10409](https://github.com/tiangolo/fastapi/pull/10409) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/index.md`. PR [#10429](https://github.com/tiangolo/fastapi/pull/10429) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#10411](https://github.com/tiangolo/fastapi/pull/10411) by [@nilslindemann](https://github.com/nilslindemann). From e1a7c03c4d121c8bfc94ff544df877bdd253cd72 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:25:00 +0000 Subject: [PATCH 166/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 24a7a0b01..bfd2ebd66 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/global-dependencies.md`. PR [#10420](https://github.com/tiangolo/fastapi/pull/10420) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/fastapi-people.md`. PR [#10285](https://github.com/tiangolo/fastapi/pull/10285) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10409](https://github.com/tiangolo/fastapi/pull/10409) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/index.md`. PR [#10429](https://github.com/tiangolo/fastapi/pull/10429) by [@nilslindemann](https://github.com/nilslindemann). From e4570cafc0619fcad467c3b3082e67afe1f53c32 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:25:52 +0000 Subject: [PATCH 167/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bfd2ebd66..df6f032c2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10422](https://github.com/tiangolo/fastapi/pull/10422) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/global-dependencies.md`. PR [#10420](https://github.com/tiangolo/fastapi/pull/10420) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/fastapi-people.md`. PR [#10285](https://github.com/tiangolo/fastapi/pull/10285) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10409](https://github.com/tiangolo/fastapi/pull/10409) by [@nilslindemann](https://github.com/nilslindemann). From dcb935e4862a9ba441c147d8b64881c694d8fd7d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:28:28 +0000 Subject: [PATCH 168/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index df6f032c2..f6d7e1995 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/history-design-future.md`. PR [#10865](https://github.com/tiangolo/fastapi/pull/10865) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10422](https://github.com/tiangolo/fastapi/pull/10422) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/global-dependencies.md`. PR [#10420](https://github.com/tiangolo/fastapi/pull/10420) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/fastapi-people.md`. PR [#10285](https://github.com/tiangolo/fastapi/pull/10285) by [@nilslindemann](https://github.com/nilslindemann). From 47412a4c254efe8718b4b03ce920881737def6da Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:32:40 +0000 Subject: [PATCH 169/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f6d7e1995..1e3384ae5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/project-generation.md`. PR [#10851](https://github.com/tiangolo/fastapi/pull/10851) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/history-design-future.md`. PR [#10865](https://github.com/tiangolo/fastapi/pull/10865) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10422](https://github.com/tiangolo/fastapi/pull/10422) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/global-dependencies.md`. PR [#10420](https://github.com/tiangolo/fastapi/pull/10420) by [@nilslindemann](https://github.com/nilslindemann). From 5c8292af8beec0cb80cb8e79c9c1ef69105b4e38 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:33:30 +0000 Subject: [PATCH 170/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1e3384ae5..936fd5090 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/testclient.md`. PR [#10843](https://github.com/tiangolo/fastapi/pull/10843) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/project-generation.md`. PR [#10851](https://github.com/tiangolo/fastapi/pull/10851) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/history-design-future.md`. PR [#10865](https://github.com/tiangolo/fastapi/pull/10865) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10422](https://github.com/tiangolo/fastapi/pull/10422) by [@nilslindemann](https://github.com/nilslindemann). From 2cfba8a371c74011c88308542ca232155e90d802 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:34:13 +0000 Subject: [PATCH 171/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 936fd5090..1b3980663 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/staticfiles.md`. PR [#10841](https://github.com/tiangolo/fastapi/pull/10841) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/testclient.md`. PR [#10843](https://github.com/tiangolo/fastapi/pull/10843) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/project-generation.md`. PR [#10851](https://github.com/tiangolo/fastapi/pull/10851) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/history-design-future.md`. PR [#10865](https://github.com/tiangolo/fastapi/pull/10865) by [@nilslindemann](https://github.com/nilslindemann). From b8d7dda04cde16f2377de844f54b2f960ae7371f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:34:52 +0000 Subject: [PATCH 172/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1b3980663..1a07cb80e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/security/index.md`. PR [#10839](https://github.com/tiangolo/fastapi/pull/10839) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/staticfiles.md`. PR [#10841](https://github.com/tiangolo/fastapi/pull/10841) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/testclient.md`. PR [#10843](https://github.com/tiangolo/fastapi/pull/10843) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/project-generation.md`. PR [#10851](https://github.com/tiangolo/fastapi/pull/10851) by [@nilslindemann](https://github.com/nilslindemann). From fe884959cd306146b433f2d96ac4fa1c0a1908a5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:35:29 +0000 Subject: [PATCH 173/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1a07cb80e..07daaf48a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/openapi/*.md`. PR [#10838](https://github.com/tiangolo/fastapi/pull/10838) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/security/index.md`. PR [#10839](https://github.com/tiangolo/fastapi/pull/10839) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/staticfiles.md`. PR [#10841](https://github.com/tiangolo/fastapi/pull/10841) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/testclient.md`. PR [#10843](https://github.com/tiangolo/fastapi/pull/10843) by [@nilslindemann](https://github.com/nilslindemann). From d7ddf9989a3c1b4dd561017c5e920fd6a4e21af4 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:36:51 +0000 Subject: [PATCH 174/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 07daaf48a..9f1b9bd83 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/middleware.md`. PR [#10837](https://github.com/tiangolo/fastapi/pull/10837) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/openapi/*.md`. PR [#10838](https://github.com/tiangolo/fastapi/pull/10838) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/security/index.md`. PR [#10839](https://github.com/tiangolo/fastapi/pull/10839) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/staticfiles.md`. PR [#10841](https://github.com/tiangolo/fastapi/pull/10841) by [@nilslindemann](https://github.com/nilslindemann). From 05a0d04115173e09347346eb30067350191599e1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:37:25 +0000 Subject: [PATCH 175/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9f1b9bd83..b7033780a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/response.md`. PR [#10824](https://github.com/tiangolo/fastapi/pull/10824) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/middleware.md`. PR [#10837](https://github.com/tiangolo/fastapi/pull/10837) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/openapi/*.md`. PR [#10838](https://github.com/tiangolo/fastapi/pull/10838) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/security/index.md`. PR [#10839](https://github.com/tiangolo/fastapi/pull/10839) by [@nilslindemann](https://github.com/nilslindemann). From 9f955fe6c50bf28abc6bede93029696d4704eedb Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:38:10 +0000 Subject: [PATCH 176/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b7033780a..2020232ed 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/httpconnection.md`. PR [#10823](https://github.com/tiangolo/fastapi/pull/10823) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/response.md`. PR [#10824](https://github.com/tiangolo/fastapi/pull/10824) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/middleware.md`. PR [#10837](https://github.com/tiangolo/fastapi/pull/10837) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/openapi/*.md`. PR [#10838](https://github.com/tiangolo/fastapi/pull/10838) by [@nilslindemann](https://github.com/nilslindemann). From 779b5953a2dc0cb9ba7b7127ac4b985e572a7f17 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:38:38 +0000 Subject: [PATCH 177/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2020232ed..efe5002f3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/websockets.md`. PR [#10822](https://github.com/tiangolo/fastapi/pull/10822) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/httpconnection.md`. PR [#10823](https://github.com/tiangolo/fastapi/pull/10823) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/response.md`. PR [#10824](https://github.com/tiangolo/fastapi/pull/10824) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/middleware.md`. PR [#10837](https://github.com/tiangolo/fastapi/pull/10837) by [@nilslindemann](https://github.com/nilslindemann). From a01f0812db1e7793c72dfb6ac2ac00c0aea61f05 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:39:28 +0000 Subject: [PATCH 178/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index efe5002f3..6ea72d6b0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/apirouter.md`. PR [#10819](https://github.com/tiangolo/fastapi/pull/10819) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/websockets.md`. PR [#10822](https://github.com/tiangolo/fastapi/pull/10822) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/httpconnection.md`. PR [#10823](https://github.com/tiangolo/fastapi/pull/10823) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/response.md`. PR [#10824](https://github.com/tiangolo/fastapi/pull/10824) by [@nilslindemann](https://github.com/nilslindemann). From 8baf7ca16db3e21ca84a4be0053e3af40b0b1731 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:40:06 +0000 Subject: [PATCH 179/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6ea72d6b0..8e5172b68 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/dependencies.md`. PR [#10818](https://github.com/tiangolo/fastapi/pull/10818) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/apirouter.md`. PR [#10819](https://github.com/tiangolo/fastapi/pull/10819) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/websockets.md`. PR [#10822](https://github.com/tiangolo/fastapi/pull/10822) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/httpconnection.md`. PR [#10823](https://github.com/tiangolo/fastapi/pull/10823) by [@nilslindemann](https://github.com/nilslindemann). From 0647300131e1128334709ea9cbfef9f870c80c83 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:40:38 +0000 Subject: [PATCH 180/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8e5172b68..4203fbf3d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/exceptions.md`. PR [#10817](https://github.com/tiangolo/fastapi/pull/10817) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/dependencies.md`. PR [#10818](https://github.com/tiangolo/fastapi/pull/10818) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/apirouter.md`. PR [#10819](https://github.com/tiangolo/fastapi/pull/10819) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/websockets.md`. PR [#10822](https://github.com/tiangolo/fastapi/pull/10822) by [@nilslindemann](https://github.com/nilslindemann). From 0a764f2bfc2e4905408e92d4bbf67458df73c97c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:42:00 +0000 Subject: [PATCH 181/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4203fbf3d..1508a9321 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/uploadfile.md`. PR [#10816](https://github.com/tiangolo/fastapi/pull/10816) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/exceptions.md`. PR [#10817](https://github.com/tiangolo/fastapi/pull/10817) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/dependencies.md`. PR [#10818](https://github.com/tiangolo/fastapi/pull/10818) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/apirouter.md`. PR [#10819](https://github.com/tiangolo/fastapi/pull/10819) by [@nilslindemann](https://github.com/nilslindemann). From 388de5c7e6aeb6a05e8a806fa8fb3f49b89ae697 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:42:40 +0000 Subject: [PATCH 182/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1508a9321..e3d32cdd3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/status.md`. PR [#10815](https://github.com/tiangolo/fastapi/pull/10815) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/uploadfile.md`. PR [#10816](https://github.com/tiangolo/fastapi/pull/10816) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/exceptions.md`. PR [#10817](https://github.com/tiangolo/fastapi/pull/10817) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/dependencies.md`. PR [#10818](https://github.com/tiangolo/fastapi/pull/10818) by [@nilslindemann](https://github.com/nilslindemann). From 89c4c7ec6e3e7023b3b4b347802b69543683617f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:43:20 +0000 Subject: [PATCH 183/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e3d32cdd3..c83827f8a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/reference/parameters.md`. PR [#10814](https://github.com/tiangolo/fastapi/pull/10814) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/status.md`. PR [#10815](https://github.com/tiangolo/fastapi/pull/10815) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/uploadfile.md`. PR [#10816](https://github.com/tiangolo/fastapi/pull/10816) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/exceptions.md`. PR [#10817](https://github.com/tiangolo/fastapi/pull/10817) by [@nilslindemann](https://github.com/nilslindemann). From 1b7851e2e8ef4cd5ee00a9b1c9e398a9c6426b9c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:44:02 +0000 Subject: [PATCH 184/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c83827f8a..73af979e1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/custom-docs-ui-assets.md`. PR [#10803](https://github.com/tiangolo/fastapi/pull/10803) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/parameters.md`. PR [#10814](https://github.com/tiangolo/fastapi/pull/10814) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/status.md`. PR [#10815](https://github.com/tiangolo/fastapi/pull/10815) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/uploadfile.md`. PR [#10816](https://github.com/tiangolo/fastapi/pull/10816) by [@nilslindemann](https://github.com/nilslindemann). From 7a3d9a0a0392c88befbd985be6aa6e8a7fbe5a34 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:45:27 +0000 Subject: [PATCH 185/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 73af979e1..2f7274f3a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#10804](https://github.com/tiangolo/fastapi/pull/10804) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/custom-docs-ui-assets.md`. PR [#10803](https://github.com/tiangolo/fastapi/pull/10803) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/parameters.md`. PR [#10814](https://github.com/tiangolo/fastapi/pull/10814) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/status.md`. PR [#10815](https://github.com/tiangolo/fastapi/pull/10815) by [@nilslindemann](https://github.com/nilslindemann). From 3725bfbf5f3291bdfff9879bd6c88e9f91302496 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:46:01 +0000 Subject: [PATCH 186/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f7274f3a..a630da658 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/separate-openapi-schemas.md`. PR [#10796](https://github.com/tiangolo/fastapi/pull/10796) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#10804](https://github.com/tiangolo/fastapi/pull/10804) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/custom-docs-ui-assets.md`. PR [#10803](https://github.com/tiangolo/fastapi/pull/10803) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/reference/parameters.md`. PR [#10814](https://github.com/tiangolo/fastapi/pull/10814) by [@nilslindemann](https://github.com/nilslindemann). From e5750e55ee96b35f6ed5cb498c50183461fdc6ee Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:46:43 +0000 Subject: [PATCH 187/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a630da658..8e4be0e98 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/conditional-openapi.md`. PR [#10790](https://github.com/tiangolo/fastapi/pull/10790) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/separate-openapi-schemas.md`. PR [#10796](https://github.com/tiangolo/fastapi/pull/10796) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#10804](https://github.com/tiangolo/fastapi/pull/10804) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/custom-docs-ui-assets.md`. PR [#10803](https://github.com/tiangolo/fastapi/pull/10803) by [@nilslindemann](https://github.com/nilslindemann). From bf47ce1d18e709d57ee7efdf825c3c7b6a6d2f3f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:47:24 +0000 Subject: [PATCH 188/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8e4be0e98..5e2b09744 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/custom-request-and-route.md`. PR [#10789](https://github.com/tiangolo/fastapi/pull/10789) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/conditional-openapi.md`. PR [#10790](https://github.com/tiangolo/fastapi/pull/10790) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/separate-openapi-schemas.md`. PR [#10796](https://github.com/tiangolo/fastapi/pull/10796) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#10804](https://github.com/tiangolo/fastapi/pull/10804) by [@nilslindemann](https://github.com/nilslindemann). From 307d19e93da9d75e1901d4a5a5d4283740774a16 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:48:05 +0000 Subject: [PATCH 189/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5e2b09744..6f04467a9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/graphql.md`. PR [#10788](https://github.com/tiangolo/fastapi/pull/10788) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/custom-request-and-route.md`. PR [#10789](https://github.com/tiangolo/fastapi/pull/10789) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/conditional-openapi.md`. PR [#10790](https://github.com/tiangolo/fastapi/pull/10790) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/separate-openapi-schemas.md`. PR [#10796](https://github.com/tiangolo/fastapi/pull/10796) by [@nilslindemann](https://github.com/nilslindemann). From 96b884a477f495d9bad14504db7fcd2e31f225b9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:48:51 +0000 Subject: [PATCH 190/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6f04467a9..2889a563d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/general.md`. PR [#10770](https://github.com/tiangolo/fastapi/pull/10770) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/graphql.md`. PR [#10788](https://github.com/tiangolo/fastapi/pull/10788) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/custom-request-and-route.md`. PR [#10789](https://github.com/tiangolo/fastapi/pull/10789) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/conditional-openapi.md`. PR [#10790](https://github.com/tiangolo/fastapi/pull/10790) by [@nilslindemann](https://github.com/nilslindemann). From 264f21653986d301fc27e091cbc29a78894a6b32 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:49:37 +0000 Subject: [PATCH 191/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2889a563d..46c68df8a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/how-to/index.md`. PR [#10769](https://github.com/tiangolo/fastapi/pull/10769) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/general.md`. PR [#10770](https://github.com/tiangolo/fastapi/pull/10770) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/graphql.md`. PR [#10788](https://github.com/tiangolo/fastapi/pull/10788) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/custom-request-and-route.md`. PR [#10789](https://github.com/tiangolo/fastapi/pull/10789) by [@nilslindemann](https://github.com/nilslindemann). From 39b222a0b5e9912f6bf228f9b9f1db1f6e348ddd Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:52:02 +0000 Subject: [PATCH 192/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 46c68df8a..5c22e8280 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/docker.md`. PR [#10759](https://github.com/tiangolo/fastapi/pull/10759) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/index.md`. PR [#10769](https://github.com/tiangolo/fastapi/pull/10769) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/general.md`. PR [#10770](https://github.com/tiangolo/fastapi/pull/10770) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/graphql.md`. PR [#10788](https://github.com/tiangolo/fastapi/pull/10788) by [@nilslindemann](https://github.com/nilslindemann). From 9d6aa67dd1073a446f424a20cf3c1705533e48bf Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 18:52:38 +0000 Subject: [PATCH 193/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5c22e8280..00cf21f45 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/server-workers.md`. PR [#10747](https://github.com/tiangolo/fastapi/pull/10747) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/docker.md`. PR [#10759](https://github.com/tiangolo/fastapi/pull/10759) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/index.md`. PR [#10769](https://github.com/tiangolo/fastapi/pull/10769) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/general.md`. PR [#10770](https://github.com/tiangolo/fastapi/pull/10770) by [@nilslindemann](https://github.com/nilslindemann). From 4f29ce71102176b414aeec261d5612051232ac48 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 20:43:43 +0100 Subject: [PATCH 194/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20German=20transl?= =?UTF-8?q?ation=20for=20`docs/de/docs/features.md`=20(#10284)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/de/docs/features.md | 151 ++++++++++++++++++++------------------- 1 file changed, 77 insertions(+), 74 deletions(-) diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index fee4b158e..76aad9f16 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -1,21 +1,26 @@ +--- +hide: + - navigation +--- + # Merkmale ## FastAPI Merkmale -**FastAPI** ermöglicht Ihnen folgendes: +**FastAPI** ermöglicht Ihnen Folgendes: ### Basiert auf offenen Standards -* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> für API-Erstellung, zusammen mit Deklarationen von <abbr title="auch genannt: Endpunkte, Routen">Pfad</abbr> <abbr title="gemeint sind: HTTP-Methoden, wie POST, GET, PUT, DELETE">Operationen</abbr>, Parameter, Nachrichtenrumpf-Anfragen (englisch: body request), Sicherheit, etc. -* Automatische Dokumentation der Datenentitäten mit dem <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (OpenAPI basiert selber auf dem JSON Schema). -* Entworfen auf Grundlage dieser Standards nach einer sorgfältigen Studie, statt einer nachträglichen Schicht über diesen Standards. -* Dies ermöglicht automatische **Quellcode-Generierung auf Benutzerebene** in vielen Sprachen. +* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> für die Erstellung von APIs, inklusive Deklarationen von <abbr title="auch genannt Endpunkte, Routen">Pfad</abbr>-<abbr title="gemeint sind HTTP-Methoden wie POST, GET, PUT, DELETE">Operationen</abbr>, Parametern, Body-Anfragen, Sicherheit, usw. +* Automatische Dokumentation der Datenmodelle mit <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (da OpenAPI selbst auf JSON Schema basiert). +* Um diese Standards herum entworfen, nach sorgfältigem Studium. Statt einer nachträglichen Schicht darüber. +* Dies ermöglicht auch automatische **Client-Code-Generierung** in vielen Sprachen. ### Automatische Dokumentation -Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzerschnittstellen. Da FastAPI auf OpenAPI basiert, gibt es hierzu mehrere Optionen, wobei zwei standardmäßig vorhanden sind. +Interaktive API-Dokumentation und erkundbare Web-Benutzeroberflächen. Da das Framework auf OpenAPI basiert, gibt es mehrere Optionen, zwei sind standardmäßig vorhanden. -* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank"><strong>Swagger UI</strong></a>, bietet interaktive Exploration: testen und rufen Sie ihre API direkt vom Webbrowser auf. +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank"><strong>Swagger UI</strong></a>, bietet interaktive Erkundung, testen und rufen Sie ihre API direkt im Webbrowser auf.  @@ -27,11 +32,9 @@ Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzers Alles basiert auf **Python 3.8 Typ**-Deklarationen (dank Pydantic). Es muss keine neue Syntax gelernt werden, nur standardisiertes modernes Python. +Wenn Sie eine zweiminütige Auffrischung benötigen, wie man Python-Typen verwendet (auch wenn Sie FastAPI nicht benutzen), schauen Sie sich das kurze Tutorial an: [Einführung in Python-Typen](python-types.md){.internal-link target=_blank}. - -Wenn Sie eine kurze, zweiminütige, Auffrischung in der Benutzung von Python Typ-Deklarationen benötigen (auch wenn Sie FastAPI nicht nutzen), schauen Sie sich diese kurze Einführung an (Englisch): Python Types{.internal-link target=_blank}. - -Sie schreiben Standard-Python mit Typ-Deklarationen: +Sie schreiben Standard-Python mit Typen: ```Python from typing import List, Dict @@ -39,20 +42,20 @@ from datetime import date from pydantic import BaseModel -# Deklariere eine Variable als str -# und bekomme Editor-Unterstütung innerhalb der Funktion +# Deklarieren Sie eine Variable als ein `str` +# und bekommen Sie Editor-Unterstütung innerhalb der Funktion def main(user_id: str): return user_id -# Ein Pydantic model +# Ein Pydantic-Modell class User(BaseModel): id: int name: str joined: date ``` -Dies kann nun wiefolgt benutzt werden: +Das kann nun wie folgt verwendet werden: ```Python my_user: User = User(id=3, name="John Doe", joined="2018-07-19") @@ -69,133 +72,133 @@ my_second_user: User = User(**second_user_data) !!! info `**second_user_data` bedeutet: - Übergebe die Schlüssel und die zugehörigen Werte des `second_user_data` Datenwörterbuches direkt als Schlüssel-Wert Argumente, äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")` + Nimm die Schlüssel-Wert-Paare des `second_user_data` <abbr title="Dictionary – Wörterbuch: In anderen Programmiersprachen auch Hash, Map, Objekt, Assoziatives Array genannt">Dicts</abbr> und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. ### Editor Unterstützung -FastAPI wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet (sogar vor der eigentlichen Implementierung), um so eine best mögliche Entwicklererfahrung zu gewährleisten. +Das ganze Framework wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet, sogar vor der Implementierung, um die bestmögliche Entwicklererfahrung zu gewährleisten. -In der letzen Python Entwickler Umfrage stellte sich heraus, dass <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">die meist genutzte Funktion die "Autovervollständigung" ist</a>. +In der letzten Python-Entwickler-Umfrage wurde klar, <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">dass die meist genutzte Funktion die „Autovervollständigung“ ist</a>. -Die gesamte Struktur von **FastAPI** soll dem gerecht werden. Autovervollständigung funktioniert überall. +Das gesamte **FastAPI**-Framework ist darauf ausgelegt, das zu erfüllen. Autovervollständigung funktioniert überall. -Sie müssen selten in die Dokumentation schauen. +Sie werden selten noch mal in der Dokumentation nachschauen müssen. So kann ihr Editor Sie unterstützen: * in <a href="https://code.visualstudio.com/" class="external-link" target="_blank">Visual Studio Code</a>: - + * in <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>: - + -Sie bekommen Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel aus einem JSON Datensatz (dieser könnte auch verschachtelt sein) aus einer Anfrage. +Sie bekommen sogar Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel in einem JSON Datensatz (dieser könnte auch verschachtelt sein), der aus einer Anfrage kommt. -Hierdurch werden Sie nie wieder einen falschen Schlüsselnamen benutzen und sparen sich lästiges Suchen in der Dokumentation, um beispielsweise herauszufinden ob Sie `username` oder `user_name` als Schlüssel verwenden. +Nie wieder falsche Schlüsselnamen tippen, Hin und Herhüpfen zwischen der Dokumentation, Hoch- und Runterscrollen, um herauszufinden, ob es `username` oder `user_name` war. ### Kompakt -FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen. +Es gibt für alles sensible **Defaultwerte**, mit optionaler Konfiguration überall. Alle Parameter können feinjustiert werden, damit sie tun, was Sie benötigen, und die API definieren, die Sie brauchen. -Aber standardmäßig, **"funktioniert einfach"** alles. +Aber standardmäßig **„funktioniert einfach alles“**. ### Validierung -* Validierung für die meisten (oder alle?) Python **Datentypen**, hierzu gehören: +* Validierung für die meisten (oder alle?) Python-**Datentypen**, hierzu gehören: * JSON Objekte (`dict`). * JSON Listen (`list`), die den Typ ihrer Elemente definieren. - * Zeichenketten (`str`), mit definierter minimaler und maximaler Länge. - * Zahlen (`int`, `float`) mit minimaler und maximaler Größe, usw. + * Strings (`str`) mit definierter minimaler und maximaler Länge. + * Zahlen (`int`, `float`) mit Mindest- und Maximal-Werten, usw. -* Validierung für ungewöhnliche Typen, wie: +* Validierung für mehr exotische Typen, wie: * URL. - * Email. + * E-Mail. * UUID. * ... und andere. -Die gesamte Validierung übernimmt das etablierte und robuste **Pydantic**. +Die gesamte Validierung übernimmt das gut etablierte und robuste **Pydantic**. ### Sicherheit und Authentifizierung -Integrierte Sicherheit und Authentifizierung. Ohne Kompromisse bei Datenbanken oder Datenmodellen. +Sicherheit und Authentifizierung ist integriert. Ohne Kompromisse bei Datenbanken oder Datenmodellen. -Unterstützt werden alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören: +Alle in OpenAPI definierten Sicherheitsschemas, inklusive: -* HTTP Basis Authentifizierung. -* **OAuth2** (auch mit **JWT Zugriffstokens**). Schauen Sie sich hierzu dieses Tutorial an: [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* HTTP Basic Authentifizierung. +* **OAuth2** (auch mit **JWT Tokens**). Siehe dazu das Tutorial zu [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. * API Schlüssel in: - * Kopfzeile (HTTP Header). + * Header-Feldern. * Anfrageparametern. - * Cookies, etc. + * Cookies, usw. -Zusätzlich gibt es alle Sicherheitsfunktionen von Starlette (auch **session cookies**). +Zusätzlich alle Sicherheitsfunktionen von Starlette (inklusive **Session Cookies**). -Alles wurde als wiederverwendbare Werkzeuge und Komponenten geschaffen, die einfach in ihre Systeme, Datenablagen, relationale und nicht-relationale Datenbanken, ..., integriert werden können. +Alles als wiederverwendbare Tools und Komponenten gebaut, die einfach in ihre Systeme, Datenspeicher, relationalen und nicht-relationalen Datenbanken, usw., integriert werden können. -### Einbringen von Abhängigkeiten (meist: Dependency Injection) +### Einbringen von Abhängigkeiten (Dependency Injection) -FastAPI enthält ein extrem einfaches, aber extrem mächtiges <abbr title='oft verwendet im Zusammenhang von: Komponenten, Resourcen, Diensten, Dienstanbieter'><strong>Dependency Injection</strong></abbr> System. +FastAPI enthält ein extrem einfach zu verwendendes, aber extrem mächtiges <abbr title='Dependency Injection – Einbringen von Abhängigkeiten: Auch bekannt als Komponenten, Resourcen, Dienste, Dienstanbieter'><strong>Dependency Injection</strong></abbr> System. -* Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierachie oder ein **"Graph" von Abhängigkeiten** entsteht. -* **Automatische Umsetzung** durch FastAPI. -* Alle abhängigen Komponenten könnten Daten von Anfragen, **Erweiterungen der Pfadoperations-**Einschränkungen und der automatisierten Dokumentation benötigen. -* **Automatische Validierung** selbst für *Pfadoperationen*-Parameter, die in den Abhängigkeiten definiert wurden. -* Unterstützt komplexe Benutzerauthentifizierungssysteme, **Datenbankverbindungen**, usw. -* **Keine Kompromisse** bei Datenbanken, Eingabemasken, usw. Sondern einfache Integration von allen. +* Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierarchie oder ein **„Graph“ von Abhängigkeiten** entsteht. +* Alles **automatisch gehandhabt** durch das Framework. +* Alle Abhängigkeiten können Daten von Anfragen anfordern und das Verhalten von **Pfadoperationen** und der automatisierten Dokumentation **modifizieren**. +* **Automatische Validierung** selbst für solche Parameter von *Pfadoperationen*, welche in Abhängigkeiten definiert sind. +* Unterstützung für komplexe Authentifizierungssysteme, **Datenbankverbindungen**, usw. +* **Keine Kompromisse** bei Datenbanken, Frontends, usw., sondern einfache Integration mit allen. ### Unbegrenzte Erweiterungen -Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie Quellcode nach Bedarf. +Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie den Code, den Sie brauchen. -Jede Integration wurde so entworfen, dass sie einfach zu nutzen ist (mit Abhängigkeiten), sodass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen an Quellcode implementieren können. Hierbei nutzen Sie die selbe Struktur und Syntax, wie bei Pfadoperationen. +Jede Integration wurde so entworfen, dass sie so einfach zu nutzen ist (mit Abhängigkeiten), dass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen Code erstellen können. Hierbei nutzen Sie die gleiche Struktur und Syntax, wie bei *Pfadoperationen*. ### Getestet -* 100% <abbr title="Die Anzahl an Code, die automatisch getestet wird">Testabdeckung</abbr>. -* 100% <abbr title="Python Typ Annotationen, mit dennen Ihr Editor und andere exteren Werkezuge Sie besser unterstützen können">Typen annotiert</abbr>. +* 100 % <abbr title="Der Prozentsatz an Code, der automatisch getestet wird">Testabdeckung</abbr>. +* 100 % <abbr title="Python-Typannotationen, mit denen Ihr Editor und andere exteren Werkezuge Sie besser unterstützen können">Typen annotiert</abbr>. * Verwendet in Produktionsanwendungen. ## Starlette's Merkmale -**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://www.starlette.io/" class="external-link" target="_blank"><strong>Starlette</strong></a>. Das bedeutet, auch ihr eigener Starlette Quellcode funktioniert. +**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://www.starlette.io/" class="external-link" target="_blank"><strong>Starlette</strong></a>. Das bedeutet, wenn Sie eigenen Starlette Quellcode haben, funktioniert der. -`FastAPI` ist eigentlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, können Sie das meiste Ihres Wissens direkt anwenden. +`FastAPI` ist tatsächlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, das meiste funktioniert genau so. -Mit **FastAPI** bekommen Sie viele von **Starlette**'s Funktionen (da FastAPI nur Starlette auf Steroiden ist): +Mit **FastAPI** bekommen Sie alles von **Starlette** (da FastAPI nur Starlette auf Steroiden ist): -* Stark beeindruckende Performanz. Es ist <a href="https://github.com/encode/starlette#performance" class="external-link" target="_blank">eines der schnellsten Python Frameworks, auf Augenhöhe mit **NodeJS** und **Go**</a>. +* Schwer beeindruckende Performanz. Es ist <a href="https://github.com/encode/starlette#performance" class="external-link" target="_blank">eines der schnellsten Python-Frameworks, auf Augenhöhe mit **NodeJS** und **Go**</a>. * **WebSocket**-Unterstützung. * Hintergrundaufgaben im selben Prozess. -* Ereignisse für das Starten und Herunterfahren. -* Testclient basierend auf HTTPX. -* **CORS**, GZip, statische Dateien, Antwortfluss. -* **Sitzungs und Cookie** Unterstützung. -* 100% Testabdeckung. -* 100% Typen annotiert. +* Ereignisse beim Starten und Herunterfahren. +* Testclient baut auf HTTPX auf. +* **CORS**, GZip, statische Dateien, Responses streamen. +* **Sitzungs- und Cookie**-Unterstützung. +* 100 % Testabdeckung. +* 100 % Typen annotierte Codebasis. ## Pydantic's Merkmale -**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Das bedeutet, auch jeder zusätzliche Pydantic Quellcode funktioniert. +**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Das bedeutet, wenn Sie eigenen Pydantic Quellcode haben, funktioniert der. -Verfügbar sind ebenso externe auf Pydantic basierende Bibliotheken, wie <abbr title="Object-Relational Mapper (Abbildung von Objekten auf relationale Strukturen)">ORM</abbr>s, <abbr title="Object-Document Mapper (Abbildung von Objekten auf nicht-relationale Strukturen)">ODM</abbr>s für Datenbanken. +Inklusive externer Bibliotheken, die auf Pydantic basieren, wie <abbr title="Object-Relational Mapper (Abbildung von Objekten auf relationale Strukturen)">ORM</abbr>s, <abbr title="Object-Document Mapper (Abbildung von Objekten auf nicht-relationale Strukturen)">ODM</abbr>s für Datenbanken. Daher können Sie in vielen Fällen das Objekt einer Anfrage **direkt zur Datenbank** schicken, weil alles automatisch validiert wird. -Das selbe gilt auch für die andere Richtung: Sie können jedes Objekt aus der Datenbank **direkt zum Klienten** schicken. +Das gleiche gilt auch für die andere Richtung: Sie können in vielen Fällen das Objekt aus der Datenbank **direkt zum Client** schicken. Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für die gesamte Datenverarbeitung Pydantic nutzt): * **Kein Kopfzerbrechen**: - * Sie müssen keine neue Schemadefinitionssprache lernen. - * Wenn Sie mit Python's Typisierung arbeiten können, können Sie auch mit Pydantic arbeiten. -* Gutes Zusammenspiel mit Ihrer/Ihrem **<abbr title="Integrierten Entwicklungsumgebung, ähnlich zu (Quellcode-)Editor">IDE</abbr>/<abbr title="Ein Programm, was Fehler im Quellcode sucht">linter</abbr>/Gehirn**: - * Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren. + * Keine neue Schemadefinition-Mikrosprache zu lernen. + * Wenn Sie Pythons Typen kennen, wissen Sie, wie man Pydantic verwendet. +* Gutes Zusammenspiel mit Ihrer/Ihrem **<abbr title="Integrierten Entwicklungsumgebung, ähnlich zu (Quellcode-)Editor">IDE</abbr>/<abbr title="Ein Programm, was Fehler im Quellcode sucht">Linter</abbr>/Gehirn**: + * Weil Pydantics Datenstrukturen einfach nur Instanzen ihrer definierten Klassen sind; Autovervollständigung, Linting, mypy und ihre Intuition sollten alle einwandfrei mit ihren validierten Daten funktionieren. * Validierung von **komplexen Strukturen**: - * Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc. - * Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema. - * Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert. + * Benutzung von hierarchischen Pydantic-Modellen, Python-`typing`s `List` und `Dict`, etc. + * Die Validierer erlauben es, komplexe Datenschemen klar und einfach zu definieren, überprüft und dokumentiert als JSON Schema. + * Sie können tief **verschachtelte JSON** Objekte haben, die alle validiert und annotiert sind. * **Erweiterbar**: - * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern. -* 100% Testabdeckung. + * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator`-dekorierten Methode im Modell erweitern. +* 100 % Testabdeckung. From e1a0c83fe3e560185cba63a7b97a6b80ddf28caa Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:16:25 +0100 Subject: [PATCH 195/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/concepts.md`=20(#10744)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/concepts.md | 311 ++++++++++++++++++++++++++++ 1 file changed, 311 insertions(+) create mode 100644 docs/de/docs/deployment/concepts.md diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md new file mode 100644 index 000000000..5e1a4f109 --- /dev/null +++ b/docs/de/docs/deployment/concepts.md @@ -0,0 +1,311 @@ +# Deployment-Konzepte + +Bei dem Deployment – der Bereitstellung – einer **FastAPI**-Anwendung, oder eigentlich jeder Art von Web-API, gibt es mehrere Konzepte, die Sie wahrscheinlich interessieren, und mithilfe der Sie die **am besten geeignete** Methode zur **Bereitstellung Ihrer Anwendung** finden können. + +Einige wichtige Konzepte sind: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +Wir werden sehen, wie diese sich auf das **Deployment** auswirken. + +Letztendlich besteht das ultimative Ziel darin, **Ihre API-Clients** auf **sichere** Weise zu bedienen, um **Unterbrechungen** zu vermeiden und die **Rechenressourcen** (z. B. entfernte Server/virtuelle Maschinen) so effizient wie möglich zu nutzen. 🚀 + +Ich erzähle Ihnen hier etwas mehr über diese **Konzepte**, was Ihnen hoffentlich die **Intuition** gibt, die Sie benötigen, um zu entscheiden, wie Sie Ihre API in sehr unterschiedlichen Umgebungen bereitstellen, möglicherweise sogar in **zukünftigen**, die jetzt noch nicht existieren. + +Durch die Berücksichtigung dieser Konzepte können Sie die beste Variante der Bereitstellung **Ihrer eigenen APIs** **evaluieren und konzipieren**. + +In den nächsten Kapiteln werde ich Ihnen mehr **konkrete Rezepte** für die Bereitstellung von FastAPI-Anwendungen geben. + +Aber schauen wir uns zunächst einmal diese grundlegenden **konzeptionellen Ideen** an. Diese Konzepte gelten auch für jede andere Art von Web-API. 💡 + +## Sicherheit – HTTPS + +Im [vorherigen Kapitel über HTTPS](https.md){.internal-link target=_blank} haben wir erfahren, wie HTTPS Verschlüsselung für Ihre API bereitstellt. + +Wir haben auch gesehen, dass HTTPS normalerweise von einer Komponente **außerhalb** Ihres Anwendungsservers bereitgestellt wird, einem **TLS-Terminierungsproxy**. + +Und es muss etwas geben, das für die **Erneuerung der HTTPS-Zertifikate** zuständig ist, es könnte sich um dieselbe Komponente handeln oder um etwas anderes. + +### Beispieltools für HTTPS + +Einige der Tools, die Sie als TLS-Terminierungsproxy verwenden können, sind: + +* Traefik + * Handhabt automatisch Zertifikat-Erneuerungen ✨ +* Caddy + * Handhabt automatisch Zertifikat-Erneuerungen ✨ +* Nginx + * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen +* HAProxy + * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen +* Kubernetes mit einem Ingress Controller wie Nginx + * Mit einer externen Komponente wie cert-manager für Zertifikat-Erneuerungen +* Es wird intern von einem Cloud-Anbieter als Teil seiner Dienste verwaltet (siehe unten 👇) + +Eine andere Möglichkeit besteht darin, dass Sie einen **Cloud-Dienst** verwenden, der den größten Teil der Arbeit übernimmt, einschließlich der Einrichtung von HTTPS. Er könnte einige Einschränkungen haben oder Ihnen mehr in Rechnung stellen, usw. In diesem Fall müssten Sie jedoch nicht selbst einen TLS-Terminierungsproxy einrichten. + +In den nächsten Kapiteln zeige ich Ihnen einige konkrete Beispiele. + +--- + +Die nächsten zu berücksichtigenden Konzepte drehen sich dann um das Programm, das Ihre eigentliche API ausführt (z. B. Uvicorn). + +## Programm und Prozess + +Wir werden viel über den laufenden „**Prozess**“ sprechen, daher ist es nützlich, Klarheit darüber zu haben, was das bedeutet und was der Unterschied zum Wort „**Programm**“ ist. + +### Was ist ein Programm? + +Das Wort **Programm** wird häufig zur Beschreibung vieler Dinge verwendet: + +* Der **Code**, den Sie schreiben, die **Python-Dateien**. +* Die **Datei**, die vom Betriebssystem **ausgeführt** werden kann, zum Beispiel: `python`, `python.exe` oder `uvicorn`. +* Ein bestimmtes Programm, während es auf dem Betriebssystem **läuft**, die CPU nutzt und Dinge im Arbeitsspeicher ablegt. Dies wird auch als **Prozess** bezeichnet. + +### Was ist ein Prozess? + +Das Wort **Prozess** wird normalerweise spezifischer verwendet und bezieht sich nur auf das, was im Betriebssystem ausgeführt wird (wie im letzten Punkt oben): + +* Ein bestimmtes Programm, während es auf dem Betriebssystem **ausgeführt** wird. + * Dies bezieht sich weder auf die Datei noch auf den Code, sondern **speziell** auf das, was vom Betriebssystem **ausgeführt** und verwaltet wird. +* Jedes Programm, jeder Code **kann nur dann Dinge tun**, wenn er **ausgeführt** wird, wenn also ein **Prozess läuft**. +* Der Prozess kann von Ihnen oder vom Betriebssystem **terminiert** („beendet“, „gekillt“) werden. An diesem Punkt hört es auf zu laufen/ausgeführt zu werden und kann **keine Dinge mehr tun**. +* Hinter jeder Anwendung, die Sie auf Ihrem Computer ausführen, steckt ein Prozess, jedes laufende Programm, jedes Fenster usw. Und normalerweise laufen viele Prozesse **gleichzeitig**, während ein Computer eingeschaltet ist. +* Es können **mehrere Prozesse** desselben **Programms** gleichzeitig ausgeführt werden. + +Wenn Sie sich den „Task-Manager“ oder „Systemmonitor“ (oder ähnliche Tools) in Ihrem Betriebssystem ansehen, können Sie viele dieser laufenden Prozesse sehen. + +Und Sie werden beispielsweise wahrscheinlich feststellen, dass mehrere Prozesse dasselbe Browserprogramm ausführen (Firefox, Chrome, Edge, usw.). Normalerweise führen diese einen Prozess pro Browsertab sowie einige andere zusätzliche Prozesse aus. + +<img class="shadow" src="/img/deployment/concepts/image01.png"> + +--- + +Nachdem wir nun den Unterschied zwischen den Begriffen **Prozess** und **Programm** kennen, sprechen wir weiter über das Deployment. + +## Beim Hochfahren ausführen + +Wenn Sie eine Web-API erstellen, möchten Sie in den meisten Fällen, dass diese **immer läuft**, ununterbrochen, damit Ihre Clients immer darauf zugreifen können. Es sei denn natürlich, Sie haben einen bestimmten Grund, warum Sie möchten, dass diese nur in bestimmten Situationen ausgeführt wird. Meistens möchten Sie jedoch, dass sie ständig ausgeführt wird und **verfügbar** ist. + +### Auf einem entfernten Server + +Wenn Sie einen entfernten Server (einen Cloud-Server, eine virtuelle Maschine, usw.) einrichten, können Sie am einfachsten Uvicorn (oder ähnliches) manuell ausführen, genau wie bei der lokalen Entwicklung. + +Und es wird funktionieren und **während der Entwicklung** nützlich sein. + +Wenn Ihre Verbindung zum Server jedoch unterbrochen wird, wird der **laufende Prozess** wahrscheinlich abstürzen. + +Und wenn der Server neu gestartet wird (z. B. nach Updates oder Migrationen vom Cloud-Anbieter), werden Sie das wahrscheinlich **nicht bemerken**. Und deshalb wissen Sie nicht einmal, dass Sie den Prozess manuell neu starten müssen. Ihre API bleibt also einfach tot. 😱 + +### Beim Hochfahren automatisch ausführen + +Im Allgemeinen möchten Sie wahrscheinlich, dass das Serverprogramm (z. B. Uvicorn) beim Hochfahren des Servers automatisch gestartet wird und kein **menschliches Eingreifen** erforderlich ist, sodass immer ein Prozess mit Ihrer API ausgeführt wird (z. B. Uvicorn, welches Ihre FastAPI-Anwendung ausführt). + +### Separates Programm + +Um dies zu erreichen, haben Sie normalerweise ein **separates Programm**, welches sicherstellt, dass Ihre Anwendung beim Hochfahren ausgeführt wird. Und in vielen Fällen würde es auch sicherstellen, dass auch andere Komponenten oder Anwendungen ausgeführt werden, beispielsweise eine Datenbank. + +### Beispieltools zur Ausführung beim Hochfahren + +Einige Beispiele für Tools, die diese Aufgabe übernehmen können, sind: + +* Docker +* Kubernetes +* Docker Compose +* Docker im Schwarm-Modus +* Systemd +* Supervisor +* Es wird intern von einem Cloud-Anbieter im Rahmen seiner Dienste verwaltet +* Andere ... + +In den nächsten Kapiteln werde ich Ihnen konkretere Beispiele geben. + +## Neustart + +Ähnlich wie Sie sicherstellen möchten, dass Ihre Anwendung beim Hochfahren ausgeführt wird, möchten Sie wahrscheinlich auch sicherstellen, dass diese nach Fehlern **neu gestartet** wird. + +### Wir machen Fehler + +Wir, als Menschen, machen ständig **Fehler**. Software hat fast *immer* **Bugs**, die an verschiedenen Stellen versteckt sind. 🐛 + +Und wir als Entwickler verbessern den Code ständig, wenn wir diese Bugs finden und neue Funktionen implementieren (und möglicherweise auch neue Bugs hinzufügen 😅). + +### Kleine Fehler automatisch handhaben + +Wenn beim Erstellen von Web-APIs mit FastAPI ein Fehler in unserem Code auftritt, wird FastAPI ihn normalerweise dem einzelnen Request zurückgeben, der den Fehler ausgelöst hat. 🛡 + +Der Client erhält für diesen Request einen **500 Internal Server Error**, aber die Anwendung arbeitet bei den nächsten Requests weiter, anstatt einfach komplett abzustürzen. + +### Größere Fehler – Abstürze + +Dennoch kann es vorkommen, dass wir Code schreiben, der **die gesamte Anwendung zum Absturz bringt** und so zum Absturz von Uvicorn und Python führt. 💥 + +Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, weil an einer Stelle ein Fehler aufgetreten ist. Sie möchten wahrscheinlich, dass sie zumindest für die *Pfadoperationen*, die nicht fehlerhaft sind, **weiterläuft**. + +### Neustart nach Absturz + +Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... + +!!! tip "Tipp" + ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. + + Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. + +Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann. + +### Beispieltools zum automatischen Neustart + +In den meisten Fällen wird dasselbe Tool, das zum **Ausführen des Programms beim Hochfahren** verwendet wird, auch für automatische **Neustarts** verwendet. + +Dies könnte zum Beispiel erledigt werden durch: + +* Docker +* Kubernetes +* Docker Compose +* Docker im Schwarm-Modus +* Systemd +* Supervisor +* Intern von einem Cloud-Anbieter im Rahmen seiner Dienste +* Andere ... + +## Replikation – Prozesse und Arbeitsspeicher + +Wenn Sie eine FastAPI-Anwendung verwenden und ein Serverprogramm wie Uvicorn verwenden, kann **ein einzelner Prozess** mehrere Clients gleichzeitig bedienen. + +In vielen Fällen möchten Sie jedoch mehrere Prozesse gleichzeitig ausführen. + +### Mehrere Prozesse – Worker + +Wenn Sie mehr Clients haben, als ein einzelner Prozess verarbeiten kann (z. B. wenn die virtuelle Maschine nicht sehr groß ist) und die CPU des Servers **mehrere Kerne** hat, dann könnten **mehrere Prozesse** gleichzeitig mit derselben Anwendung laufen und alle Requests unter sich verteilen. + +Wenn Sie mit **mehreren Prozessen** dasselbe API-Programm ausführen, werden diese üblicherweise als **<abbr title="Arbeiter">Worker</abbr>** bezeichnet. + +### Workerprozesse und Ports + +Erinnern Sie sich aus der Dokumentation [Über HTTPS](https.md){.internal-link target=_blank}, dass nur ein Prozess auf einer Kombination aus Port und IP-Adresse auf einem Server lauschen kann? + +Das ist immer noch wahr. + +Um also **mehrere Prozesse** gleichzeitig zu haben, muss es einen **einzelnen Prozess geben, der einen Port überwacht**, welcher dann die Kommunikation auf irgendeine Weise an jeden Workerprozess überträgt. + +### Arbeitsspeicher pro Prozess + +Wenn das Programm nun Dinge in den Arbeitsspeicher lädt, zum Beispiel ein Modell für maschinelles Lernen in einer Variablen oder den Inhalt einer großen Datei in einer Variablen, verbraucht das alles **einen Teil des Arbeitsspeichers (RAM – Random Access Memory)** des Servers. + +Und mehrere Prozesse teilen sich normalerweise keinen Speicher. Das bedeutet, dass jeder laufende Prozess seine eigenen Dinge, eigenen Variablen und eigenen Speicher hat. Und wenn Sie in Ihrem Code viel Speicher verbrauchen, verbraucht **jeder Prozess** die gleiche Menge Speicher. + +### Serverspeicher + +Wenn Ihr Code beispielsweise ein Machine-Learning-Modell mit **1 GB Größe** lädt und Sie einen Prozess mit Ihrer API ausführen, verbraucht dieser mindestens 1 GB RAM. Und wenn Sie **4 Prozesse** (4 Worker) starten, verbraucht jeder 1 GB RAM. Insgesamt verbraucht Ihre API also **4 GB RAM**. + +Und wenn Ihr entfernter Server oder Ihre virtuelle Maschine nur über 3 GB RAM verfügt, führt der Versuch, mehr als 4 GB RAM zu laden, zu Problemen. 🚨 + +### Mehrere Prozesse – Ein Beispiel + +Im folgenden Beispiel gibt es einen **Manager-Prozess**, welcher zwei **Workerprozesse** startet und steuert. + +Dieser Manager-Prozess wäre wahrscheinlich derjenige, welcher der IP am **Port** lauscht. Und er würde die gesamte Kommunikation an die Workerprozesse weiterleiten. + +Diese Workerprozesse würden Ihre Anwendung ausführen, sie würden die Hauptberechnungen durchführen, um einen **Request** entgegenzunehmen und eine **Response** zurückzugeben, und sie würden alles, was Sie in Variablen einfügen, in den RAM laden. + +<img src="/img/deployment/concepts/process-ram.svg"> + +Und natürlich würden auf derselben Maschine neben Ihrer Anwendung wahrscheinlich auch **andere Prozesse** laufen. + +Ein interessantes Detail ist dabei, dass der Prozentsatz der von jedem Prozess verwendeten **CPU** im Laufe der Zeit stark **variieren** kann, der **Arbeitsspeicher (RAM)** jedoch normalerweise mehr oder weniger **stabil** bleibt. + +Wenn Sie eine API haben, die jedes Mal eine vergleichbare Menge an Berechnungen durchführt, und Sie viele Clients haben, dann wird die **CPU-Auslastung** wahrscheinlich *ebenfalls stabil sein* (anstatt ständig schnell zu steigen und zu fallen). + +### Beispiele für Replikation-Tools und -Strategien + +Es gibt mehrere Ansätze, um dies zu erreichen, und ich werde Ihnen in den nächsten Kapiteln mehr über bestimmte Strategien erzählen, beispielsweise wenn es um Docker und Container geht. + +Die wichtigste zu berücksichtigende Einschränkung besteht darin, dass es eine **einzelne** Komponente geben muss, welche die **öffentliche IP** auf dem **Port** verwaltet. Und dann muss diese irgendwie die Kommunikation **weiterleiten**, an die replizierten **Prozesse/Worker**. + +Hier sind einige mögliche Kombinationen und Strategien: + +* **Gunicorn**, welches **Uvicorn-Worker** managt + * Gunicorn wäre der **Prozessmanager**, der die **IP** und den **Port** überwacht, die Replikation würde durch **mehrere Uvicorn-Workerprozesse** erfolgen +* **Uvicorn**, welches **Uvicorn-Worker** managt + * Ein Uvicorn-**Prozessmanager** würde der **IP** am **Port** lauschen, und er würde **mehrere Uvicorn-Workerprozesse** starten. +* **Kubernetes** und andere verteilte **Containersysteme** + * Etwas in der **Kubernetes**-Ebene würde die **IP** und den **Port** abhören. Die Replikation hätte **mehrere Container**, in jedem wird jeweils **ein Uvicorn-Prozess** ausgeführt. +* **Cloud-Dienste**, welche das für Sie erledigen + * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. + +!!! tip "Tipp" + Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. + + Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +## Schritte vor dem Start + +Es gibt viele Fälle, in denen Sie, **bevor Sie Ihre Anwendung starten**, einige Schritte ausführen möchten. + +Beispielsweise möchten Sie möglicherweise **Datenbankmigrationen** ausführen. + +In den meisten Fällen möchten Sie diese Schritte jedoch nur **einmal** ausführen. + +Sie möchten also einen **einzelnen Prozess** haben, um diese **Vorab-Schritte** auszuführen, bevor Sie die Anwendung starten. + +Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, der die Vorab-Schritte ausführt, *auch* wenn Sie anschließend **mehrere Prozesse** (mehrere Worker) für die Anwendung selbst starten. Wenn diese Schritte von **mehreren Prozessen** ausgeführt würden, würden diese die Arbeit **verdoppeln**, indem sie sie **parallel** ausführen, und wenn es sich bei den Schritten um etwas Delikates wie eine Datenbankmigration handelt, könnte das miteinander Konflikte verursachen. + +Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. + +!!! tip "Tipp" + Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. + + In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 + +### Beispiele für Strategien für Vorab-Schritte + +Es hängt **stark** davon ab, wie Sie **Ihr System bereitstellen**, und hängt wahrscheinlich mit der Art und Weise zusammen, wie Sie Programme starten, Neustarts durchführen, usw. + +Hier sind einige mögliche Ideen: + +* Ein „Init-Container“ in Kubernetes, der vor Ihrem Anwendungs-Container ausgeführt wird +* Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet + * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. + +!!! tip "Tipp" + Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +## Ressourcennutzung + +Ihr(e) Server ist (sind) eine **Ressource**, welche Sie mit Ihren Programmen, der Rechenzeit auf den CPUs und dem verfügbaren RAM-Speicher verbrauchen oder **nutzen** können. + +Wie viele Systemressourcen möchten Sie verbrauchen/nutzen? Sie mögen „nicht viel“ denken, aber in Wirklichkeit möchten Sie tatsächlich **so viel wie möglich ohne Absturz** verwenden. + +Wenn Sie für drei Server bezahlen, aber nur wenig von deren RAM und CPU nutzen, **verschwenden Sie wahrscheinlich Geld** 💸 und wahrscheinlich **Strom für den Server** 🌎, usw. + +In diesem Fall könnte es besser sein, nur zwei Server zu haben und einen höheren Prozentsatz von deren Ressourcen zu nutzen (CPU, Arbeitsspeicher, Festplatte, Netzwerkbandbreite, usw.). + +Wenn Sie andererseits über zwei Server verfügen und **100 % ihrer CPU und ihres RAM** nutzen, wird irgendwann ein Prozess nach mehr Speicher fragen und der Server muss die Festplatte als „Speicher“ verwenden (was tausendmal langsamer sein kann) oder er könnte sogar **abstürzen**. Oder ein Prozess muss möglicherweise einige Berechnungen durchführen und müsste warten, bis die CPU wieder frei ist. + +In diesem Fall wäre es besser, **einen zusätzlichen Server** zu besorgen und einige Prozesse darauf auszuführen, damit alle über **genug RAM und CPU-Zeit** verfügen. + +Es besteht auch die Möglichkeit, dass es aus irgendeinem Grund zu **Spitzen** in der Nutzung Ihrer API kommt. Vielleicht ist diese viral gegangen, oder vielleicht haben andere Dienste oder Bots damit begonnen, sie zu nutzen. Und vielleicht möchten Sie in solchen Fällen über zusätzliche Ressourcen verfügen, um auf der sicheren Seite zu sein. + +Sie können eine **beliebige Zahl** festlegen, um beispielsweise eine Ressourcenauslastung zwischen **50 % und 90 %** anzustreben. Der Punkt ist, dass dies wahrscheinlich die wichtigen Dinge sind, die Sie messen und verwenden sollten, um Ihre Deployments zu optimieren. + +Sie können einfache Tools wie `htop` verwenden, um die in Ihrem Server verwendete CPU und den RAM oder die von jedem Prozess verwendete Menge anzuzeigen. Oder Sie können komplexere Überwachungstools verwenden, die möglicherweise auf mehrere Server usw. verteilt sind. + +## Zusammenfassung + +Sie haben hier einige der wichtigsten Konzepte gelesen, die Sie wahrscheinlich berücksichtigen müssen, wenn Sie entscheiden, wie Sie Ihre Anwendung bereitstellen: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +Das Verständnis dieser Ideen und deren Anwendung sollte Ihnen die nötige Intuition vermitteln, um bei der Konfiguration und Optimierung Ihrer Deployments Entscheidungen zu treffen. 🤓 + +In den nächsten Abschnitten gebe ich Ihnen konkretere Beispiele für mögliche Strategien, die Sie verfolgen können. 🚀 From 6590b52319d9a916d6dc8ca8276b226bce13504a Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:16:35 +0100 Subject: [PATCH 196/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/manually.md`=20(#10738)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/manually.md | 145 ++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 docs/de/docs/deployment/manually.md diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md new file mode 100644 index 000000000..c8e348aa1 --- /dev/null +++ b/docs/de/docs/deployment/manually.md @@ -0,0 +1,145 @@ +# Einen Server manuell ausführen – Uvicorn + +Das Wichtigste, was Sie zum Ausführen einer **FastAPI**-Anwendung auf einer entfernten Servermaschine benötigen, ist ein ASGI-Serverprogramm, wie **Uvicorn**. + +Es gibt 3 Hauptalternativen: + +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: ein hochperformanter ASGI-Server. +* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. +* <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: Der für Django Channels entwickelte ASGI-Server. + +## Servermaschine und Serverprogramm + +Bei den Benennungen gibt es ein kleines Detail, das Sie beachten sollten. 💡 + +Das Wort „**Server**“ bezieht sich häufig sowohl auf den entfernten-/Cloud-Computer (die physische oder virtuelle Maschine) als auch auf das Programm, das auf dieser Maschine ausgeführt wird (z. B. Uvicorn). + +Denken Sie einfach daran, wenn Sie „Server“ im Allgemeinen lesen, dass es sich auf eines dieser beiden Dinge beziehen kann. + +Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als **Server**, aber auch als **Maschine**, **VM** (virtuelle Maschine) oder **Knoten** bezeichnet. Diese Begriffe beziehen sich auf irgendeine Art von entfernten Rechner, normalerweise unter Linux, auf dem Sie Programme ausführen. + +## Das Serverprogramm installieren + +Sie können einen ASGI-kompatiblen Server installieren mit: + +=== "Uvicorn" + + * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. + + <div class="termy"> + + ```console + $ pip install "uvicorn[standard]" + + ---> 100% + ``` + + </div> + + !!! tip "Tipp" + Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. + + Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. + +=== "Hypercorn" + + * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. + + <div class="termy"> + + ```console + $ pip install hypercorn + + ---> 100% + ``` + + </div> + + ... oder jeden anderen ASGI-Server. + +## Das Serverprogramm ausführen + +Anschließend können Sie Ihre Anwendung auf die gleiche Weise ausführen, wie Sie es in den Tutorials getan haben, jedoch ohne die Option `--reload`, z. B.: + +=== "Uvicorn" + + <div class="termy"> + + ```console + $ uvicorn main:app --host 0.0.0.0 --port 80 + + <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) + ``` + + </div> + +=== "Hypercorn" + + <div class="termy"> + + ```console + $ hypercorn main:app --bind 0.0.0.0:80 + + Running on 0.0.0.0:8080 over http (CTRL + C to quit) + ``` + + </div> + +!!! warning "Achtung" + Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. + + Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. + + Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. + +## Hypercorn mit Trio + +Starlette und **FastAPI** basieren auf <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a>, welches diese sowohl mit der Python-Standardbibliothek <a href="https://docs.python.org/3/library/asyncio-task.html" class="external-link" target="_blank">asyncio</a>, als auch mit <a href="https://trio.readthedocs.io/en/stable/" class="external-link" target="_blank">Trio</a> kompatibel macht. + +Dennoch ist Uvicorn derzeit nur mit asyncio kompatibel und verwendet normalerweise <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a>, den leistungsstarken Drop-in-Ersatz für `asyncio`. + +Wenn Sie jedoch **Trio** direkt verwenden möchten, können Sie **Hypercorn** verwenden, da dieses es unterstützt. ✨ + +### Hypercorn mit Trio installieren + +Zuerst müssen Sie Hypercorn mit Trio-Unterstützung installieren: + +<div class="termy"> + +```console +$ pip install "hypercorn[trio]" +---> 100% +``` + +</div> + +### Mit Trio ausführen + +Dann können Sie die Befehlszeilenoption `--worker-class` mit dem Wert `trio` übergeben: + +<div class="termy"> + +```console +$ hypercorn main:app --worker-class trio +``` + +</div> + +Und das startet Hypercorn mit Ihrer Anwendung und verwendet Trio als Backend. + +Jetzt können Sie Trio intern in Ihrer Anwendung verwenden. Oder noch besser: Sie können AnyIO verwenden, sodass Ihr Code sowohl mit Trio als auch asyncio kompatibel ist. 🎉 + +## Konzepte des Deployments + +Obige Beispiele führen das Serverprogramm (z. B. Uvicorn) aus, starten **einen einzelnen Prozess** und überwachen alle IPs (`0.0.0.0`) an einem vordefinierten Port (z. B. `80`). + +Das ist die Grundidee. Aber Sie möchten sich wahrscheinlich um einige zusätzliche Dinge kümmern, wie zum Beispiel: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +In den nächsten Kapiteln erzähle ich Ihnen mehr über jedes dieser Konzepte, wie Sie über diese nachdenken, und gebe Ihnen einige konkrete Beispiele mit Strategien für den Umgang damit. 🚀 From 19694bc83937a4bcb306725e6c175a6b560fc8df Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:16:46 +0100 Subject: [PATCH 197/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/https.md`=20(#10737)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/https.md | 190 +++++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 docs/de/docs/deployment/https.md diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md new file mode 100644 index 000000000..3ebe59af2 --- /dev/null +++ b/docs/de/docs/deployment/https.md @@ -0,0 +1,190 @@ +# Über HTTPS + +Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ wird oder nicht. + +Aber es ist viel komplexer als das. + +!!! tip "Tipp" + Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. + +Um **die Grundlagen von HTTPS** aus Sicht des Benutzers zu erlernen, schauen Sie sich <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a> an. + +Aus **Sicht des Entwicklers** sollten Sie beim Nachdenken über HTTPS Folgendes beachten: + +* Für HTTPS muss **der Server** über von einem **Dritten** generierte **„Zertifikate“** verfügen. + * Diese Zertifikate werden tatsächlich vom Dritten **erworben** und nicht „generiert“. +* Zertifikate haben eine **Lebensdauer**. + * Sie **verfallen**. + * Und dann müssen sie vom Dritten **erneuert**, **erneut erworben** werden. +* Die Verschlüsselung der Verbindung erfolgt auf **TCP-Ebene**. + * Das ist eine Schicht **unter HTTP**. + * Die Handhabung von **Zertifikaten und Verschlüsselung** erfolgt also **vor HTTP**. +* **TCP weiß nichts über „<abbr title="Domäne, Bereich, Wirkungsraum">Domains</abbr>“**. Nur über IP-Adressen. + * Die Informationen über die angeforderte **spezifische Domain** befinden sich in den **HTTP-Daten**. +* Die **HTTPS-Zertifikate** „zertifizieren“ eine **bestimmte Domain**, aber das Protokoll und die Verschlüsselung erfolgen auf TCP-Ebene, **ohne zu wissen**, um welche Domain es sich handelt. +* **Standardmäßig** bedeutet das, dass Sie nur **ein HTTPS-Zertifikat pro IP-Adresse** haben können. + * Ganz gleich, wie groß Ihr Server ist oder wie klein die einzelnen Anwendungen darauf sind. + * Hierfür gibt es jedoch eine **Lösung**. +* Es gibt eine **Erweiterung** zum **TLS**-Protokoll (dasjenige, das die Verschlüsselung auf TCP-Ebene, vor HTTP, verwaltet) namens **<a href="https://en.wikipedia.org/wiki/Server_Name_Indication" class="external-link" target="_blank"><abbr title="Server Name Indication – Angabe des Servernamens">SNI</abbr></a>**. + * Mit dieser SNI-Erweiterung kann ein einzelner Server (mit einer **einzelnen IP-Adresse**) über **mehrere HTTPS-Zertifikate** verfügen und **mehrere HTTPS-Domains/Anwendungen** bedienen. + * Damit das funktioniert, muss eine **einzelne** Komponente (Programm), die auf dem Server ausgeführt wird und welche die **öffentliche IP-Adresse** überwacht, **alle HTTPS-Zertifikate** des Servers haben. +* **Nachdem** eine sichere Verbindung hergestellt wurde, ist das Kommunikationsprotokoll **immer noch HTTP**. + * Die Inhalte sind **verschlüsselt**, auch wenn sie mit dem **HTTP-Protokoll** gesendet werden. + +Es ist eine gängige Praxis, **ein Programm/HTTP-Server** auf dem Server (der Maschine, dem Host usw.) laufen zu lassen, welches **alle HTTPS-Aspekte verwaltet**: Empfangen der **verschlüsselten HTTPS-Requests**, Senden der **entschlüsselten HTTP-Requests** an die eigentliche HTTP-Anwendung die auf demselben Server läuft (in diesem Fall die **FastAPI**-Anwendung), entgegennehmen der **HTTP-Response** von der Anwendung, **verschlüsseln derselben** mithilfe des entsprechenden **HTTPS-Zertifikats** und Zurücksenden zum Client über **HTTPS**. Dieser Server wird oft als **<a href="https://en.wikipedia.org/wiki/TLS_termination_proxy" class="external-link" target="_blank">TLS-Terminierungsproxy</a>** bezeichnet. + +Einige der Optionen, die Sie als TLS-Terminierungsproxy verwenden können, sind: + +* Traefik (kann auch Zertifikat-Erneuerungen durchführen) +* Caddy (kann auch Zertifikat-Erneuerungen durchführen) +* Nginx +* HAProxy + +## Let's Encrypt + +Vor Let's Encrypt wurden diese **HTTPS-Zertifikate** von vertrauenswürdigen Dritten verkauft. + +Der Prozess zum Erwerb eines dieser Zertifikate war früher umständlich, erforderte viel Papierarbeit und die Zertifikate waren ziemlich teuer. + +Aber dann wurde **<a href="https://letsencrypt.org/" class="external-link" target="_blank">Let's Encrypt</a>** geschaffen. + +Es ist ein Projekt der Linux Foundation. Es stellt **kostenlose HTTPS-Zertifikate** automatisiert zur Verfügung. Diese Zertifikate nutzen standardmäßig die gesamte kryptografische Sicherheit und sind kurzlebig (circa 3 Monate), sodass die **Sicherheit tatsächlich besser ist**, aufgrund der kürzeren Lebensdauer. + +Die Domains werden sicher verifiziert und die Zertifikate werden automatisch generiert. Das ermöglicht auch die automatische Erneuerung dieser Zertifikate. + +Die Idee besteht darin, den Erwerb und die Erneuerung der Zertifikate zu automatisieren, sodass Sie **sicheres HTTPS, kostenlos und für immer** haben können. + +## HTTPS für Entwickler + +Hier ist ein Beispiel, wie eine HTTPS-API aussehen könnte, Schritt für Schritt, wobei vor allem die für Entwickler wichtigen Ideen berücksichtigt werden. + +### Domainname + +Alles beginnt wahrscheinlich damit, dass Sie einen **Domainnamen erwerben**. Anschließend konfigurieren Sie ihn in einem DNS-Server (wahrscheinlich beim selben Cloud-Anbieter). + +Sie würden wahrscheinlich einen Cloud-Server (eine virtuelle Maschine) oder etwas Ähnliches bekommen, und dieser hätte eine <abbr title="Sie ändert sich nicht">feste</abbr> **öffentliche IP-Adresse**. + +In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) konfigurieren, um mit **Ihrer Domain** auf die öffentliche **IP-Adresse Ihres Servers** zu verweisen. + +Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. + +!!! tip "Tipp" + Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. + +### DNS + +Konzentrieren wir uns nun auf alle tatsächlichen HTTPS-Aspekte. + +Zuerst würde der Browser mithilfe der **DNS-Server** herausfinden, welches die **IP für die Domain** ist, in diesem Fall für `someapp.example.com`. + +Die DNS-Server geben dem Browser eine bestimmte **IP-Adresse** zurück. Das wäre die von Ihrem Server verwendete öffentliche IP-Adresse, die Sie in den DNS-Servern konfiguriert haben. + +<img src="/img/deployment/https/https01.svg"> + +### TLS-Handshake-Start + +Der Browser kommuniziert dann mit dieser IP-Adresse über **Port 443** (den HTTPS-Port). + +Der erste Teil der Kommunikation besteht lediglich darin, die Verbindung zwischen dem Client und dem Server herzustellen und die zu verwendenden kryptografischen Schlüssel usw. zu vereinbaren. + +<img src="/img/deployment/https/https02.svg"> + +Diese Interaktion zwischen dem Client und dem Server zum Aufbau der TLS-Verbindung wird als **<abbr title="TLS-Handschlag">TLS-Handshake</abbr>** bezeichnet. + +### TLS mit SNI-Erweiterung + +**Nur ein Prozess** im Server kann an einem bestimmten **Port** einer bestimmten **IP-Adresse** lauschen. Möglicherweise gibt es andere Prozesse, die an anderen Ports dieselbe IP-Adresse abhören, jedoch nur einen für jede Kombination aus IP-Adresse und Port. + +TLS (HTTPS) verwendet standardmäßig den spezifischen Port `443`. Das ist also der Port, den wir brauchen. + +Da an diesem Port nur ein Prozess lauschen kann, wäre der Prozess, der dies tun würde, der **TLS-Terminierungsproxy**. + +Der TLS-Terminierungsproxy hätte Zugriff auf ein oder mehrere **TLS-Zertifikate** (HTTPS-Zertifikate). + +Mithilfe der oben beschriebenen **SNI-Erweiterung** würde der TLS-Terminierungsproxy herausfinden, welches der verfügbaren TLS-Zertifikate (HTTPS) er für diese Verbindung verwenden muss, und zwar das, welches mit der vom Client erwarteten Domain übereinstimmt. + +In diesem Fall würde er das Zertifikat für `someapp.example.com` verwenden. + +<img src="/img/deployment/https/https03.svg"> + +Der Client **vertraut** bereits der Entität, die das TLS-Zertifikat generiert hat (in diesem Fall Let's Encrypt, aber wir werden später mehr darüber erfahren), sodass er **verifizieren** kann, dass das Zertifikat gültig ist. + +Mithilfe des Zertifikats entscheiden der Client und der TLS-Terminierungsproxy dann, **wie der Rest der TCP-Kommunikation verschlüsselt werden soll**. Damit ist der **TLS-Handshake** abgeschlossen. + +Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verbindung**, via TLS. Und dann können sie diese Verbindung verwenden, um die eigentliche **HTTP-Kommunikation** zu beginnen. + +Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. + +!!! tip "Tipp" + Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. + +### HTTPS-Request + +Da Client und Server (sprich, der Browser und der TLS-Terminierungsproxy) nun über eine **verschlüsselte TCP-Verbindung** verfügen, können sie die **HTTP-Kommunikation** starten. + +Der Client sendet also einen **HTTPS-Request**. Das ist einfach ein HTTP-Request über eine verschlüsselte TLS-Verbindung. + +<img src="/img/deployment/https/https04.svg"> + +### Den Request entschlüsseln + +Der TLS-Terminierungsproxy würde die vereinbarte Verschlüsselung zum **Entschlüsseln des Requests** verwenden und den **einfachen (entschlüsselten) HTTP-Request** an den Prozess weiterleiten, der die Anwendung ausführt (z. B. einen Prozess, bei dem Uvicorn die FastAPI-Anwendung ausführt). + +<img src="/img/deployment/https/https05.svg"> + +### HTTP-Response + +Die Anwendung würde den Request verarbeiten und eine **einfache (unverschlüsselte) HTTP-Response** an den TLS-Terminierungsproxy senden. + +<img src="/img/deployment/https/https06.svg"> + +### HTTPS-Response + +Der TLS-Terminierungsproxy würde dann die Response mithilfe der zuvor vereinbarten Kryptografie (als das Zertifikat für `someapp.example.com` verhandelt wurde) **verschlüsseln** und sie an den Browser zurücksenden. + +Als Nächstes überprüft der Browser, ob die Response gültig und mit dem richtigen kryptografischen Schlüssel usw. verschlüsselt ist. Anschließend **entschlüsselt er die Response** und verarbeitet sie. + +<img src="/img/deployment/https/https07.svg"> + +Der Client (Browser) weiß, dass die Response vom richtigen Server kommt, da dieser die Kryptografie verwendet, die zuvor mit dem **HTTPS-Zertifikat** vereinbart wurde. + +### Mehrere Anwendungen + +Auf demselben Server (oder denselben Servern) könnten sich **mehrere Anwendungen** befinden, beispielsweise andere API-Programme oder eine Datenbank. + +Nur ein Prozess kann diese spezifische IP und den Port verarbeiten (in unserem Beispiel der TLS-Terminierungsproxy), aber die anderen Anwendungen/Prozesse können auch auf dem/den Server(n) ausgeführt werden, solange sie nicht versuchen, dieselbe **Kombination aus öffentlicher IP und Port** zu verwenden. + +<img src="/img/deployment/https/https08.svg"> + +Auf diese Weise könnte der TLS-Terminierungsproxy HTTPS und Zertifikate für **mehrere Domains**, für mehrere Anwendungen, verarbeiten und die Requests dann jeweils an die richtige Anwendung weiterleiten. + +### Verlängerung des Zertifikats + +Irgendwann in der Zukunft würde jedes Zertifikat **ablaufen** (etwa 3 Monate nach dem Erwerb). + +Und dann gäbe es ein anderes Programm (in manchen Fällen ist es ein anderes Programm, in manchen Fällen ist es derselbe TLS-Terminierungsproxy), das mit Let's Encrypt kommuniziert und das/die Zertifikat(e) erneuert. + +<img src="/img/deployment/https/https.svg"> + +Die **TLS-Zertifikate** sind **einem Domainnamen zugeordnet**, nicht einer IP-Adresse. + +Um die Zertifikate zu erneuern, muss das erneuernde Programm der Behörde (Let's Encrypt) **nachweisen**, dass es diese Domain tatsächlich **besitzt und kontrolliert**. + +Um dies zu erreichen und den unterschiedlichen Anwendungsanforderungen gerecht zu werden, gibt es mehrere Möglichkeiten. Einige beliebte Methoden sind: + +* **Einige DNS-Einträge ändern**. + * Hierfür muss das erneuernde Programm die APIs des DNS-Anbieters unterstützen. Je nachdem, welchen DNS-Anbieter Sie verwenden, kann dies eine Option sein oder auch nicht. +* **Als Server ausführen** (zumindest während des Zertifikatserwerbsvorgangs), auf der öffentlichen IP-Adresse, die der Domain zugeordnet ist. + * Wie oben erwähnt, kann nur ein Prozess eine bestimmte IP und einen bestimmten Port überwachen. + * Das ist einer der Gründe, warum es sehr nützlich ist, wenn derselbe TLS-Terminierungsproxy auch den Zertifikats-Erneuerungsprozess übernimmt. + * Andernfalls müssen Sie möglicherweise den TLS-Terminierungsproxy vorübergehend stoppen, das Programm starten, welches die neuen Zertifikate beschafft, diese dann mit dem TLS-Terminierungsproxy konfigurieren und dann den TLS-Terminierungsproxy neu starten. Das ist nicht ideal, da Ihre Anwendung(en) während der Zeit, in der der TLS-Terminierungsproxy ausgeschaltet ist, nicht erreichbar ist/sind. + +Dieser ganze Erneuerungsprozess, während die Anwendung weiterhin bereitgestellt wird, ist einer der Hauptgründe, warum Sie ein **separates System zur Verarbeitung von HTTPS** mit einem TLS-Terminierungsproxy haben möchten, anstatt einfach die TLS-Zertifikate direkt mit dem Anwendungsserver zu verwenden (z. B. Uvicorn). + +## Zusammenfassung + +**HTTPS** zu haben ist sehr wichtig und in den meisten Fällen eine **kritische Anforderung**. Die meiste Arbeit, die Sie als Entwickler in Bezug auf HTTPS aufwenden müssen, besteht lediglich darin, **diese Konzepte zu verstehen** und wie sie funktionieren. + +Sobald Sie jedoch die grundlegenden Informationen zu **HTTPS für Entwickler** kennen, können Sie verschiedene Tools problemlos kombinieren und konfigurieren, um alles auf einfache Weise zu verwalten. + +In einigen der nächsten Kapitel zeige ich Ihnen einige konkrete Beispiele für die Einrichtung von **HTTPS** für **FastAPI**-Anwendungen. 🔒 From 0a27f397720f732d2f5482ddcb5534eb4f3ffa30 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:16:56 +0100 Subject: [PATCH 198/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/index.md`=20(#10733)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/index.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/de/docs/deployment/index.md diff --git a/docs/de/docs/deployment/index.md b/docs/de/docs/deployment/index.md new file mode 100644 index 000000000..1aa131097 --- /dev/null +++ b/docs/de/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Deployment + +Das Deployment einer **FastAPI**-Anwendung ist relativ einfach. + +## Was bedeutet Deployment? + +**Deployment** (Deutsch etwa: **Bereitstellen der Anwendung**) bedeutet, die notwendigen Schritte durchzuführen, um die Anwendung **für die Endbenutzer verfügbar** zu machen. + +Bei einer **Web-API** bedeutet das normalerweise, diese auf einem **entfernten Rechner** zu platzieren, mit einem **Serverprogramm**, welches gute Leistung, Stabilität, usw. bietet, damit Ihre **Benutzer** auf die Anwendung effizient und ohne Unterbrechungen oder Probleme **zugreifen** können. + +Das steht im Gegensatz zu den **Entwicklungsphasen**, in denen Sie ständig den Code ändern, kaputt machen, reparieren, den Entwicklungsserver stoppen und neu starten, usw. + +## Deployment-Strategien + +Abhängig von Ihrem spezifischen Anwendungsfall und den von Ihnen verwendeten Tools gibt es mehrere Möglichkeiten, das zu tun. + +Sie könnten mithilfe einer Kombination von Tools selbst **einen Server bereitstellen**, Sie könnten einen **Cloud-Dienst** nutzen, der einen Teil der Arbeit für Sie erledigt, oder andere mögliche Optionen. + +Ich zeige Ihnen einige der wichtigsten Konzepte, die Sie beim Deployment einer **FastAPI**-Anwendung wahrscheinlich berücksichtigen sollten (obwohl das meiste davon auch für jede andere Art von Webanwendung gilt). + +In den nächsten Abschnitten erfahren Sie mehr über die zu beachtenden Details und über die Techniken, das zu tun. ✨ From beb0235aadd2c121532255ef5023af5226828b72 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:17:05 +0100 Subject: [PATCH 199/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/wsgi.md`=20(#10713)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/wsgi.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 docs/de/docs/advanced/wsgi.md diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md new file mode 100644 index 000000000..19ff90a90 --- /dev/null +++ b/docs/de/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# WSGI inkludieren – Flask, Django und andere + +Sie können WSGI-Anwendungen mounten, wie Sie es in [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}, [Hinter einem Proxy](behind-a-proxy.md){.internal-link target=_blank} gesehen haben. + +Dazu können Sie die `WSGIMiddleware` verwenden und damit Ihre WSGI-Anwendung wrappen, zum Beispiel Flask, Django usw. + +## `WSGIMiddleware` verwenden + +Sie müssen `WSGIMiddleware` importieren. + +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!} +``` + +## Es ansehen + +Jetzt wird jede Anfrage unter dem Pfad `/v1/` von der Flask-Anwendung verarbeitet. + +Und der Rest wird von **FastAPI** gehandhabt. + +Wenn Sie das mit Uvicorn ausführen und auf <a href="http://localhost:8000/v1/" class="external-link" target="_blank">http://localhost:8000/v1/</a> gehen, sehen Sie die Response von Flask: + +```txt +Hello, World from Flask! +``` + +Und wenn Sie auf <a href="http://localhost:8000/v2" class="external-link" target="_blank">http://localhost:8000/v2</a> gehen, sehen Sie die Response von FastAPI: + +```JSON +{ + "message": "Hello World" +} +``` From e9c6dfd44805887b93824f5365d84b99d37dfba6 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:17:14 +0100 Subject: [PATCH 200/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/settings.md`=20(#10709)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/settings.md | 485 ++++++++++++++++++++++++++++++ 1 file changed, 485 insertions(+) create mode 100644 docs/de/docs/advanced/settings.md diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md new file mode 100644 index 000000000..fe01d8e1f --- /dev/null +++ b/docs/de/docs/advanced/settings.md @@ -0,0 +1,485 @@ +# Einstellungen und Umgebungsvariablen + +In vielen Fällen benötigt Ihre Anwendung möglicherweise einige externe Einstellungen oder Konfigurationen, zum Beispiel geheime Schlüssel, Datenbank-Anmeldeinformationen, Anmeldeinformationen für E-Mail-Dienste, usw. + +Die meisten dieser Einstellungen sind variabel (können sich ändern), wie z. B. Datenbank-URLs. Und vieles könnten schützenswerte, geheime Daten sein. + +Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestellt, die von der Anwendung gelesen werden. + +## Umgebungsvariablen + +!!! tip "Tipp" + Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. + +Eine <a href="https://de.wikipedia.org/wiki/Umgebungsvariable" class="external-link" target="_blank">Umgebungsvariable</a> (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann. + +Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen: + +=== "Linux, macOS, Windows Bash" + + <div class="termy"> + + ```console + // Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels + $ export MY_NAME="Wade Wilson" + + // Dann könnten Sie diese mit anderen Programmen verwenden, etwa + $ echo "Hello $MY_NAME" + + Hello Wade Wilson + ``` + + </div> + +=== "Windows PowerShell" + + <div class="termy"> + + ```console + // Erstelle eine Umgebungsvariable MY_NAME + $ $Env:MY_NAME = "Wade Wilson" + + // Verwende sie mit anderen Programmen, etwa + $ echo "Hello $Env:MY_NAME" + + Hello Wade Wilson + ``` + + </div> + +### Umgebungsvariablen mit Python auslesen + +Sie können Umgebungsvariablen auch außerhalb von Python im Terminal (oder mit einer anderen Methode) erstellen und diese dann mit Python auslesen. + +Sie könnten zum Beispiel eine Datei `main.py` haben mit: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +!!! tip "Tipp" + Das zweite Argument für <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> ist der zurückzugebende Defaultwert. + + Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. + +Dann könnten Sie dieses Python-Programm aufrufen: + +<div class="termy"> + +```console +// Hier legen wir die Umgebungsvariable noch nicht fest +$ python main.py + +// Da wir die Umgebungsvariable nicht festgelegt haben, erhalten wir den Standardwert + +Hello World from Python + +// Aber wenn wir zuerst eine Umgebungsvariable erstellen +$ export MY_NAME="Wade Wilson" + +// Und dann das Programm erneut aufrufen +$ python main.py + +// Kann es jetzt die Umgebungsvariable lesen + +Hello Wade Wilson from Python +``` + +</div> + +Da Umgebungsvariablen außerhalb des Codes festgelegt, aber vom Code gelesen werden können und nicht zusammen mit den übrigen Dateien gespeichert (an `git` committet) werden müssen, werden sie häufig für Konfigurationen oder Einstellungen verwendet. + +Sie können eine Umgebungsvariable auch nur für einen bestimmten Programmaufruf erstellen, die nur für dieses Programm und nur für dessen Dauer verfügbar ist. + +Erstellen Sie diese dazu direkt vor dem Programm selbst, in derselben Zeile: + +<div class="termy"> + +```console +// Erstelle eine Umgebungsvariable MY_NAME inline für diesen Programmaufruf +$ MY_NAME="Wade Wilson" python main.py + +// main.py kann jetzt diese Umgebungsvariable lesen + +Hello Wade Wilson from Python + +// Die Umgebungsvariable existiert danach nicht mehr +$ python main.py + +Hello World from Python +``` + +</div> + +!!! tip "Tipp" + Weitere Informationen dazu finden Sie unter <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>. + +### Typen und Validierung + +Diese Umgebungsvariablen können nur Text-Zeichenketten verarbeiten, da sie außerhalb von Python liegen und mit anderen Programmen und dem Rest des Systems (und sogar mit verschiedenen Betriebssystemen wie Linux, Windows, macOS) kompatibel sein müssen. + +Das bedeutet, dass jeder in Python aus einer Umgebungsvariablen gelesene Wert ein `str` ist und jede Konvertierung in einen anderen Typ oder jede Validierung im Code erfolgen muss. + +## Pydantic `Settings` + +Glücklicherweise bietet Pydantic ein großartiges Werkzeug zur Verarbeitung dieser Einstellungen, die von Umgebungsvariablen stammen, mit <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings Management</a>. + +### `pydantic-settings` installieren + +Installieren Sie zunächst das Package `pydantic-settings`: + +<div class="termy"> + +```console +$ pip install pydantic-settings +---> 100% +``` + +</div> + +Es ist bereits enthalten, wenn Sie die `all`-Extras installiert haben, mit: + +<div class="termy"> + +```console +$ pip install "fastapi[all]" +---> 100% +``` + +</div> + +!!! info + In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. + +### Das `Settings`-Objekt erstellen + +Importieren Sie `BaseSettings` aus Pydantic und erstellen Sie eine Unterklasse, ganz ähnlich wie bei einem Pydantic-Modell. + +Auf die gleiche Weise wie bei Pydantic-Modellen deklarieren Sie Klassenattribute mit Typannotationen und möglicherweise Defaultwerten. + +Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`. + +=== "Pydantic v2" + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001.py!} + ``` + +=== "Pydantic v1" + + !!! info + In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001_pv1.py!} + ``` + +!!! tip "Tipp" + Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. + +Wenn Sie dann eine Instanz dieser `Settings`-Klasse erstellen (in diesem Fall als `settings`-Objekt), liest Pydantic die Umgebungsvariablen ohne Berücksichtigung der Groß- und Kleinschreibung. Eine Variable `APP_NAME` in Großbuchstaben wird also als Attribut `app_name` gelesen. + +Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses `settings`-Objekt verwenden, verfügen Sie über Daten mit den von Ihnen deklarierten Typen (z. B. ist `items_per_user` ein `int`). + +### `settings` verwenden + +Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: + +```Python hl_lines="18-20" +{!../../../docs_src/settings/tutorial001.py!} +``` + +### Den Server ausführen + +Als Nächstes würden Sie den Server ausführen und die Konfigurationen als Umgebungsvariablen übergeben. Sie könnten beispielsweise `ADMIN_EMAIL` und `APP_NAME` festlegen mit: + +<div class="termy"> + +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +!!! tip "Tipp" + Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. + +Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt. + +Der `app_name` wäre `"ChimichangApp"`. + +Und `items_per_user` würde seinen Standardwert von `50` behalten. + +## Einstellungen in einem anderen Modul + +Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen haben. + +Sie könnten beispielsweise eine Datei `config.py` haben mit: + +```Python +{!../../../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!} +``` + +!!! tip "Tipp" + Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. + +## Einstellungen in einer Abhängigkeit + +In manchen Fällen kann es nützlich sein, die Einstellungen mit einer Abhängigkeit bereitzustellen, anstatt ein globales Objekt `settings` zu haben, das überall verwendet wird. + +Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Abhängigkeit mit Ihren eigenen benutzerdefinierten Einstellungen zu überschreiben. + +### Die Konfigurationsdatei + +Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: + +```Python hl_lines="10" +{!../../../docs_src/settings/app02/config.py!} +``` + +Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. + +### Die Haupt-Anwendungsdatei + +Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. + +=== "Python 3.9+" + + ```Python hl_lines="6 12-13" + {!> ../../../docs_src/settings/app02_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="6 12-13" + {!> ../../../docs_src/settings/app02_an/main.py!} + ``` + +=== "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!} + ``` + +!!! tip "Tipp" + Wir werden das `@lru_cache` in Kürze besprechen. + + Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. + +Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. + +=== "Python 3.9+" + + ```Python hl_lines="17 19-21" + {!> ../../../docs_src/settings/app02_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 19-21" + {!> ../../../docs_src/settings/app02_an/main.py!} + ``` + +=== "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!} + ``` + +### 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!} +``` + +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. + +Dann können wir testen, ob das verwendet wird. + +## Lesen einer `.env`-Datei + +Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielleicht in verschiedenen Umgebungen, kann es nützlich sein, diese in eine Datei zu schreiben und sie dann daraus zu lesen, als wären sie Umgebungsvariablen. + +Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. + +!!! tip "Tipp" + Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. + + 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 <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>. + +!!! tip "Tipp" + Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. + +### Die `.env`-Datei + +Sie könnten eine `.env`-Datei haben, mit: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Einstellungen aus `.env` lesen + +Und dann aktualisieren Sie Ihre `config.py` mit: + +=== "Pydantic v2" + + ```Python hl_lines="9" + {!> ../../../docs_src/settings/app03_an/config.py!} + ``` + + !!! tip "Tipp" + Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/latest/concepts/config/" class="external-link" target="_blank">Pydantic: Configuration</a>. + +=== "Pydantic v1" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/settings/app03_an/config_pv1.py!} + ``` + + !!! tip "Tipp" + Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. + +!!! info + In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. + +Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten. + +### Die `Settings` nur einmal laden mittels `lru_cache` + +Das Lesen einer Datei von der Festplatte ist normalerweise ein kostspieliger (langsamer) Vorgang, daher möchten Sie ihn wahrscheinlich nur einmal ausführen und dann dasselbe Einstellungsobjekt erneut verwenden, anstatt es für jeden Request zu lesen. + +Aber jedes Mal, wenn wir ausführen: + +```Python +Settings() +``` + +würde ein neues `Settings`-Objekt erstellt und bei der Erstellung würde die `.env`-Datei erneut ausgelesen. + +Wenn die Abhängigkeitsfunktion wie folgt wäre: + +```Python +def get_settings(): + return Settings() +``` + +würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für jeden Request lesen. ⚠️ + +Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ + +=== "Python 3.9+" + + ```Python hl_lines="1 11" + {!> ../../../docs_src/settings/app03_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 11" + {!> ../../../docs_src/settings/app03_an/main.py!} + ``` + +=== "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!} + ``` + +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. + +#### Technische Details zu `lru_cache` + +`@lru_cache` ändert die Funktion, die es dekoriert, dahingehend, denselben Wert zurückzugeben, der beim ersten Mal zurückgegeben wurde, anstatt ihn erneut zu berechnen und den Code der Funktion jedes Mal auszuführen. + +Die darunter liegende Funktion wird also für jede Argumentkombination einmal ausgeführt. Und dann werden die von jeder dieser Argumentkombinationen zurückgegebenen Werte immer wieder verwendet, wenn die Funktion mit genau derselben Argumentkombination aufgerufen wird. + +Wenn Sie beispielsweise eine Funktion haben: + +```Python +@lru_cache +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +könnte Ihr Programm so ausgeführt werden: + +```mermaid +sequenceDiagram + +participant code as Code +participant function as say_hi() +participant execute as Funktion ausgeführt + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: gib das gespeicherte Resultat zurück + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: gib das gespeicherte Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: gib das gespeicherte Resultat zurück + end +``` + +Im Fall unserer Abhängigkeit `get_settings()` akzeptiert die Funktion nicht einmal Argumente, sodass sie immer den gleichen Wert zurückgibt. + +Auf diese Weise verhält es sich fast so, als wäre es nur eine globale Variable. Da es jedoch eine Abhängigkeitsfunktion verwendet, können wir diese zu Testzwecken problemlos überschreiben. + +`@lru_cache` ist Teil von `functools`, welches Teil von Pythons Standardbibliothek ist. Weitere Informationen dazu finden Sie in der <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache" class="external-link" target="_blank">Python Dokumentation für `@lru_cache`</a>. + +## Zusammenfassung + +Mit Pydantic Settings können Sie die Einstellungen oder Konfigurationen für Ihre Anwendung verwalten und dabei die gesamte Leistungsfähigkeit der Pydantic-Modelle nutzen. + +* Durch die Verwendung einer Abhängigkeit können Sie das Testen vereinfachen. +* Sie können `.env`-Dateien damit verwenden. +* Durch die Verwendung von `@lru_cache` können Sie vermeiden, die dotenv-Datei bei jedem Request erneut zu lesen, während Sie sie während des Testens überschreiben können. From be8fab0e500ca5e579d28995185fec26c3bb4b4b Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:17:23 +0100 Subject: [PATCH 201/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/openapi-callbacks.md`=20(#107?= =?UTF-8?q?10)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/openapi-callbacks.md | 179 +++++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 docs/de/docs/advanced/openapi-callbacks.md diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..026fdb4fe --- /dev/null +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -0,0 +1,179 @@ +# OpenAPI-Callbacks + +Sie könnten eine API mit einer *Pfadoperation* erstellen, die einen Request an eine *externe API* auslösen könnte, welche von jemand anderem erstellt wurde (wahrscheinlich derselbe Entwickler, der Ihre API *verwenden* würde). + +Der Vorgang, der stattfindet, wenn Ihre API-Anwendung die *externe API* aufruft, wird als „Callback“ („Rückruf“) bezeichnet. Denn die Software, die der externe Entwickler geschrieben hat, sendet einen Request an Ihre API und dann *ruft Ihre API zurück* (*calls back*) und sendet einen Request an eine *externe API* (die wahrscheinlich vom selben Entwickler erstellt wurde). + +In diesem Fall möchten Sie möglicherweise dokumentieren, wie diese externe API aussehen *sollte*. Welche *Pfadoperation* sie haben sollte, welchen Body sie erwarten sollte, welche Response sie zurückgeben sollte, usw. + +## Eine Anwendung mit Callbacks + +Sehen wir uns das alles anhand eines Beispiels an. + +Stellen Sie sich vor, Sie entwickeln eine Anwendung, mit der Sie Rechnungen erstellen können. + +Diese Rechnungen haben eine `id`, einen optionalen `title`, einen `customer` (Kunde) und ein `total` (Gesamtsumme). + +Der Benutzer Ihrer API (ein externer Entwickler) erstellt mit einem POST-Request eine Rechnung in Ihrer API. + +Dann wird Ihre API (beispielsweise): + +* die Rechnung an einen Kunden des externen Entwicklers senden. +* das Geld einsammeln. +* eine Benachrichtigung an den API-Benutzer (den externen Entwickler) zurücksenden. + * Dies erfolgt durch Senden eines POST-Requests (von *Ihrer API*) an eine *externe API*, die von diesem externen Entwickler bereitgestellt wird (das ist der „Callback“). + +## Die normale **FastAPI**-Anwendung + +Sehen wir uns zunächst an, wie die normale API-Anwendung aussehen würde, bevor wir den Callback hinzufügen. + +Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und einen Query-Parameter `callback_url`, der die URL für den Callback enthält. + +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!} +``` + +!!! tip "Tipp" + Der Query-Parameter `callback_url` verwendet einen Pydantic-<a href="https://docs.pydantic.dev/latest/api/networks/" class="external-link" target="_blank">Url</a>-Typ. + +Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist. + +## Dokumentation des Callbacks + +Der tatsächliche Callback-Code hängt stark von Ihrer eigenen API-Anwendung ab. + +Und er wird wahrscheinlich von Anwendung zu Anwendung sehr unterschiedlich sein. + +Es könnten nur eine oder zwei Codezeilen sein, wie zum Beispiel: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Der möglicherweise wichtigste Teil des Callbacks besteht jedoch darin, sicherzustellen, dass Ihr API-Benutzer (der externe Entwickler) die *externe API* gemäß den Daten, die *Ihre API* im Requestbody des Callbacks senden wird, korrekt implementiert, usw. + +Als Nächstes fügen wir den Code hinzu, um zu dokumentieren, wie diese *externe API* aussehen sollte, um den Callback von *Ihrer API* zu empfangen. + +Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API angezeigt und zeigt externen Entwicklern, wie diese die *externe API* erstellen sollten. + +In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. + +!!! tip "Tipp" + Der eigentliche Callback ist nur ein HTTP-Request. + + Wenn Sie den Callback selbst implementieren, können Sie beispielsweise <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> oder <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a> verwenden. + +## Schreiben des Codes, der den Callback dokumentiert + +Dieser Code wird nicht in Ihrer Anwendung ausgeführt, wir benötigen ihn nur, um zu *dokumentieren*, wie diese *externe API* aussehen soll. + +Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatische Dokumentation für eine API erstellen. + +Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). + +!!! tip "Tipp" + Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. + + Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. + +### Einen Callback-`APIRouter` erstellen + +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!} +``` + +### Die Callback-*Pfadoperation* erstellen + +Um die Callback-*Pfadoperation* zu erstellen, verwenden Sie denselben `APIRouter`, den Sie oben erstellt haben. + +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!} +``` + +Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: + +* Es muss kein tatsächlicher Code vorhanden sein, da Ihre Anwendung diesen Code niemals aufruft. Sie wird nur zur Dokumentation der *externen API* verwendet. Die Funktion könnte also einfach `pass` enthalten. +* Der *Pfad* kann einen <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression" class="external-link" target="_blank">OpenAPI-3-Ausdruck</a> enthalten (mehr dazu weiter unten), wo er Variablen mit Parametern und Teilen des ursprünglichen Requests verwenden kann, der an *Ihre API* gesendet wurde. + +### Der Callback-Pfadausdruck + +Der Callback-*Pfad* kann einen <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression" class="external-link" target="_blank">OpenAPI-3-Ausdruck</a> enthalten, welcher Teile des ursprünglichen Requests enthalten kann, der an *Ihre API* gesendet wurde. + +In diesem Fall ist es der `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Wenn Ihr API-Benutzer (der externe Entwickler) also einen Request an *Ihre API* sendet, via: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +mit einem JSON-Körper: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +dann verarbeitet *Ihre API* die Rechnung und sendet irgendwann später einen Callback-Request an die `callback_url` (die *externe API*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +mit einem JSON-Body, der etwa Folgendes enthält: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie dem folgenden erwarten: + +```JSON +{ + "ok": true +} +``` + +!!! tip "Tipp" + Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). + +### Den Callback-Router hinzufügen + +An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejenige(n), die der *externe Entwickler* in der *externen API* implementieren sollte) im Callback-Router, den Sie oben erstellt haben. + +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!} +``` + +!!! tip "Tipp" + Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. + +### Es in der Dokumentation ansehen + +Jetzt können Sie Ihre Anwendung mit Uvicorn starten und auf <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> gehen. + +Sie sehen Ihre Dokumentation, einschließlich eines Abschnitts „Callbacks“ für Ihre *Pfadoperation*, der zeigt, wie die *externe API* aussehen sollte: + +<img src="/img/tutorial/openapi-callbacks/image01.png"> From cf101d48592f885771071358172bb1ee7270c2a6 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:17:32 +0100 Subject: [PATCH 202/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/testing-dependencies.md`=20(#?= =?UTF-8?q?10706)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/testing-dependencies.md | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 docs/de/docs/advanced/testing-dependencies.md diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..e7841b5f5 --- /dev/null +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -0,0 +1,81 @@ +# Testen mit Ersatz für Abhängigkeiten + +## Abhängigkeiten beim Testen überschreiben + +Es gibt einige Szenarien, in denen Sie beim Testen möglicherweise eine Abhängigkeit überschreiben möchten. + +Sie möchten nicht, dass die ursprüngliche Abhängigkeit ausgeführt wird (und auch keine der möglicherweise vorhandenen Unterabhängigkeiten). + +Stattdessen möchten Sie eine andere Abhängigkeit bereitstellen, die nur während Tests (möglicherweise nur bei einigen bestimmten Tests) verwendet wird und einen Wert bereitstellt, der dort verwendet werden kann, wo der Wert der ursprünglichen Abhängigkeit verwendet wurde. + +### Anwendungsfälle: Externer Service + +Ein Beispiel könnte sein, dass Sie einen externen Authentifizierungsanbieter haben, mit dem Sie sich verbinden müssen. + +Sie senden ihm ein Token und er gibt einen authentifizierten Benutzer zurück. + +Dieser Anbieter berechnet Ihnen möglicherweise Gebühren pro Anfrage, und der Aufruf könnte etwas länger dauern, als wenn Sie einen vordefinierten Scheinbenutzer für Tests hätten. + +Sie möchten den externen Anbieter wahrscheinlich einmal testen, ihn aber nicht unbedingt bei jedem weiteren ausgeführten Test aufrufen. + +In diesem Fall können Sie die Abhängigkeit, die diesen Anbieter aufruft, überschreiben und eine benutzerdefinierte Abhängigkeit verwenden, die einen Scheinbenutzer zurückgibt, nur für Ihre Tests. + +### Verwenden Sie das Attribut `app.dependency_overrides`. + +Für diese Fälle verfügt Ihre **FastAPI**-Anwendung über das Attribut `app.dependency_overrides`, bei diesem handelt sich um ein einfaches `dict`. + +Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüssel die ursprüngliche Abhängigkeit (eine Funktion) und als Wert Ihre Überschreibung der Abhängigkeit (eine andere Funktion) ein. + +Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. + +=== "Python 3.10+" + + ```Python hl_lines="26-27 30" + {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="28-29 32" + {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="29-30 33" + {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! tip "Tipp" + Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. + + Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. + + FastAPI kann sie in jedem Fall überschreiben. + +Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), indem Sie `app.dependency_overrides` auf ein leeres `dict` setzen: + +```Python +app.dependency_overrides = {} +``` + +!!! tip "Tipp" + Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. From d5a8d8faa481a770ce1a46ac45124ed987020a3e Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:17:40 +0100 Subject: [PATCH 203/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/testing-events.md`=20(#10704)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/testing-events.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 docs/de/docs/advanced/testing-events.md diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md new file mode 100644 index 000000000..f50093548 --- /dev/null +++ b/docs/de/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# Events testen: Hochfahren – Herunterfahren + +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!} +``` From 3a264f730bfcd2a5e31f1ccaf0d7f4897c509cc5 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:17:48 +0100 Subject: [PATCH 204/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/testing-websockets.md`=20(#10?= =?UTF-8?q?703)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/testing-websockets.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 docs/de/docs/advanced/testing-websockets.md diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..53de72f15 --- /dev/null +++ b/docs/de/docs/advanced/testing-websockets.md @@ -0,0 +1,12 @@ +# WebSockets testen + +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!} +``` + +!!! note "Hinweis" + Weitere Informationen finden Sie in der Starlette-Dokumentation zum <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Testen von WebSockets</a>. From f6fd035cef6e96c18e4ebb7167cb7306dd8d6831 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:17:58 +0100 Subject: [PATCH 205/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/websockets.md`=20(#10687)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/websockets.md | 224 ++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 docs/de/docs/advanced/websockets.md diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md new file mode 100644 index 000000000..e5e6a9d01 --- /dev/null +++ b/docs/de/docs/advanced/websockets.md @@ -0,0 +1,224 @@ +# WebSockets + +Sie können <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API" class="external-link" target="_blank">WebSockets</a> mit **FastAPI** verwenden. + +## `WebSockets` installieren + +Zuerst müssen Sie `WebSockets` installieren: + +<div class="termy"> + +```console +$ pip install websockets + +---> 100% +``` + +</div> + +## WebSockets-Client + +### In Produktion + +In Ihrem Produktionssystem haben Sie wahrscheinlich ein Frontend, das mit einem modernen Framework wie React, Vue.js oder Angular erstellt wurde. + +Und um über WebSockets mit Ihrem Backend zu kommunizieren, würden Sie wahrscheinlich die Werkzeuge Ihres Frontends verwenden. + +Oder Sie verfügen möglicherweise über eine native Mobile-Anwendung, die direkt in nativem Code mit Ihrem WebSocket-Backend kommuniziert. + +Oder Sie haben andere Möglichkeiten, mit dem WebSocket-Endpunkt zu kommunizieren. + +--- + +Für dieses Beispiel verwenden wir jedoch ein sehr einfaches HTML-Dokument mit etwas JavaScript, alles in einem langen String. + +Das ist natürlich nicht optimal und man würde das nicht in der Produktion machen. + +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!} +``` + +## Einen `websocket` erstellen + +Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: + +```Python hl_lines="1 46-47" +{!../../../docs_src/websockets/tutorial001.py!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.websockets import WebSocket` verwenden. + + **FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. + +## Nachrichten erwarten und Nachrichten senden + +In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. + +```Python hl_lines="48-52" +{!../../../docs_src/websockets/tutorial001.py!} +``` + +Sie können Binär-, Text- und JSON-Daten empfangen und senden. + +## Es ausprobieren + +Wenn Ihre Datei `main.py` heißt, führen Sie Ihre Anwendung so aus: + +<div class="termy"> + +```console +$ uvicorn main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +Öffnen Sie Ihren Browser unter <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>. + +Sie sehen eine einfache Seite wie: + +<img src="/img/tutorial/websockets/image01.png"> + +Sie können Nachrichten in das Eingabefeld tippen und absenden: + +<img src="/img/tutorial/websockets/image02.png"> + +Und Ihre **FastAPI**-Anwendung mit WebSockets antwortet: + +<img src="/img/tutorial/websockets/image03.png"> + +Sie können viele Nachrichten senden (und empfangen): + +<img src="/img/tutorial/websockets/image04.png"> + +Und alle verwenden dieselbe WebSocket-Verbindung. + +## Verwendung von `Depends` und anderen + +In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verwenden: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: + +=== "Python 3.10+" + + ```Python hl_lines="68-69 82" + {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="68-69 82" + {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="69-70 83" + {!> ../../../docs_src/websockets/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! info + Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. + + Sie können einen „Closing“-Code verwenden, aus den <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">gültigen Codes, die in der Spezifikation definiert sind</a>. + +### WebSockets mit Abhängigkeiten ausprobieren + +Wenn Ihre Datei `main.py` heißt, führen Sie Ihre Anwendung mit Folgendem aus: + +<div class="termy"> + +```console +$ uvicorn main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +Öffnen Sie Ihren Browser unter <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>. + +Dort können Sie einstellen: + +* Die „Item ID“, die im Pfad verwendet wird. +* Das „Token“, das als Query-Parameter verwendet wird. + +!!! tip "Tipp" + Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. + +Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfangen: + +<img src="/img/tutorial/websockets/image05.png"> + +## Verbindungsabbrüche und mehreren Clients handhaben + +Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. + +=== "Python 3.9+" + + ```Python hl_lines="79-81" + {!> ../../../docs_src/websockets/tutorial003_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="81-83" + {!> ../../../docs_src/websockets/tutorial003.py!} + ``` + +Zum Ausprobieren: + +* Öffnen Sie die Anwendung mit mehreren Browser-Tabs. +* Schreiben Sie Nachrichten in den Tabs. +* Schließen Sie dann einen der Tabs. + +Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients erhalten eine Nachricht wie: + +``` +Client #1596980209979 left the chat +``` + +!!! tip "Tipp" + Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. + + Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. + + Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> an. + +## Mehr Informationen + +Weitere Informationen zu Optionen finden Sie in der Dokumentation von Starlette: + +* <a href="https://www.starlette.io/websockets/" class="external-link" target="_blank">Die `WebSocket`-Klasse</a>. +* <a href="https://www.starlette.io/endpoints/#websocketendpoint" class="external-link" target="_blank">Klassen-basierte Handhabung von WebSockets</a>. From 38cdebfdaa9b49542815b433b423ceb77623ebd2 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:18:06 +0100 Subject: [PATCH 206/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/sub-applications.md`=20(#1067?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/sub-applications.md | 73 +++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 docs/de/docs/advanced/sub-applications.md diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md new file mode 100644 index 000000000..7dfaaa0cd --- /dev/null +++ b/docs/de/docs/advanced/sub-applications.md @@ -0,0 +1,73 @@ +# Unteranwendungen – Mounts + +Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen OpenAPI und deren eigenen Dokumentationsoberflächen benötigen, können Sie eine Hauptanwendung haben und dann eine (oder mehrere) Unteranwendung(en) „mounten“. + +## Mounten einer **FastAPI**-Anwendung + +„Mounten“ („Einhängen“) bedeutet das Hinzufügen einer völlig „unabhängigen“ Anwendung an einem bestimmten Pfad, die sich dann um die Handhabung aller unter diesem Pfad liegenden _Pfadoperationen_ kümmert, welche in dieser Unteranwendung deklariert sind. + +### Hauptanwendung + +Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: + +```Python hl_lines="3 6-8" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### Unteranwendung + +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!} +``` + +### Die Unteranwendung mounten + +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!} +``` + +### Es in der automatischen API-Dokumentation betrachten + +Führen Sie nun `uvicorn` mit der Hauptanwendung aus. Wenn Ihre Datei `main.py` lautet, wäre das: + +<div class="termy"> + +```console +$ uvicorn main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +Und öffnen Sie die Dokumentation unter <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Sie sehen die automatische API-Dokumentation für die Hauptanwendung, welche nur deren eigene _Pfadoperationen_ anzeigt: + +<img src="/img/tutorial/sub-applications/image01.png"> + +Öffnen Sie dann die Dokumentation für die Unteranwendung unter <a href="http://127.0.0.1:8000/subapi/docs" class="external-link" target="_blank">http://127.0.0.1:8000/subapi/docs</a>. + +Sie sehen die automatische API-Dokumentation für die Unteranwendung, welche nur deren eigene _Pfadoperationen_ anzeigt, alle unter dem korrekten Unterpfad-Präfix `/subapi`: + +<img src="/img/tutorial/sub-applications/image02.png"> + +Wenn Sie versuchen, mit einer der beiden Benutzeroberflächen zu interagieren, funktionieren diese ordnungsgemäß, da der Browser mit jeder spezifischen Anwendung oder Unteranwendung kommunizieren kann. + +### Technische Details: `root_path` + +Wenn Sie eine Unteranwendung wie oben beschrieben mounten, kümmert sich FastAPI darum, den Mount-Pfad für die Unteranwendung zu kommunizieren, mithilfe eines Mechanismus aus der ASGI-Spezifikation namens `root_path`. + +Auf diese Weise weiß die Unteranwendung, dass sie dieses Pfadpräfix für die Benutzeroberfläche der Dokumentation verwenden soll. + +Und die Unteranwendung könnte auch ihre eigenen gemounteten Unteranwendungen haben und alles würde korrekt funktionieren, da FastAPI sich um alle diese `root_path`s automatisch kümmert. + +Mehr über den `root_path` und dessen explizite Verwendung erfahren Sie im Abschnitt [Hinter einem Proxy](behind-a-proxy.md){.internal-link target=_blank}. From 3b2160b69d643818340bdbcb54e793b1dc03017d Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:18:15 +0100 Subject: [PATCH 207/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/middleware.md`=20(#10668)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/middleware.md | 99 +++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 docs/de/docs/advanced/middleware.md diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md new file mode 100644 index 000000000..2c4e8542a --- /dev/null +++ b/docs/de/docs/advanced/middleware.md @@ -0,0 +1,99 @@ +# Fortgeschrittene Middleware + +Im Haupttutorial haben Sie gelesen, wie Sie Ihrer Anwendung [benutzerdefinierte Middleware](../tutorial/middleware.md){.internal-link target=_blank} hinzufügen können. + +Und dann auch, wie man [CORS mittels der `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank} handhabt. + +In diesem Abschnitt werden wir sehen, wie man andere Middlewares verwendet. + +## ASGI-Middleware hinzufügen + +Da **FastAPI** auf Starlette basiert und die <abbr title="Asynchronous Server Gateway Interface">ASGI</abbr>-Spezifikation implementiert, können Sie jede ASGI-Middleware verwenden. + +Eine Middleware muss nicht speziell für FastAPI oder Starlette gemacht sein, um zu funktionieren, solange sie der ASGI-Spezifikation genügt. + +Im Allgemeinen handelt es sich bei ASGI-Middleware um Klassen, die als erstes Argument eine ASGI-Anwendung erwarten. + +In der Dokumentation für ASGI-Middlewares von Drittanbietern wird Ihnen wahrscheinlich gesagt, etwa Folgendes zu tun: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Aber FastAPI (eigentlich Starlette) bietet eine einfachere Möglichkeit, welche sicherstellt, dass die internen Middlewares zur Behandlung von Serverfehlern und benutzerdefinierten Exceptionhandlern ordnungsgemäß funktionieren. + +Dazu verwenden Sie `app.add_middleware()` (wie schon im Beispiel für CORS gesehen). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` empfängt eine Middleware-Klasse als erstes Argument und dann alle weiteren Argumente, die an die Middleware übergeben werden sollen. + +## Integrierte Middleware + +**FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. + +!!! note "Technische Details" + Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. + + **FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. + +## `HTTPSRedirectMiddleware` + +Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müssen. + +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!} +``` + +## `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!} +``` + +Die folgenden Argumente werden unterstützt: + +* `allowed_hosts` – Eine Liste von Domain-Namen, die als Hostnamen zulässig sein sollten. Wildcard-Domains wie `*.example.com` werden unterstützt, um Subdomains zu matchen. Um jeden Hostnamen zu erlauben, verwenden Sie entweder `allowed_hosts=["*"]` oder lassen Sie diese Middleware weg. + +Wenn ein eingehender Request nicht korrekt validiert wird, wird eine „400“-Response gesendet. + +## `GZipMiddleware` + +Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding`-Header enthalten. + +Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. + +```Python hl_lines="2 6" +{!../../../docs_src/advanced_middleware/tutorial003.py!} +``` + +Die folgenden Argumente werden unterstützt: + +* `minimum_size` – Antworten, die kleiner als diese Mindestgröße in Bytes sind, nicht per GZip komprimieren. Der Defaultwert ist `500`. + +## Andere Middlewares + +Es gibt viele andere ASGI-Middlewares. + +Zum Beispiel: + +* <a href="https://docs.sentry.io/platforms/python/guides/fastapi/" class="external-link" target="_blank">Sentry</a> +* <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorns `ProxyHeadersMiddleware`</a> +* <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">MessagePack</a> + +Um mehr über weitere verfügbare Middlewares herauszufinden, besuchen Sie <a href="https://www.starlette.io/middleware/" class="external-link" target="_blank">Starlettes Middleware-Dokumentation</a> und die <a href="https://github.com/florimondmanca/awesome-asgi" class="external-link" target="_blank">ASGI Awesome List</a>. From 92f36da16a3b1534e6ef81d5619938c237e73158 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:18:23 +0100 Subject: [PATCH 208/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/dataclasses.md`=20(#10667)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/dataclasses.md | 98 ++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 docs/de/docs/advanced/dataclasses.md diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md new file mode 100644 index 000000000..c78a6d3dd --- /dev/null +++ b/docs/de/docs/advanced/dataclasses.md @@ -0,0 +1,98 @@ +# Verwendung von Datenklassen + +FastAPI basiert auf **Pydantic** und ich habe Ihnen gezeigt, wie Sie Pydantic-Modelle verwenden können, um Requests und Responses zu deklarieren. + +Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von <a href="https://docs.python.org/3/library/dataclasses.html" class="external-link" target="_blank">`dataclasses`</a>: + +```Python hl_lines="1 7-12 19-20" +{!../../../docs_src/dataclasses/tutorial001.py!} +``` + +Das ist dank **Pydantic** ebenfalls möglich, da es <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">`dataclasses` intern unterstützt</a>. + +Auch wenn im obige Code Pydantic nicht explizit vorkommt, verwendet FastAPI Pydantic, um diese Standard-Datenklassen in Pydantics eigene Variante von Datenklassen zu konvertieren. + +Und natürlich wird das gleiche unterstützt: + +* Validierung der Daten +* Serialisierung der Daten +* Dokumentation der Daten, usw. + +Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt. + +!!! info + Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. + + Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. + + Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 + +## Datenklassen als `response_model` + +Sie können `dataclasses` auch im Parameter `response_model` verwenden: + +```Python hl_lines="1 7-13 19" +{!../../../docs_src/dataclasses/tutorial002.py!} +``` + +Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. + +Auf diese Weise wird deren Schema in der Benutzeroberfläche der API-Dokumentation angezeigt: + +<img src="/img/tutorial/dataclasses/image01.png"> + +## Datenklassen in verschachtelten Datenstrukturen + +Sie können `dataclasses` auch mit anderen Typannotationen kombinieren, um verschachtelte Datenstrukturen zu erstellen. + +In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von `dataclasses` verwenden. Zum Beispiel, wenn Sie Fehler in der automatisch generierten API-Dokumentation haben. + +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!} +``` + +1. Wir importieren `field` weiterhin von Standard-`dataclasses`. + +2. `pydantic.dataclasses` ist ein direkter Ersatz für `dataclasses`. + +3. Die Datenklasse `Author` enthält eine Liste von `Item`-Datenklassen. + +4. Die Datenklasse `Author` wird im `response_model`-Parameter verwendet. + +5. Sie können andere Standard-Typannotationen mit Datenklassen als Requestbody verwenden. + + In diesem Fall handelt es sich um eine Liste von `Item`-Datenklassen. + +6. Hier geben wir ein Dictionary zurück, das `items` enthält, welches eine Liste von Datenklassen ist. + + FastAPI ist weiterhin in der Lage, die Daten nach JSON zu <abbr title="Konvertieren der Daten in ein übertragbares Format">serialisieren</abbr>. + +7. Hier verwendet das `response_model` als Typannotation eine Liste von `Author`-Datenklassen. + + Auch hier können Sie `dataclasses` mit Standard-Typannotationen kombinieren. + +8. Beachten Sie, dass diese *Pfadoperation-Funktion* reguläres `def` anstelle von `async def` verwendet. + + Wie immer können Sie in FastAPI `def` und `async def` beliebig kombinieren. + + Wenn Sie eine Auffrischung darüber benötigen, wann welche Anwendung sinnvoll ist, lesen Sie den Abschnitt „In Eile?“ in der Dokumentation zu [`async` und `await`](../async.md#in-eile){.internal-link target=_blank}. + +9. Diese *Pfadoperation-Funktion* gibt keine Datenklassen zurück (obwohl dies möglich wäre), sondern eine Liste von Dictionarys mit internen Daten. + + FastAPI verwendet den Parameter `response_model` (der Datenklassen enthält), um die Response zu konvertieren. + +Sie können `dataclasses` mit anderen Typannotationen auf vielfältige Weise kombinieren, um komplexe Datenstrukturen zu bilden. + +Weitere Einzelheiten finden Sie in den Bemerkungen im Quellcode oben. + +## Mehr erfahren + +Sie können `dataclasses` auch mit anderen Pydantic-Modellen kombinieren, von ihnen erben, sie in Ihre eigenen Modelle einbinden, usw. + +Weitere Informationen finden Sie in der <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/" class="external-link" target="_blank">Pydantic-Dokumentation zu Datenklassen</a>. + +## Version + +Dies ist verfügbar seit FastAPI-Version `0.67.0`. 🔖 From 3a327ccfb525646830bf174e8c16456458a88dc6 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:18:32 +0100 Subject: [PATCH 209/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/using-request-directly.md`=20?= =?UTF-8?q?(#10653)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/using-request-directly.md | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 docs/de/docs/advanced/using-request-directly.md diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..f40f5d4be --- /dev/null +++ b/docs/de/docs/advanced/using-request-directly.md @@ -0,0 +1,52 @@ +# Den Request direkt verwenden + +Bisher haben Sie die Teile des Requests, die Sie benötigen, mithilfe von deren Typen deklariert. + +Daten nehmend von: + +* Dem Pfad als Parameter. +* Headern. +* Cookies. +* usw. + +Und indem Sie das tun, validiert **FastAPI** diese Daten, konvertiert sie und generiert automatisch Dokumentation für Ihre API. + +Es gibt jedoch Situationen, in denen Sie möglicherweise direkt auf das `Request`-Objekt zugreifen müssen. + +## Details zum `Request`-Objekt + +Da **FastAPI** unter der Haube eigentlich **Starlette** ist, mit einer Ebene von mehreren Tools darüber, können Sie Starlette's <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request`</a>-Objekt direkt verwenden, wenn Sie es benötigen. + +Das bedeutet allerdings auch, dass, wenn Sie Daten direkt vom `Request`-Objekt nehmen (z. B. dessen Body lesen), diese von FastAPI nicht validiert, konvertiert oder dokumentiert werden (mit OpenAPI, für die automatische API-Benutzeroberfläche). + +Obwohl jeder andere normal deklarierte Parameter (z. B. der Body, mit einem Pydantic-Modell) dennoch validiert, konvertiert, annotiert, usw. werden würde. + +Es gibt jedoch bestimmte Fälle, in denen es nützlich ist, auf das `Request`-Objekt zuzugreifen. + +## Das `Request`-Objekt direkt verwenden + +Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfadoperation-Funktion* zugreifen. + +Dazu müssen Sie direkt auf den Request zugreifen. + +```Python hl_lines="1 7-8" +{!../../../docs_src/using_request_directly/tutorial001.py!} +``` + +Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. + +!!! tip "Tipp" + Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. + + Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. + + Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. + +## `Request`-Dokumentation + +Weitere Details zum <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation</a>. + +!!! note "Technische Details" + Sie können auch `from starlette.requests import Request` verwenden. + + **FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. From e8537099ac231660b3d9a4a4fb06a4a26c04b95e Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:18:40 +0100 Subject: [PATCH 210/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/security/index.md`=20(#10635)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/security/index.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 docs/de/docs/advanced/security/index.md diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md new file mode 100644 index 000000000..a3c975bed --- /dev/null +++ b/docs/de/docs/advanced/security/index.md @@ -0,0 +1,16 @@ +# Fortgeschrittene Sicherheit + +## Zusatzfunktionen + +Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit. + +!!! tip "Tipp" + Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + + Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +## Lesen Sie zuerst das Tutorial + +In den nächsten Abschnitten wird davon ausgegangen, dass Sie das Haupt-[Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} bereits gelesen haben. + +Sie basieren alle auf den gleichen Konzepten, ermöglichen jedoch einige zusätzliche Funktionalitäten. From 8ee29c54c93b3ae12c03ccc6b7cea8017b3d494c Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:18:49 +0100 Subject: [PATCH 211/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/advanced-dependencies.md`=20(?= =?UTF-8?q?#10633)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../de/docs/advanced/advanced-dependencies.md | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 docs/de/docs/advanced/advanced-dependencies.md diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..33b93b332 --- /dev/null +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -0,0 +1,138 @@ +# Fortgeschrittene Abhängigkeiten + +## Parametrisierte Abhängigkeiten + +Alle Abhängigkeiten, die wir bisher gesehen haben, waren festgelegte Funktionen oder Klassen. + +Es kann jedoch Fälle geben, in denen Sie Parameter für eine Abhängigkeit festlegen möchten, ohne viele verschiedene Funktionen oder Klassen zu deklarieren. + +Stellen wir uns vor, wir möchten eine Abhängigkeit haben, die prüft, ob ein Query-Parameter `q` einen vordefinierten Inhalt hat. + +Aber wir wollen diesen vordefinierten Inhalt per Parameter festlegen können. + +## Eine „aufrufbare“ Instanz + +In Python gibt es eine Möglichkeit, eine Instanz einer Klasse „aufrufbar“ („callable“) zu machen. + +Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Klasse. + +Dazu deklarieren wir eine Methode `__call__`: + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. + +## Die Instanz parametrisieren + +Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. + +## Eine Instanz erstellen + +Wir könnten eine Instanz dieser Klasse erstellen mit: + +=== "Python 3.9+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. + +## Die Instanz als Abhängigkeit verwenden + +Dann könnten wir diesen `checker` in einem `Depends(checker)` anstelle von `Depends(FixedContentQueryChecker)` verwenden, da die Abhängigkeit die Instanz `checker` und nicht die Klasse selbst ist. + +Und beim Auflösen der Abhängigkeit ruft **FastAPI** diesen `checker` wie folgt auf: + +```Python +checker(q="somequery") +``` + +... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: + +=== "Python 3.9+" + + ```Python hl_lines="22" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +!!! tip "Tipp" + Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. + + Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. + + In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. + + Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. From 85a868d5224baecbe86db4f995016a6cd390d474 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:18:58 +0100 Subject: [PATCH 212/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/response-change-status-code.m?= =?UTF-8?q?d`=20(#10632)?= 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/de/docs/advanced/response-change-status-code.md diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..bba908a3e --- /dev/null +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -0,0 +1,33 @@ +# Response – Statuscode ändern + +Sie haben wahrscheinlich schon vorher gelesen, dass Sie einen Standard-[Response-Statuscode](../tutorial/response-status-code.md){.internal-link target=_blank} festlegen können. + +In manchen Fällen müssen Sie jedoch einen anderen als den Standard-Statuscode zurückgeben. + +## Anwendungsfall + +Stellen Sie sich zum Beispiel vor, Sie möchten standardmäßig den HTTP-Statuscode „OK“ `200` zurückgeben. + +Wenn die Daten jedoch nicht vorhanden waren, möchten Sie diese erstellen und den HTTP-Statuscode „CREATED“ `201` zurückgeben. + +Sie möchten aber dennoch in der Lage sein, die von Ihnen zurückgegebenen Daten mit einem `response_model` zu filtern und zu konvertieren. + +In diesen Fällen können Sie einen `Response`-Parameter verwenden. + +## Einen `Response`-Parameter verwenden + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies und Header tun können). + +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!} +``` + +Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um den Statuscode (auch Cookies und Header) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und den Statuscode darin festlegen. Bedenken Sie jedoch, dass der gewinnt, welcher zuletzt gesetzt wird. From 8de82dc8d6ae09c251e920ee450fb61b1b8844fc Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:19:06 +0100 Subject: [PATCH 213/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/response-headers.md`=20(#1062?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/response-headers.md | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 docs/de/docs/advanced/response-headers.md diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md new file mode 100644 index 000000000..6f4760e7f --- /dev/null +++ b/docs/de/docs/advanced/response-headers.md @@ -0,0 +1,42 @@ +# Response-Header + +## Verwenden Sie einen `Response`-Parameter + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies tun können). + +Und dann können Sie Header in diesem *vorübergehenden* Response-Objekt festlegen. + +```Python hl_lines="1 7-8" +{!../../../docs_src/response_headers/tutorial002.py!} +``` + +Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um die Header (auch Cookies und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und darin Header (und Cookies) festlegen. + +## Eine `Response` direkt zurückgeben + +Sie können auch Header hinzufügen, wenn Sie eine `Response` direkt zurückgeben. + +Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} beschrieben und übergeben Sie die Header als zusätzlichen Parameter: + +```Python hl_lines="10-12" +{!../../../docs_src/response_headers/tutorial001.py!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + + Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +## Benutzerdefinierte Header + +Beachten Sie, dass benutzerdefinierte proprietäre Header <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">mittels des Präfix 'X-'</a> hinzugefügt werden können. + +Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen können soll, müssen Sie diese zu Ihren CORS-Konfigurationen hinzufügen (weitere Informationen finden Sie unter [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), unter Verwendung des Parameters `expose_headers`, dokumentiert in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlettes CORS-Dokumentation</a>. From 8d211155a071bdede150e14290de691a0c43e1f3 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:19:17 +0100 Subject: [PATCH 214/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/response-cookies.md`=20(#1062?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/response-cookies.md | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 docs/de/docs/advanced/response-cookies.md diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md new file mode 100644 index 000000000..0f09bd444 --- /dev/null +++ b/docs/de/docs/advanced/response-cookies.md @@ -0,0 +1,49 @@ +# Response-Cookies + +## Einen `Response`-Parameter verwenden + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren. + +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!} +``` + +Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um die Cookies (auch Header und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den `Response`-Parameter auch in Abhängigkeiten deklarieren und darin Cookies (und Header) setzen. + +## Eine `Response` direkt zurückgeben + +Sie können Cookies auch erstellen, wenn Sie eine `Response` direkt in Ihrem Code zurückgeben. + +Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} beschrieben. + +Setzen Sie dann Cookies darin und geben Sie sie dann zurück: + +```Python hl_lines="10-12" +{!../../../docs_src/response_cookies/tutorial001.py!} +``` + +!!! tip "Tipp" + Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. + + Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. + + Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. + +### Mehr Informationen + +!!! note "Technische Details" + Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + + Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">Dokumentation in Starlette</a> an. From 552197a41777ddf19d4c59addda624e29584981b Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:19:26 +0100 Subject: [PATCH 215/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/additional-responses.md`=20(#?= =?UTF-8?q?10626)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/additional-responses.md | 240 ++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 docs/de/docs/advanced/additional-responses.md diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md new file mode 100644 index 000000000..2bfcfab33 --- /dev/null +++ b/docs/de/docs/advanced/additional-responses.md @@ -0,0 +1,240 @@ +# Zusätzliche Responses in OpenAPI + +!!! warning "Achtung" + Dies ist ein eher fortgeschrittenes Thema. + + Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. + +Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren. + +Diese zusätzlichen Responses werden in das OpenAPI-Schema aufgenommen, sodass sie auch in der API-Dokumentation erscheinen. + +Für diese zusätzlichen Responses müssen Sie jedoch sicherstellen, dass Sie eine `Response`, wie etwa `JSONResponse`, direkt zurückgeben, mit Ihrem Statuscode und Inhalt. + +## Zusätzliche Response mit `model` + +Sie können Ihren *Pfadoperation-Dekoratoren* einen Parameter `responses` übergeben. + +Der nimmt ein `dict` entgegen, die Schlüssel sind Statuscodes für jede Response, wie etwa `200`, und die Werte sind andere `dict`s mit den Informationen für jede Response. + +Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein Pydantic-Modell enthält, genau wie `response_model`. + +**FastAPI** nimmt dieses Modell, generiert dessen JSON-Schema und fügt es an der richtigen Stelle in OpenAPI ein. + +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!} +``` + +!!! note "Hinweis" + Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. + +!!! info + Der `model`-Schlüssel ist nicht Teil von OpenAPI. + + **FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. + + Die richtige Stelle ist: + + * Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: + * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: + * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. + * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. + +Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten: + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Die Schemas werden von einer anderen Stelle innerhalb des OpenAPI-Schemas referenziert: + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Zusätzliche Medientypen für die Haupt-Response + +Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientypen für dieselbe Haupt-Response hinzuzufügen. + +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!} +``` + +!!! note "Hinweis" + Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. + +!!! info + Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). + + Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. + +## Informationen kombinieren + +Sie können auch Response-Informationen von mehreren Stellen kombinieren, einschließlich der Parameter `response_model`, `status_code` und `responses`. + +Sie können ein `response_model` deklarieren, indem Sie den Standardstatuscode `200` (oder bei Bedarf einen benutzerdefinierten) verwenden und dann zusätzliche Informationen für dieselbe Response in `responses` direkt im OpenAPI-Schema deklarieren. + +**FastAPI** behält die zusätzlichen Informationen aus `responses` und kombiniert sie mit dem JSON-Schema aus Ihrem Modell. + +Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, die ein Pydantic-Modell verwendet und über eine benutzerdefinierte Beschreibung (`description`) verfügt. + +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!} +``` + +Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: + +<img src="/img/tutorial/additional-responses/image01.png"> + +## Vordefinierte und benutzerdefinierte Responses kombinieren + +Möglicherweise möchten Sie einige vordefinierte Responses haben, die für viele *Pfadoperationen* gelten, Sie möchten diese jedoch mit benutzerdefinierten Responses kombinieren, die für jede *Pfadoperation* erforderlich sind. + +In diesen Fällen können Sie die Python-Technik zum „Entpacken“ eines `dict`s mit `**dict_to_unpack` verwenden: + +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Hier wird `new_dict` alle Schlüssel-Wert-Paare von `old_dict` plus das neue Schlüssel-Wert-Paar enthalten: + +```Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoperationen* wiederverwenden und sie mit zusätzlichen benutzerdefinierten Responses kombinieren. + +Zum Beispiel: + +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` + +## Weitere Informationen zu OpenAPI-Responses + +Um zu sehen, was genau Sie in die Responses aufnehmen können, können Sie die folgenden Abschnitte in der OpenAPI-Spezifikation überprüfen: + +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject" class="external-link" target="_blank">OpenAPI Responses Object</a>, enthält das `Response Object`. +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject" class="external-link" target="_blank">OpenAPI Response Object</a>, Sie können alles davon direkt in jede Response innerhalb Ihres `responses`-Parameter einfügen. Einschließlich `description`, `headers`, `content` (darin deklarieren Sie verschiedene Medientypen und JSON-Schemas) und `links`. From 7c10c1cc0159f5a8022f5d02153816374e894e55 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:19:36 +0100 Subject: [PATCH 216/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/response-directly.md`=20(#106?= =?UTF-8?q?18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/response-directly.md | 63 ++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 docs/de/docs/advanced/response-directly.md diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md new file mode 100644 index 000000000..13bca7825 --- /dev/null +++ b/docs/de/docs/advanced/response-directly.md @@ -0,0 +1,63 @@ +# Eine Response direkt zurückgeben + +Wenn Sie eine **FastAPI** *Pfadoperation* erstellen, können Sie normalerweise beliebige Daten davon zurückgeben: ein `dict`, eine `list`e, ein Pydantic-Modell, ein Datenbankmodell, usw. + +Standardmäßig konvertiert **FastAPI** diesen Rückgabewert automatisch nach JSON, mithilfe des `jsonable_encoder`, der in [JSON-kompatibler Encoder](../tutorial/encoder.md){.internal-link target=_blank} erläutert wird. + +Dann würde es hinter den Kulissen diese JSON-kompatiblen Daten (z. B. ein `dict`) in eine `JSONResponse` einfügen, die zum Senden der Response an den Client verwendet würde. + +Sie können jedoch direkt eine `JSONResponse` von Ihren *Pfadoperationen* zurückgeben. + +Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookies zurückzugeben. + +## Eine `Response` zurückgeben + +Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. + +!!! tip "Tipp" + `JSONResponse` selbst ist eine Unterklasse von `Response`. + +Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten. + +Es wird keine Datenkonvertierung mit Pydantic-Modellen durchführen, es wird den Inhalt nicht in irgendeinen Typ konvertieren, usw. + +Dadurch haben Sie viel Flexibilität. Sie können jeden Datentyp zurückgeben, jede Datendeklaration oder -validierung überschreiben, usw. + +## Verwendung des `jsonable_encoder` in einer `Response` + +Da **FastAPI** keine Änderungen an einer von Ihnen zurückgegebenen `Response` vornimmt, müssen Sie sicherstellen, dass deren Inhalt dafür bereit ist. + +Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen, ohne es zuvor in ein `dict` zu konvertieren, bei dem alle Datentypen (wie `datetime`, `UUID`, usw.) in JSON-kompatible Typen konvertiert wurden. + +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!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +## Eine benutzerdefinierte `Response` zurückgeben + +Das obige Beispiel zeigt alle Teile, die Sie benötigen, ist aber noch nicht sehr nützlich, da Sie das `item` einfach direkt hätten zurückgeben können, und **FastAPI** würde es für Sie in eine `JSONResponse` einfügen, es in ein `dict` konvertieren, usw. All das standardmäßig. + +Sehen wir uns nun an, wie Sie damit eine benutzerdefinierte Response zurückgeben können. + +Nehmen wir an, Sie möchten eine <a href="https://en.wikipedia.org/wiki/XML" class="external-link" target="_blank">XML</a>-Response zurückgeben. + +Sie könnten Ihren XML-Inhalt als String in eine `Response` einfügen und sie zurückgeben: + +```Python hl_lines="1 18" +{!../../../docs_src/response_directly/tutorial002.py!} +``` + +## Anmerkungen + +Wenn Sie eine `Response` direkt zurücksenden, werden deren Daten weder validiert, konvertiert (serialisiert), noch automatisch dokumentiert. + +Sie können sie aber trotzdem wie unter [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} beschrieben dokumentieren. + +In späteren Abschnitten erfahren Sie, wie Sie diese benutzerdefinierten `Response`s verwenden/deklarieren und gleichzeitig über automatische Datenkonvertierung, Dokumentation, usw. verfügen. From fd4a727e452a43de686a6a4dcd15cdc74697e36e Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:19:44 +0100 Subject: [PATCH 217/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/index.md`=20(#10611)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/index.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 docs/de/docs/advanced/index.md diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md new file mode 100644 index 000000000..048e31e06 --- /dev/null +++ b/docs/de/docs/advanced/index.md @@ -0,0 +1,33 @@ +# Handbuch für fortgeschrittene Benutzer + +## Zusatzfunktionen + +Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} sollte ausreichen, um Ihnen einen Überblick über alle Hauptfunktionen von **FastAPI** zu geben. + +In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. + +!!! tip "Tipp" + Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + + Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +## Lesen Sie zuerst das Tutorial + +Sie können immer noch die meisten Funktionen in **FastAPI** mit den Kenntnissen aus dem Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} nutzen. + +Und in den nächsten Abschnitten wird davon ausgegangen, dass Sie es bereits gelesen haben und dass Sie diese Haupt-Ideen kennen. + +## Externe Kurse + +Obwohl das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} und dieses **Handbuch für fortgeschrittene Benutzer** als geführtes Tutorial (wie ein Buch) geschrieben sind und für Sie ausreichen sollten, um **FastAPI zu lernen**, möchten Sie sie vielleicht durch zusätzliche Kurse ergänzen. + +Oder Sie belegen einfach lieber andere Kurse, weil diese besser zu Ihrem Lernstil passen. + +Einige Kursanbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, dies gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Gemeinschaft** (Sie), da diese Ihnen nicht nur eine **gute Lernerfahrung** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework verfügen **, FastAPI. 🙇 + +Vielleicht möchten Sie ihre Kurse ausprobieren: + +* <a href="https://training.talkpython.fm/fastapi-courses" class="external-link" target="_blank">Talk Python Training</a> +* <a href="https://testdriven.io/courses/tdd-fastapi/" class="external-link" target="_blank">Test-Driven Development</a> From de25cc7fa99b565c968b8395464e31488d12c8ec Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:19:53 +0100 Subject: [PATCH 218/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/schema-extra-example.md`=20(#?= =?UTF-8?q?10597)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/schema-extra-example.md | 326 ++++++++++++++++++ 1 file changed, 326 insertions(+) create mode 100644 docs/de/docs/tutorial/schema-extra-example.md diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..e8bfc9876 --- /dev/null +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -0,0 +1,326 @@ +# Beispiel-Request-Daten deklarieren + +Sie können Beispiele für die Daten deklarieren, die Ihre Anwendung empfangen kann. + +Hier sind mehrere Möglichkeiten, das zu tun. + +## Zusätzliche JSON-Schemadaten in Pydantic-Modellen + +Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden. + +=== "Python 3.10+ Pydantic v2" + + ```Python hl_lines="13-24" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} + ``` + +=== "Python 3.10+ Pydantic v1" + + ```Python hl_lines="13-23" + {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} + ``` + +=== "Python 3.8+ Pydantic v2" + + ```Python hl_lines="15-26" + {!> ../../../docs_src/schema_extra_example/tutorial001.py!} + ``` + +=== "Python 3.8+ Pydantic v1" + + ```Python hl_lines="15-25" + {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} + ``` + +Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet. + +=== "Pydantic v2" + + In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic-Dokumentation: Configuration</a>. + + Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. + +=== "Pydantic v1" + + In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic-Dokumentation: Schema customization</a>. + + Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. + +!!! tip "Tipp" + Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. + + Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen. + +!!! info + OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist. + + Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr> und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓 + + Mehr erfahren Sie am Ende dieser Seite. + +## Zusätzliche Argumente für `Field` + +Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren: + +=== "Python 3.10+" + + ```Python hl_lines="2 8-11" + {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 10-13" + {!> ../../../docs_src/schema_extra_example/tutorial002.py!} + ``` + +## `examples` im JSON-Schema – OpenAPI + +Bei Verwendung von: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen deklarieren, die zu ihren **JSON-Schemas** innerhalb von **OpenAPI** hinzugefügt werden. + +### `Body` mit `examples` + +Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält: + +=== "Python 3.10+" + + ```Python hl_lines="22-29" + {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="22-29" + {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="23-30" + {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="20-27" + {!> ../../../docs_src/schema_extra_example/tutorial003.py!} + ``` + +### Beispiel in der Dokumentations-Benutzeroberfläche + +Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen: + +<img src="/img/tutorial/body-fields/image01.png"> + +### `Body` mit mehreren `examples` + +Sie können natürlich auch mehrere `examples` übergeben: + +=== "Python 3.10+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23-38" + {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24-39" + {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="21-36" + {!> ../../../docs_src/schema_extra_example/tutorial004.py!} + ``` + +Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten. + +<abbr title="26.08.2023">Während dies geschrieben wird</abbr>, unterstützt Swagger UI, das für die Anzeige der Dokumentations-Benutzeroberfläche zuständige Tool, jedoch nicht die Anzeige mehrerer Beispiele für die Daten in **JSON Schema**. Aber lesen Sie unten für einen Workaround weiter. + +### OpenAPI-spezifische `examples` + +Schon bevor **JSON Schema** `examples` unterstützte, unterstützte OpenAPI ein anderes Feld, das auch `examples` genannt wurde. + +Diese **OpenAPI-spezifischen** `examples` finden sich in einem anderen Abschnitt der OpenAPI-Spezifikation. Sie sind **Details für jede *Pfadoperation***, nicht für jedes JSON-Schema. + +Und Swagger UI unterstützt dieses spezielle Feld `examples` schon seit einiger Zeit. Sie können es also verwenden, um verschiedene **Beispiele in der Benutzeroberfläche der Dokumentation anzuzeigen**. + +Das Format dieses OpenAPI-spezifischen Felds `examples` ist ein `dict` mit **mehreren Beispielen** (anstelle einer `list`e), jedes mit zusätzlichen Informationen, die auch zu **OpenAPI** hinzugefügt werden. + +Dies erfolgt nicht innerhalb jedes in OpenAPI enthaltenen JSON-Schemas, sondern außerhalb, in der *Pfadoperation*. + +### Verwendung des Parameters `openapi_examples` + +Sie können die OpenAPI-spezifischen `examples` in FastAPI mit dem Parameter `openapi_examples` deklarieren, für: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +Die Schlüssel des `dict` identifizieren jedes Beispiel, und jeder Wert (`"value"`) ist ein weiteres `dict`. + +Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten: + +* `summary`: Kurze Beschreibung für das Beispiel. +* `description`: Eine lange Beschreibung, die Markdown-Text enthalten kann. +* `value`: Dies ist das tatsächlich angezeigte Beispiel, z. B. ein `dict`. +* `externalValue`: Alternative zu `value`, eine URL, die auf das Beispiel verweist. Allerdings wird dies möglicherweise nicht von so vielen Tools unterstützt wie `value`. + +Sie können es so verwenden: + +=== "Python 3.10+" + + ```Python hl_lines="23-49" + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23-49" + {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24-50" + {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="19-45" + {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} + ``` + +=== "Python 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!} + ``` + +### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche + +Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehen: + +<img src="/img/tutorial/body-fields/image02.png"> + +## Technische Details + +!!! tip "Tipp" + Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. + + Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war. + + Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓 + +!!! warning "Achtung" + Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. + + Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne. + +Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**. + +JSON Schema hatte keine `examples`, daher fügte OpenAPI seiner eigenen modifizierten Version ein eigenes `example`-Feld hinzu. + +OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Spezifikation hinzu: + +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object" class="external-link" target="_blank">`Parameter Object` (in der Spezifikation)</a>, das verwendet wurde von FastAPIs: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object" class="external-link" target="_blank">`Request Body Object` im Feld `content` des `Media Type Object`s (in der Spezifikation)</a>, das verwendet wurde von FastAPIs: + * `Body()` + * `File()` + * `Form()` + +!!! info + Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`. + +### JSON Schemas Feld `examples` + +Aber dann fügte JSON Schema ein <a href="https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5" class="external-link" target="_blank">`examples`</a>-Feld zu einer neuen Version der Spezifikation hinzu. + +Und dann basierte das neue OpenAPI 3.1.0 auf der neuesten Version (JSON Schema 2020-12), die dieses neue Feld `examples` enthielt. + +Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdefinierten) `example`-Feld, im Singular, das jetzt deprecated ist. + +Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben). + +!!! info + Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉). + + Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0. + +### Pydantic- und FastAPI-`examples` + +Wenn Sie `examples` innerhalb eines Pydantic-Modells hinzufügen, indem Sie `schema_extra` oder `Field(examples=["something"])` verwenden, wird dieses Beispiel dem **JSON-Schema** für dieses Pydantic-Modell hinzugefügt. + +Und dieses **JSON-Schema** des Pydantic-Modells ist in der **OpenAPI** Ihrer API enthalten und wird dann in der Benutzeroberfläche der Dokumentation verwendet. + +In Versionen von FastAPI vor 0.99.0 (0.99.0 und höher verwenden das neuere OpenAPI 3.1.0), wenn Sie `example` oder `examples` mit einem der anderen Werkzeuge (`Query()`, `Body()`, usw.) verwendet haben, wurden diese Beispiele nicht zum JSON-Schema hinzugefügt, das diese Daten beschreibt (nicht einmal zur OpenAPI-eigenen Version von JSON Schema), sondern direkt zur *Pfadoperation*-Deklaration in OpenAPI (außerhalb der Teile von OpenAPI, die JSON Schema verwenden). + +Aber jetzt, da FastAPI 0.99.0 und höher, OpenAPI 3.1.0 verwendet, das JSON Schema 2020-12 verwendet, und Swagger UI 5.0.0 und höher, ist alles konsistenter und die Beispiele sind in JSON Schema enthalten. + +### Swagger-Benutzeroberfläche und OpenAPI-spezifische `examples`. + +Da die Swagger-Benutzeroberfläche derzeit nicht mehrere JSON Schema Beispiele unterstützt (Stand: 26.08.2023), hatten Benutzer keine Möglichkeit, mehrere Beispiele in der Dokumentation anzuzeigen. + +Um dieses Problem zu lösen, hat FastAPI `0.103.0` **Unterstützung** für die Deklaration desselben alten **OpenAPI-spezifischen** `examples`-Felds mit dem neuen Parameter `openapi_examples` hinzugefügt. 🤓 + +### Zusammenfassung + +Ich habe immer gesagt, dass ich Geschichte nicht so sehr mag ... und jetzt schauen Sie mich an, wie ich „Technikgeschichte“-Unterricht gebe. 😅 + +Kurz gesagt: **Upgraden Sie auf FastAPI 0.99.0 oder höher**, und die Dinge sind viel **einfacher, konsistenter und intuitiver**, und Sie müssen nicht alle diese historischen Details kennen. 😎 From 247611337c3620aedac4cb185c6f386343ef71a0 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:20:01 +0100 Subject: [PATCH 219/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/testing.md`=20(#10586)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/testing.md | 212 +++++++++++++++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 docs/de/docs/tutorial/testing.md diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md new file mode 100644 index 000000000..541cc1bf0 --- /dev/null +++ b/docs/de/docs/tutorial/testing.md @@ -0,0 +1,212 @@ +# Testen + +Dank <a href="https://www.starlette.io/testclient/" class="external-link" target="_blank">Starlette</a> ist das Testen von **FastAPI**-Anwendungen einfach und macht Spaß. + +Es basiert auf <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a>, welches wiederum auf der Grundlage von requests konzipiert wurde, es ist also sehr vertraut und intuitiv. + +Damit können Sie <a href="https://docs.pytest.org/" class="external-link" target="_blank">pytest</a> direkt mit **FastAPI** verwenden. + +## Verwendung von `TestClient` + +!!! info + Um `TestClient` zu verwenden, installieren Sie zunächst <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. + + Z. B. `pip install httpx`. + +Importieren Sie `TestClient`. + +Erstellen Sie einen `TestClient`, indem Sie ihm Ihre **FastAPI**-Anwendung übergeben. + +Erstellen Sie Funktionen mit einem Namen, der mit `test_` beginnt (das sind `pytest`-Konventionen). + +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!} +``` + +!!! tip "Tipp" + Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. + + Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden. + + Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. + +!!! note "Technische Details" + Sie könnten auch `from starlette.testclient import TestClient` verwenden. + + **FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +!!! tip "Tipp" + Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. + +## Tests separieren + +In einer echten Anwendung würden Sie Ihre Tests wahrscheinlich in einer anderen Datei haben. + +Und Ihre **FastAPI**-Anwendung könnte auch aus mehreren Dateien/Modulen, usw. bestehen. + +### **FastAPI** Anwendungsdatei + +Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigger-applications.md){.internal-link target=_blank} beschrieben: + +``` +. +├── app +│ ├── __init__.py +│ └── main.py +``` + +In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: + + +```Python +{!../../../docs_src/app_testing/main.py!} +``` + +### Testdatei + +Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte sich im selben Python-Package befinden (dasselbe Verzeichnis mit einer `__init__.py`-Datei): + +``` hl_lines="5" +. +├── app +│ ├── __init__.py +│ ├── main.py +│ └── test_main.py +``` + +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!} +``` + +... und haben den Code für die Tests wie zuvor. + +## Testen: erweitertes Beispiel + +Nun erweitern wir dieses Beispiel und fügen weitere Details hinzu, um zu sehen, wie verschiedene Teile getestet werden. + +### Erweiterte **FastAPI**-Anwendungsdatei + +Fahren wir mit der gleichen Dateistruktur wie zuvor fort: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +│ └── test_main.py +``` + +Nehmen wir an, dass die Datei `main.py` mit Ihrer **FastAPI**-Anwendung jetzt einige andere **Pfadoperationen** hat. + +Sie verfügt über eine `GET`-Operation, die einen Fehler zurückgeben könnte. + +Sie verfügt über eine `POST`-Operation, die mehrere Fehler zurückgeben könnte. + +Beide *Pfadoperationen* erfordern einen `X-Token`-Header. + +=== "Python 3.10+" + + ```Python + {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} + ``` + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/app_testing/app_b_an/main.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + {!> ../../../docs_src/app_testing/app_b_py310/main.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python + {!> ../../../docs_src/app_testing/app_b/main.py!} + ``` + +### Erweiterte Testdatei + +Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: + +```Python +{!> ../../../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. + +Dann machen Sie in Ihren Tests einfach das gleiche. + +Z. B.: + +* Um einen *Pfad*- oder *Query*-Parameter zu übergeben, fügen Sie ihn der URL selbst hinzu. +* Um einen JSON-Body zu übergeben, übergeben Sie ein Python-Objekt (z. B. ein `dict`) an den Parameter `json`. +* Wenn Sie *Formulardaten* anstelle von JSON senden müssen, verwenden Sie stattdessen den `data`-Parameter. +* Um *Header* zu übergeben, verwenden Sie ein `dict` im `headers`-Parameter. +* Für *Cookies* ein `dict` im `cookies`-Parameter. + +Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX-Dokumentation</a>. + +!!! info + Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle. + + Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird. + +## Tests ausführen + +Danach müssen Sie nur noch `pytest` installieren: + +<div class="termy"> + +```console +$ pip install pytest + +---> 100% +``` + +</div> + +Es erkennt die Dateien und Tests automatisch, führt sie aus und berichtet Ihnen die Ergebnisse. + +Führen Sie die Tests aus, mit: + +<div class="termy"> + +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py <span style="color: green; white-space: pre;">...... [100%]</span> + +<span style="color: green;">================= 1 passed in 0.03s =================</span> +``` + +</div> From df50cd081e56885d2e00d837794d9384def64ae6 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:25:38 +0100 Subject: [PATCH 220/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/metadata.md`=20(#10581)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/metadata.md | 123 ++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 docs/de/docs/tutorial/metadata.md diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md new file mode 100644 index 000000000..2061e2a5b --- /dev/null +++ b/docs/de/docs/tutorial/metadata.md @@ -0,0 +1,123 @@ +# Metadaten und URLs der Dokumentationen + +Sie können mehrere Metadaten-Einstellungen für Ihre **FastAPI**-Anwendung konfigurieren. + +## Metadaten für die API + +Sie können die folgenden Felder festlegen, welche in der OpenAPI-Spezifikation und den Benutzeroberflächen der automatischen API-Dokumentation verwendet werden: + +| Parameter | Typ | Beschreibung | +|------------|------|-------------| +| `title` | `str` | Der Titel der API. | +| `summary` | `str` | Eine kurze Zusammenfassung der API. <small>Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0.</small> | +| `description` | `str` | Eine kurze Beschreibung der API. Kann Markdown verwenden. | +| `version` | `string` | Die Version der API. Das ist die Version Ihrer eigenen Anwendung, nicht die von OpenAPI. Zum Beispiel `2.5.0`. | +| `terms_of_service` | `str` | Eine URL zu den Nutzungsbedingungen für die API. Falls angegeben, muss es sich um eine URL handeln. | +| `contact` | `dict` | Die Kontaktinformationen für die verfügbar gemachte API. Kann mehrere Felder enthalten. <details><summary><code>contact</code>-Felder</summary><table><thead><tr><th>Parameter</th><th>Typ</th><th>Beschreibung</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>Der identifizierende Name der Kontaktperson/Organisation.</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>Die URL, die auf die Kontaktinformationen verweist. MUSS im Format einer URL vorliegen.</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>Die E-Mail-Adresse der Kontaktperson/Organisation. MUSS im Format einer E-Mail-Adresse vorliegen.</td></tr></tbody></table></details> | +| `license_info` | `dict` | Die Lizenzinformationen für die verfügbar gemachte API. Kann mehrere Felder enthalten. <details><summary><code>license_info</code>-Felder</summary><table><thead><tr><th>Parameter</th><th>Typ</th><th>Beschreibung</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>ERFORDERLICH</strong> (wenn eine <code>license_info</code> festgelegt ist). Der für die API verwendete Lizenzname.</td></tr><tr><td><code>identifier</code></td><td><code>str</code></td><td>Ein <a href="https://spdx.org/licenses/" class="external-link" target="_blank">SPDX</a>-Lizenzausdruck für die API. Das Feld <code>identifier</code> und das Feld <code>url</code> schließen sich gegenseitig aus. <small>Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0.</small></td></tr><tr><td><code>url</code></td><td><code >str</code></td><td>Eine URL zur Lizenz, die für die API verwendet wird. MUSS im Format einer URL vorliegen.</td></tr></tbody></table></details> | + +Sie können diese wie folgt setzen: + +```Python hl_lines="3-16 19-32" +{!../../../docs_src/metadata/tutorial001.py!} +``` + +!!! tip "Tipp" + Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert. + +Mit dieser Konfiguration würde die automatische API-Dokumentation wie folgt aussehen: + +<img src="/img/tutorial/metadata/image01.png"> + +## Lizenz-ID + +Seit OpenAPI 3.1.0 und FastAPI 0.99.0 können Sie die `license_info` auch mit einem `identifier` anstelle einer `url` festlegen. + +Zum Beispiel: + +```Python hl_lines="31" +{!../../../docs_src/metadata/tutorial001_1.py!} +``` + +## Metadaten für Tags + +Sie können mit dem Parameter `openapi_tags` auch zusätzliche Metadaten für die verschiedenen Tags hinzufügen, die zum Gruppieren Ihrer Pfadoperationen verwendet werden. + +Es wird eine Liste benötigt, die für jedes Tag ein Dict enthält. + +Jedes Dict kann Folgendes enthalten: + +* `name` (**erforderlich**): ein `str` mit demselben Tag-Namen, den Sie im Parameter `tags` in Ihren *Pfadoperationen* und `APIRouter`n verwenden. +* `description`: ein `str` mit einer kurzen Beschreibung für das Tag. Sie kann Markdown enthalten und wird in der Benutzeroberfläche der Dokumentation angezeigt. +* `externalDocs`: ein `dict`, das externe Dokumentation beschreibt mit: + * `description`: ein `str` mit einer kurzen Beschreibung für die externe Dokumentation. + * `url` (**erforderlich**): ein `str` mit der URL für die externe Dokumentation. + +### Metadaten für Tags erstellen + +Versuchen wir das an einem Beispiel mit Tags für `users` und `items`. + +Erstellen Sie Metadaten für Ihre Tags und übergeben Sie sie an den Parameter `openapi_tags`: + +```Python hl_lines="3-16 18" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +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" + Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. + +### Ihre Tags verwenden + +Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n), um diese verschiedenen Tags zuzuweisen: + +```Python hl_lines="21 26" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +!!! info + Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags){.internal-link target=_blank}. + +### Die Dokumentation anschauen + +Wenn Sie nun die Dokumentation ansehen, werden dort alle zusätzlichen Metadaten angezeigt: + +<img src="/img/tutorial/metadata/image02.png"> + +### Reihenfolge der Tags + +Die Reihenfolge der Tag-Metadaten-Dicts definiert auch die Reihenfolge, in der diese in der Benutzeroberfläche der Dokumentation angezeigt werden. + +Auch wenn beispielsweise `users` im Alphabet nach `items` kommt, wird es vor diesen angezeigt, da wir seine Metadaten als erstes Dict der Liste hinzugefügt haben. + +## OpenAPI-URL + +Standardmäßig wird das OpenAPI-Schema unter `/openapi.json` bereitgestellt. + +Sie können das aber mit dem Parameter `openapi_url` konfigurieren. + +Um beispielsweise festzulegen, dass es unter `/api/v1/openapi.json` bereitgestellt wird: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial002.py!} +``` + +Wenn Sie das OpenAPI-Schema vollständig deaktivieren möchten, können Sie `openapi_url=None` festlegen, wodurch auch die Dokumentationsbenutzeroberflächen deaktiviert werden, die es verwenden. + +## URLs der Dokumentationen + +Sie können die beiden enthaltenen Dokumentationsbenutzeroberflächen konfigurieren: + +* **Swagger UI**: bereitgestellt unter `/docs`. + * Sie können deren URL mit dem Parameter `docs_url` festlegen. + * Sie können sie deaktivieren, indem Sie `docs_url=None` festlegen. +* **ReDoc**: bereitgestellt unter `/redoc`. + * Sie können deren URL mit dem Parameter `redoc_url` festlegen. + * Sie können sie deaktivieren, indem Sie `redoc_url=None` festlegen. + +Um beispielsweise Swagger UI so einzustellen, dass sie unter `/documentation` bereitgestellt wird, und ReDoc zu deaktivieren: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial003.py!} +``` From 459ace50bca3aa543e2a5c638f9d3cdff9f8bf9c Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:25:57 +0100 Subject: [PATCH 221/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/async-tests.md`=20(#10708)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/async-tests.md | 95 ++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 docs/de/docs/advanced/async-tests.md diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md new file mode 100644 index 000000000..2e2c22210 --- /dev/null +++ b/docs/de/docs/advanced/async-tests.md @@ -0,0 +1,95 @@ +# Asynchrone Tests + +Sie haben bereits gesehen, wie Sie Ihre **FastAPI**-Anwendungen mit dem bereitgestellten `TestClient` testen. Bisher haben Sie nur gesehen, wie man synchrone Tests schreibt, ohne `async`hrone Funktionen zu verwenden. + +Die Möglichkeit, in Ihren Tests asynchrone Funktionen zu verwenden, könnte beispielsweise nützlich sein, wenn Sie Ihre Datenbank asynchron abfragen. Stellen Sie sich vor, Sie möchten das Senden von Requests an Ihre FastAPI-Anwendung testen und dann überprüfen, ob Ihr Backend die richtigen Daten erfolgreich in die Datenbank geschrieben hat, während Sie eine asynchrone Datenbankbibliothek verwenden. + +Schauen wir uns an, wie wir das machen können. + +## pytest.mark.anyio + +Wenn wir in unseren Tests asynchrone Funktionen aufrufen möchten, müssen unsere Testfunktionen asynchron sein. AnyIO stellt hierfür ein nettes Plugin zur Verfügung, mit dem wir festlegen können, dass einige Testfunktionen asynchron aufgerufen werden sollen. + +## HTTPX + +Auch wenn Ihre **FastAPI**-Anwendung normale `def`-Funktionen anstelle von `async def` verwendet, handelt es sich darunter immer noch um eine `async`hrone Anwendung. + +Der `TestClient` macht unter der Haube magisches, um die asynchrone FastAPI-Anwendung in Ihren normalen `def`-Testfunktionen, mithilfe von Standard-Pytest aufzurufen. Aber diese Magie funktioniert nicht mehr, wenn wir sie in asynchronen Funktionen verwenden. Durch die asynchrone Ausführung unserer Tests können wir den `TestClient` nicht mehr in unseren Testfunktionen verwenden. + +Der `TestClient` basiert auf <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> und glücklicherweise können wir ihn direkt verwenden, um die API zu testen. + +## Beispiel + +Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größere Anwendungen](../tutorial/bigger-applications.md){.internal-link target=_blank} und [Testen](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +│ └── test_main.py +``` + +Die Datei `main.py` hätte als Inhalt: + +```Python +{!../../../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!} +``` + +## Es ausführen + +Sie können Ihre Tests wie gewohnt ausführen mit: + +<div class="termy"> + +```console +$ pytest + +---> 100% +``` + +</div> + +## Details + +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!} +``` + +!!! tip "Tipp" + Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. + +Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. + +```Python hl_lines="9-10" +{!../../../docs_src/async_tests/test_main.py!} +``` + +Das ist das Äquivalent zu: + +```Python +response = client.get('/') +``` + +... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. + +!!! tip "Tipp" + Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. + +!!! 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 <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. + +## Andere asynchrone Funktionsaufrufe + +Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. + +!!! tip "Tipp" + Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDBs MotorClient</a>), 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. From dccf41c51e7b80ffca7c11887a777dbc1254c09d Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:26:08 +0100 Subject: [PATCH 222/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/security/oauth2-scopes.md`=20?= =?UTF-8?q?(#10643)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/oauth2-scopes.md | 598 ++++++++++++++++++ 1 file changed, 598 insertions(+) create mode 100644 docs/de/docs/advanced/security/oauth2-scopes.md diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..ffd34d65f --- /dev/null +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,598 @@ +# OAuth2-Scopes + +Sie können OAuth2-<abbr title="Geltungsbereiche">Scopes</abbr> direkt in **FastAPI** verwenden, sie sind nahtlos integriert. + +Das ermöglicht es Ihnen, ein feingranuliertes Berechtigungssystem nach dem OAuth2-Standard in Ihre OpenAPI-Anwendung (und deren API-Dokumentation) zu integrieren. + +OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter usw. verwendet wird. Sie verwenden ihn, um Benutzern und Anwendungen spezifische Berechtigungen zu erteilen. + +Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter anmelden („log in with“), verwendet die entsprechende Anwendung OAuth2 mit Scopes. + +In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten. + +!!! warning "Achtung" + Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. + + Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. + + Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. + + Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. + + In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. + + Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. + +## OAuth2-Scopes und OpenAPI + +Die OAuth2-Spezifikation definiert „Scopes“ als eine Liste von durch Leerzeichen getrennten Strings. + +Der Inhalt jedes dieser Strings kann ein beliebiges Format haben, sollte jedoch keine Leerzeichen enthalten. + +Diese Scopes stellen „Berechtigungen“ dar. + +In OpenAPI (z. B. der API-Dokumentation) können Sie „Sicherheitsschemas“ definieren. + +Wenn eines dieser Sicherheitsschemas OAuth2 verwendet, können Sie auch Scopes deklarieren und verwenden. + +Jeder „Scope“ ist nur ein String (ohne Leerzeichen). + +Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel: + +* `users:read` oder `users:write` sind gängige Beispiele. +* `instagram_basic` wird von Facebook / Instagram verwendet. +* `https://www.googleapis.com/auth/drive` wird von Google verwendet. + +!!! info + In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + + Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. + + Diese Details sind implementierungsspezifisch. + + Für OAuth2 sind es einfach nur Strings. + +## Gesamtübersicht + +Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes: + +=== "Python 3.10+" + + ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 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!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Sehen wir uns diese Änderungen nun Schritt für Schritt an. + +## OAuth2-Sicherheitsschema + +Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei verfügbaren Scopes deklarieren: `me` und `items`. + +Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: + +=== "Python 3.10+" + + ```Python hl_lines="62-65" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="62-65" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="63-66" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "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!} + ``` + + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="62-65" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. + +Und Sie können auswählen, auf welche Scopes Sie Zugriff haben möchten: `me` und `items`. + +Das ist derselbe Mechanismus, der verwendet wird, wenn Sie beim Anmelden mit Facebook, Google, GitHub, usw. Berechtigungen erteilen: + +<img src="/img/tutorial/security/image11.png"> + +## JWT-Token mit Scopes + +Ändern Sie nun die Token-*Pfadoperation*, um die angeforderten Scopes zurückzugeben. + +Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Eigenschaft `scopes` mit einer `list`e von `str`s für jeden Scope, den es im Request erhalten hat. + +Und wir geben die Scopes als Teil des JWT-Tokens zurück. + +!!! danger "Gefahr" + Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. + + Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. + +=== "Python 3.10+" + + ```Python hl_lines="155" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="155" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="156" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="155" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren + +Jetzt deklarieren wir, dass die *Pfadoperation* für `/users/me/items/` den Scope `items` erfordert. + +Dazu importieren und verwenden wir `Security` von `fastapi`. + +Sie können `Security` verwenden, um Abhängigkeiten zu deklarieren (genau wie `Depends`), aber `Security` erhält auch einen Parameter `scopes` mit einer Liste von Scopes (Strings). + +In diesem Fall übergeben wir eine Abhängigkeitsfunktion `get_current_active_user` an `Security` (genauso wie wir es mit `Depends` tun würden). + +Wir übergeben aber auch eine `list`e von Scopes, in diesem Fall mit nur einem Scope: `items` (es könnten mehrere sein). + +Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängigkeiten deklarieren, nicht nur mit `Depends`, sondern auch mit `Security`. Ihre eigene Unterabhängigkeitsfunktion (`get_current_user`) und weitere Scope-Anforderungen deklarierend. + +In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). + +!!! note "Hinweis" + Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. + + Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. + +=== "Python 3.10+" + + ```Python hl_lines="4 139 170" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 139 170" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 140 171" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! 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. + + Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. + + Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. + +## `SecurityScopes` verwenden + +Aktualisieren Sie nun die Abhängigkeit `get_current_user`. + +Das ist diejenige, die von den oben genannten Abhängigkeiten verwendet wird. + +Hier verwenden wir dasselbe OAuth2-Schema, das wir zuvor erstellt haben, und deklarieren es als Abhängigkeit: `oauth2_scheme`. + +Da diese Abhängigkeitsfunktion selbst keine Scope-Anforderungen hat, können wir `Depends` mit `oauth2_scheme` verwenden. Wir müssen `Security` nicht verwenden, wenn wir keine Sicherheits-Scopes angeben müssen. + +Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der aus `fastapi.security` importiert wird. + +Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). + +=== "Python 3.10+" + + ```Python hl_lines="8 105" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8 105" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 106" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Die `scopes` verwenden + +Der Parameter `security_scopes` wird vom Typ `SecurityScopes` sein. + +Dieses verfügt über ein Attribut `scopes` mit einer Liste, die alle von ihm selbst benötigten Scopes enthält und ferner alle Abhängigkeiten, die dieses als Unterabhängigkeit verwenden. Sprich, alle „Dependanten“ ... das mag verwirrend klingen, wird aber später noch einmal erklärt. + +Das `security_scopes`-Objekt (der Klasse `SecurityScopes`) stellt außerdem ein `scope_str`-Attribut mit einem einzelnen String bereit, der die durch Leerzeichen getrennten Scopes enthält (den werden wir verwenden). + +Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederverwenden (`raise`n) können. + +In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). + +=== "Python 3.10+" + + ```Python hl_lines="105 107-115" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="105 107-115" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="106 108-116" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="105 107-115" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Den `username` und das Format der Daten überprüfen + +Wir verifizieren, dass wir einen `username` erhalten, und extrahieren die Scopes. + +Und dann validieren wir diese Daten mit dem Pydantic-Modell (wobei wir die `ValidationError`-Exception abfangen), und wenn wir beim Lesen des JWT-Tokens oder beim Validieren der Daten mit Pydantic einen Fehler erhalten, lösen wir die zuvor erstellte `HTTPException` aus. + +Dazu aktualisieren wir das Pydantic-Modell `TokenData` mit einem neuen Attribut `scopes`. + +Durch die Validierung der Daten mit Pydantic können wir sicherstellen, dass wir beispielsweise präzise eine `list`e von `str`s mit den Scopes und einen `str` mit dem `username` haben. + +Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anwendung zu Fehlern führen könnte und darum ein Sicherheitsrisiko darstellt. + +Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. + +=== "Python 3.10+" + + ```Python hl_lines="46 116-127" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="46 116-127" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="47 117-128" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="46 116-127" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Die `scopes` verifizieren + +Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von dieser Abhängigkeit und deren Verwendern (einschließlich *Pfadoperationen*) gefordert werden. Andernfalls lösen wir eine `HTTPException` aus. + +Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. + +=== "Python 3.10+" + + ```Python hl_lines="128-134" + {!> ../../../docs_src/security/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="128-134" + {!> ../../../docs_src/security/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="129-135" + {!> ../../../docs_src/security/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="128-134" + {!> ../../../docs_src/security/tutorial005.py!} + ``` + +## Abhängigkeitsbaum und Scopes + +Sehen wir uns diesen Abhängigkeitsbaum und die Scopes noch einmal an. + +Da die Abhängigkeit `get_current_active_user` von `get_current_user` abhängt, wird der bei `get_current_active_user` deklarierte Scope `"me"` in die Liste der erforderlichen Scopes in `security_scopes.scopes` aufgenommen, das an `get_current_user` übergeben wird. + +Die *Pfadoperation* selbst deklariert auch einen Scope, `"items"`, sodass dieser auch in der Liste der `security_scopes.scopes` enthalten ist, die an `get_current_user` übergeben wird. + +So sieht die Hierarchie der Abhängigkeiten und Scopes aus: + +* Die *Pfadoperation* `read_own_items` hat: + * Erforderliche Scopes `["items"]` mit der Abhängigkeit: + * `get_current_active_user`: + * Die Abhängigkeitsfunktion `get_current_active_user` hat: + * Erforderliche Scopes `["me"]` mit der Abhängigkeit: + * `get_current_user`: + * Die Abhängigkeitsfunktion `get_current_user` hat: + * Selbst keine erforderlichen Scopes. + * Eine Abhängigkeit, die `oauth2_scheme` verwendet. + * Einen `security_scopes`-Parameter vom Typ `SecurityScopes`: + * Dieser `security_scopes`-Parameter hat ein Attribut `scopes` mit einer `list`e, die alle oben deklarierten Scopes enthält, sprich: + * `security_scopes.scopes` enthält `["me", "items"]` für die *Pfadoperation* `read_own_items`. + * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. + * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. + +!!! tip "Tipp" + Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. + + Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. + +## Weitere Details zu `SecurityScopes`. + +Sie können `SecurityScopes` an jeder Stelle und an mehreren Stellen verwenden, es muss sich nicht in der „Wurzel“-Abhängigkeit befinden. + +Es wird immer die Sicherheits-Scopes enthalten, die in den aktuellen `Security`-Abhängigkeiten deklariert sind und in allen Abhängigkeiten für **diese spezifische** *Pfadoperation* und **diesen spezifischen** Abhängigkeitsbaum. + +Da die `SecurityScopes` alle von den Verwendern der Abhängigkeiten deklarierten Scopes enthalten, können Sie damit überprüfen, ob ein Token in einer zentralen Abhängigkeitsfunktion über die erforderlichen Scopes verfügt, und dann unterschiedliche Scope-Anforderungen in unterschiedlichen *Pfadoperationen* deklarieren. + +Diese werden für jede *Pfadoperation* unabhängig überprüft. + +## Testen Sie es + +Wenn Sie die API-Dokumentation öffnen, können Sie sich authentisieren und angeben, welche Scopes Sie autorisieren möchten. + +<img src="/img/tutorial/security/image11.png"> + +Wenn Sie keinen Scope auswählen, werden Sie „authentifiziert“, aber wenn Sie versuchen, auf `/users/me/` oder `/users/me/items/` zuzugreifen, wird eine Fehlermeldung angezeigt, die sagt, dass Sie nicht über genügend Berechtigungen verfügen. Sie können aber auf `/status/` zugreifen. + +Und wenn Sie den Scope `me`, aber nicht den Scope `items` auswählen, können Sie auf `/users/me/` zugreifen, aber nicht auf `/users/me/items/`. + +Das würde einer Drittanbieteranwendung passieren, die versucht, auf eine dieser *Pfadoperationen* mit einem Token zuzugreifen, das von einem Benutzer bereitgestellt wurde, abhängig davon, wie viele Berechtigungen der Benutzer dieser Anwendung erteilt hat. + +## Über Integrationen von Drittanbietern + +In diesem Beispiel verwenden wir den OAuth2-Flow „Password“. + +Das ist angemessen, wenn wir uns bei unserer eigenen Anwendung anmelden, wahrscheinlich mit unserem eigenen Frontend. + +Weil wir darauf vertrauen können, dass es den `username` und das `password` erhält, welche wir kontrollieren. + +Wenn Sie jedoch eine OAuth2-Anwendung erstellen, mit der andere eine Verbindung herstellen würden (d.h. wenn Sie einen Authentifizierungsanbieter erstellen, der Facebook, Google, GitHub usw. entspricht), sollten Sie einen der anderen Flows verwenden. + +Am häufigsten ist der „Implicit“-Flow. + +Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. + +!!! note "Hinweis" + Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. + + Aber am Ende implementieren sie denselben OAuth2-Standard. + +**FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`. + +## `Security` in Dekorator-`dependencies` + +Auf die gleiche Weise können Sie eine `list`e von `Depends` im Parameter `dependencies` des Dekorators definieren (wie in [Abhängigkeiten in Pfadoperation-Dekoratoren](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} erläutert), Sie könnten auch dort `Security` mit `scopes` verwenden. From ccc738cd0f238de3c9bf5b5bc9efe94de7391866 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:26:19 +0100 Subject: [PATCH 223/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/templates.md`=20(#10678)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/templates.md | 119 +++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 docs/de/docs/advanced/templates.md diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md new file mode 100644 index 000000000..17d821e61 --- /dev/null +++ b/docs/de/docs/advanced/templates.md @@ -0,0 +1,119 @@ +# Templates + +Sie können jede gewünschte Template-Engine mit **FastAPI** verwenden. + +Eine häufige Wahl ist Jinja2, dasselbe, was auch von Flask und anderen Tools verwendet wird. + +Es gibt Werkzeuge zur einfachen Konfiguration, die Sie direkt in Ihrer **FastAPI**-Anwendung verwenden können (bereitgestellt von Starlette). + +## Abhängigkeiten installieren + +Installieren Sie `jinja2`: + +<div class="termy"> + +```console +$ pip install jinja2 + +---> 100% +``` + +</div> + +## Verwendung von `Jinja2Templates` + +* Importieren Sie `Jinja2Templates`. +* Erstellen Sie ein `templates`-Objekt, das Sie später wiederverwenden können. +* 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!} +``` + +!!! note "Hinweis" + Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. + + Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. + +!!! tip "Tipp" + Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. + +!!! note "Technische Details" + Sie können auch `from starlette.templating import Jinja2Templates` verwenden. + + **FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. + +## Templates erstellen + +Dann können Sie unter `templates/item.html` ein Template erstellen, mit z. B. folgendem Inhalt: + +```jinja hl_lines="7" +{!../../../docs_src/templates/templates/item.html!} +``` + +### Template-Kontextwerte + +Im HTML, welches enthält: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +... wird die `id` angezeigt, welche dem „Kontext“-`dict` entnommen wird, welches Sie übergeben haben: + +```Python +{"id": id} +``` + +Mit beispielsweise einer ID `42` würde das wie folgt gerendert werden: + +```html +Item ID: 42 +``` + +### Template-`url_for`-Argumente + +Sie können `url_for()` auch innerhalb des Templates verwenden, es nimmt als Argumente dieselben Argumente, die von Ihrer *Pfadoperation-Funktion* verwendet werden. + +Der Abschnitt mit: + +{% raw %} + +```jinja +<a href="{{ url_for('read_item', id=id) }}"> +``` + +{% endraw %} + +... generiert also einen Link zu derselben URL, welche von der *Pfadoperation-Funktion* `read_item(id=id)` gehandhabt werden würde. + +Mit beispielsweise der ID `42` würde dies Folgendes ergeben: + +```html +<a href="/items/42"> +``` + +## Templates und statische Dateien + +Sie können `url_for()` innerhalb des Templates auch beispielsweise mit den `StaticFiles` verwenden, die Sie mit `name="static"` gemountet haben. + +```jinja hl_lines="4" +{!../../../docs_src/templates/templates/item.html!} +``` + +In diesem Beispiel würde das zu einer CSS-Datei unter `static/styles.css` verlinken, mit folgendem Inhalt: + +```CSS hl_lines="4" +{!../../../docs_src/templates/static/styles.css!} +``` + +Und da Sie `StaticFiles` verwenden, wird diese CSS-Datei automatisch von Ihrer **FastAPI**-Anwendung unter der URL `/static/styles.css` bereitgestellt. + +## Mehr Details + +Weitere Informationen, einschließlich, wie man Templates testet, finden Sie in der <a href="https://www.starlette.io/templates/" class="external-link" target="_blank">Starlette Dokumentation zu Templates</a>. From b9b6963f154348bfed7bbf063ea5a0b4cf777001 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:26:28 +0100 Subject: [PATCH 224/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/alternatives.md`=20(#10855)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/alternatives.md | 414 +++++++++++++++++++++++++++++++++++ 1 file changed, 414 insertions(+) create mode 100644 docs/de/docs/alternatives.md diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md new file mode 100644 index 000000000..ea624ff3a --- /dev/null +++ b/docs/de/docs/alternatives.md @@ -0,0 +1,414 @@ +# Alternativen, Inspiration und Vergleiche + +Was hat **FastAPI** inspiriert, ein Vergleich zu Alternativen, und was FastAPI von diesen gelernt hat. + +## Einführung + +**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren. + +Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten. + +Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen. + +Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise). + +## Vorherige Tools + +### <a href="https://www.djangoproject.com/" class="external-link" target="_blank">Django</a> + +Es ist das beliebteste Python-Framework und genießt großes Vertrauen. Es wird zum Aufbau von Systemen wie Instagram verwendet. + +Ist relativ eng mit relationalen Datenbanken (wie MySQL oder PostgreSQL) gekoppelt, daher ist es nicht sehr einfach, eine NoSQL-Datenbank (wie Couchbase, MongoDB, Cassandra, usw.) als Hauptspeicherengine zu verwenden. + +Es wurde erstellt, um den HTML-Code im Backend zu generieren, nicht um APIs zu erstellen, die von einem modernen Frontend (wie React, Vue.js und Angular) oder von anderen Systemen (wie <abbr title="Internet of Things">IoT</abbr>-Geräten) verwendet werden, um mit ihm zu kommunizieren. + +### <a href="https://www.django-rest-framework.org/" class="external-link" target="_blank">Django REST Framework</a> + +Das Django REST Framework wurde als flexibles Toolkit zum Erstellen von Web-APIs unter Verwendung von Django entwickelt, um dessen API-Möglichkeiten zu verbessern. + +Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbrite. + +Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. + +!!! note "Hinweis" + Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. + + +!!! check "Inspirierte **FastAPI**" + Eine automatische API-Dokumentationsoberfläche zu haben. + +### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> + +Flask ist ein „Mikroframework“, es enthält weder Datenbankintegration noch viele der Dinge, die standardmäßig in Django enthalten sind. + +Diese Einfachheit und Flexibilität ermöglichen beispielsweise die Verwendung von NoSQL-Datenbanken als Hauptdatenspeichersystem. + +Da es sehr einfach ist, ist es relativ intuitiv zu erlernen, obwohl die Dokumentation an einigen Stellen etwas technisch wird. + +Es wird auch häufig für andere Anwendungen verwendet, die nicht unbedingt eine Datenbank, Benutzerverwaltung oder eine der vielen in Django enthaltenen Funktionen benötigen. Obwohl viele dieser Funktionen mit Plugins hinzugefügt werden können. + +Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframework“ handelt, welches so erweitert werden kann, dass es genau das abdeckt, was benötigt wird, war ein Schlüsselmerkmal, das ich beibehalten wollte. + +Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. + +!!! check "Inspirierte **FastAPI**" + Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. + + Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. + + +### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> + +**FastAPI** ist eigentlich keine Alternative zu **Requests**. Der Umfang der beiden ist sehr unterschiedlich. + +Es wäre tatsächlich üblich, Requests *innerhalb* einer FastAPI-Anwendung zu verwenden. + +Dennoch erhielt FastAPI von Requests einiges an Inspiration. + +**Requests** ist eine Bibliothek zur *Interaktion* mit APIs (als Client), während **FastAPI** eine Bibliothek zum *Erstellen* von APIs (als Server) ist. + +Die beiden stehen mehr oder weniger an entgegengesetzten Enden und ergänzen sich. + +Requests hat ein sehr einfaches und intuitives Design, ist sehr einfach zu bedienen und verfügt über sinnvolle Standardeinstellungen. Aber gleichzeitig ist es sehr leistungsstark und anpassbar. + +Aus diesem Grund heißt es auf der offiziellen Website: + +> Requests ist eines der am häufigsten heruntergeladenen Python-Packages aller Zeiten + +Die Art und Weise, wie Sie es verwenden, ist sehr einfach. Um beispielsweise einen `GET`-Request zu machen, würden Sie schreiben: + +```Python +response = requests.get("http://example.com/some/url") +``` + +Die entsprechende *Pfadoperation* der FastAPI-API könnte wie folgt aussehen: + +```Python hl_lines="1" +@app.get("/some/url") +def read_url(): + return {"message": "Hello World"} +``` + +Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. + +!!! check "Inspirierte **FastAPI**" + * Über eine einfache und intuitive API zu verfügen. + * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. + * Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. + + +### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> + +Die Hauptfunktion, die ich vom Django REST Framework haben wollte, war die automatische API-Dokumentation. + +Dann fand ich heraus, dass es einen Standard namens Swagger gab, zur Dokumentation von APIs unter Verwendung von JSON (oder YAML, einer Erweiterung von JSON). + +Und es gab bereits eine Web-Oberfläche für Swagger-APIs. Die Möglichkeit, Swagger-Dokumentation für eine API zu generieren, würde die automatische Nutzung dieser Web-Oberfläche ermöglichen. + +Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umbenannt. + +Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. + +!!! check "Inspirierte **FastAPI**" + Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. + + Und Standard-basierte Tools für die Oberfläche zu integrieren: + + * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> + * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> + + Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). + +### Flask REST Frameworks + +Es gibt mehrere Flask REST Frameworks, aber nachdem ich die Zeit und Arbeit investiert habe, sie zu untersuchen, habe ich festgestellt, dass viele nicht mehr unterstützt werden oder abgebrochen wurden und dass mehrere fortbestehende Probleme sie unpassend machten. + +### <a href="https://marshmallow.readthedocs.io/en/stable/" class="external-link" target="_blank">Marshmallow</a> + +Eine der von API-Systemen benötigen Hauptfunktionen ist die Daten-„<abbr title="Auch „Marshalling“, „Konvertierung“ genannt">Serialisierung</abbr>“, welche Daten aus dem Code (Python) entnimmt und in etwas umwandelt, was durch das Netzwerk gesendet werden kann. Beispielsweise das Konvertieren eines Objekts, welches Daten aus einer Datenbank enthält, in ein JSON-Objekt. Konvertieren von `datetime`-Objekten in Strings, usw. + +Eine weitere wichtige Funktion, benötigt von APIs, ist die Datenvalidierung, welche sicherstellt, dass die Daten unter gegebenen Umständen gültig sind. Zum Beispiel, dass ein Feld ein `int` ist und kein zufälliger String. Das ist besonders nützlich für hereinkommende Daten. + +Ohne ein Datenvalidierungssystem müssten Sie alle Prüfungen manuell im Code durchführen. + +Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibliothek und ich habe sie schon oft genutzt. + +Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein <abbr title="die Definition, wie Daten geformt sein werden sollen">Schema</abbr> zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. + +!!! check "Inspirierte **FastAPI**" + Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. + +### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> + +Eine weitere wichtige Funktion, die von APIs benötigt wird, ist das <abbr title="Lesen und Konvertieren nach Python-Daten">Parsen</abbr> von Daten aus eingehenden Requests. + +Webargs wurde entwickelt, um dieses für mehrere Frameworks, einschließlich Flask, bereitzustellen. + +Es verwendet unter der Haube Marshmallow, um die Datenvalidierung durchzuführen. Und es wurde von denselben Entwicklern erstellt. + +Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte. + +!!! info + Webargs wurde von denselben Marshmallow-Entwicklern erstellt. + +!!! check "Inspirierte **FastAPI**" + Eingehende Requestdaten automatisch zu validieren. + +### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> + +Marshmallow und Webargs bieten Validierung, Parsen und Serialisierung als Plugins. + +Es fehlt jedoch noch die Dokumentation. Dann wurde APISpec erstellt. + +Es ist ein Plugin für viele Frameworks (und es gibt auch ein Plugin für Starlette). + +Die Funktionsweise besteht darin, dass Sie die Definition des Schemas im YAML-Format im Docstring jeder Funktion schreiben, die eine Route verarbeitet. + +Und es generiert OpenAPI-Schemas. + +So funktioniert es in Flask, Starlette, Responder, usw. + +Aber dann haben wir wieder das Problem einer Mikrosyntax innerhalb eines Python-Strings (eines großen YAML). + +Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet. + +!!! info + APISpec wurde von denselben Marshmallow-Entwicklern erstellt. + + +!!! check "Inspirierte **FastAPI**" + Den offenen Standard für APIs, OpenAPI, zu unterstützen. + +### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> + +Hierbei handelt es sich um ein Flask-Plugin, welches Webargs, Marshmallow und APISpec miteinander verbindet. + +Es nutzt die Informationen von Webargs und Marshmallow, um mithilfe von APISpec automatisch OpenAPI-Schemas zu generieren. + +Ein großartiges Tool, sehr unterbewertet. Es sollte weitaus populärer als viele andere Flask-Plugins sein. Möglicherweise liegt es daran, dass die Dokumentation zu kompakt und abstrakt ist. + +Das löste das Problem, YAML (eine andere Syntax) in Python-Docstrings schreiben zu müssen. + +Diese Kombination aus Flask, Flask-apispec mit Marshmallow und Webargs war bis zur Entwicklung von **FastAPI** mein Lieblings-Backend-Stack. + +Die Verwendung führte zur Entwicklung mehrerer Flask-Full-Stack-Generatoren. Dies sind die Hauptstacks, die ich (und mehrere externe Teams) bisher verwendet haben: + +* <a href="https://github.com/tiangolo/full-stack" class="external-link" target="_blank">https://github.com/tiangolo/full-stack</a> +* <a href="https://github.com/tiangolo/full-stack-flask-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-flask-couchbase</a> +* <a href="https://github.com/tiangolo/full-stack-flask-couchdb" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-flask-couchdb</a> + +Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md){.internal-link target=_blank}. + +!!! info + Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. + +!!! check "Inspirierte **FastAPI**" + Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. + +### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (und <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) + +Dies ist nicht einmal Python, NestJS ist ein von Angular inspiriertes JavaScript (TypeScript) NodeJS Framework. + +Es erreicht etwas Ähnliches wie Flask-apispec. + +Es verfügt über ein integriertes Dependency Injection System, welches von Angular 2 inspiriert ist. Erfordert ein Vorab-Registrieren der „Injectables“ (wie alle anderen Dependency Injection Systeme, welche ich kenne), sodass der Code ausschweifender wird und es mehr Codeverdoppelung gibt. + +Da die Parameter mit TypeScript-Typen beschrieben werden (ähnlich den Python-Typhinweisen), ist die Editorunterstützung ziemlich gut. + +Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten bleiben, können die Typen nicht gleichzeitig die Validierung, Serialisierung und Dokumentation definieren. Aus diesem Grund und aufgrund einiger Designentscheidungen ist es für die Validierung, Serialisierung und automatische Schemagenerierung erforderlich, an vielen Stellen Dekoratoren hinzuzufügen. Es wird also ziemlich ausführlich. + +Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. + +!!! check "Inspirierte **FastAPI**" + Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. + + Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. + +### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> + +Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. + +!!! note "Technische Details" + Es verwendete <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. + + Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. + +!!! check "Inspirierte **FastAPI**" + Einen Weg zu finden, eine hervorragende Performanz zu haben. + + Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). + +### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> + +Falcon ist ein weiteres leistungsstarkes Python-Framework. Es ist minimalistisch konzipiert und dient als Grundlage für andere Frameworks wie Hug. + +Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter empfangen, einen „Request“ und eine „Response“. Dann „lesen“ Sie Teile des Requests und „schreiben“ Teile der Response. Aufgrund dieses Designs ist es nicht möglich, Request-Parameter und -Bodys mit Standard-Python-Typhinweisen als Funktionsparameter zu deklarieren. + +Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. + +!!! check "Inspirierte **FastAPI**" + Wege zu finden, eine großartige Performanz zu erzielen. + + Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. + + Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. + +### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> + +Ich habe Molten in den ersten Phasen der Entwicklung von **FastAPI** entdeckt. Und es hat ganz ähnliche Ideen: + +* Basierend auf Python-Typhinweisen. +* Validierung und Dokumentation aus diesen Typen. +* Dependency Injection System. + +Es verwendet keine Datenvalidierungs-, Serialisierungs- und Dokumentationsbibliothek eines Dritten wie Pydantic, sondern verfügt über eine eigene. Daher wären diese Datentyp-Definitionen nicht so einfach wiederverwendbar. + +Es erfordert eine etwas ausführlichere Konfiguration. Und da es auf WSGI (anstelle von ASGI) basiert, ist es nicht darauf ausgelegt, die hohe Leistung von Tools wie Uvicorn, Starlette und Sanic zu nutzen. + +Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängigkeiten und die Abhängigkeiten werden basierend auf den deklarierten Typen aufgelöst. Daher ist es nicht möglich, mehr als eine „Komponente“ zu deklarieren, welche einen bestimmten Typ bereitstellt. + +Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. + +!!! check "Inspirierte **FastAPI**" + Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. + + Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). + +### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> + +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. + +Es verwendete benutzerdefinierte Typen in seinen Deklarationen anstelle von Standard-Python-Typen, es war aber dennoch ein großer Fortschritt. + +Außerdem war es eines der ersten Frameworks, welches ein benutzerdefiniertes Schema generierte, welches die gesamte API in JSON deklarierte. + +Es basierte nicht auf einem Standard wie OpenAPI und JSON Schema. Daher wäre es nicht einfach, es in andere Tools wie Swagger UI zu integrieren. Aber, nochmal, es war eine sehr innovative Idee. + +Es verfügt über eine interessante, ungewöhnliche Funktion: Mit demselben Framework ist es möglich, APIs und auch CLIs zu erstellen. + +Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz. + +!!! info + Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. + +!!! check "Ideen, die **FastAPI** inspiriert haben" + Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. + + Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. + + Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. + +### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (≦ 0.5) + +Kurz bevor ich mich entschied, **FastAPI** zu erstellen, fand ich den **APIStar**-Server. Er hatte fast alles, was ich suchte, und ein tolles Design. + +Er war eine der ersten Implementierungen eines Frameworks, die ich je gesehen hatte (vor NestJS und Molten), welches Python-Typhinweise zur Deklaration von Parametern und Requests verwendeten. Ich habe ihn mehr oder weniger zeitgleich mit Hug gefunden. Aber APIStar nutzte den OpenAPI-Standard. + +Er verfügte an mehreren Stellen über automatische Datenvalidierung, Datenserialisierung und OpenAPI-Schemagenerierung, basierend auf denselben Typhinweisen. + +Body-Schemadefinitionen verwendeten nicht die gleichen Python-Typhinweise wie Pydantic, er war Marshmallow etwas ähnlicher, sodass die Editorunterstützung nicht so gut war, aber dennoch war APIStar die beste verfügbare Option. + +Er hatte zu dieser Zeit die besten Leistungsbenchmarks (nur übertroffen von Starlette). + +Anfangs gab es keine Web-Oberfläche für die automatische API-Dokumentation, aber ich wusste, dass ich Swagger UI hinzufügen konnte. + +Er verfügte über ein Dependency Injection System. Es erforderte eine Vorab-Registrierung der Komponenten, wie auch bei anderen oben besprochenen Tools. Aber dennoch, es war ein tolles Feature. + +Ich konnte ihn nie in einem vollständigen Projekt verwenden, da er keine Sicherheitsintegration hatte, sodass ich nicht alle Funktionen, die ich hatte, durch die auf Flask-apispec basierenden Full-Stack-Generatoren ersetzen konnte. Ich hatte in meinem Projekte-Backlog den Eintrag, einen Pull Request zu erstellen, welcher diese Funktionalität hinzufügte. + +Doch dann verlagerte sich der Schwerpunkt des Projekts. + +Es handelte sich nicht länger um ein API-Webframework, da sich der Entwickler auf Starlette konzentrieren musste. + +Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework. + +!!! info + APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: + + * Django REST Framework + * Starlette (auf welchem **FastAPI** basiert) + * Uvicorn (verwendet von Starlette und **FastAPI**) + +!!! check "Inspirierte **FastAPI**" + Zu existieren. + + Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. + + Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. + + Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. + + Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. + +## Verwendet von **FastAPI** + +### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> + +Pydantic ist eine Bibliothek zum Definieren von Datenvalidierung, Serialisierung und Dokumentation (unter Verwendung von JSON Schema) basierend auf Python-Typhinweisen. + +Das macht es äußerst intuitiv. + +Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig. + +!!! check "**FastAPI** verwendet es, um" + Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. + + **FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. + +### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> + +Starlette ist ein leichtgewichtiges <abbr title="Der neue Standard für die Erstellung asynchroner Python-Webanwendungen">ASGI</abbr>-Framework/Toolkit, welches sich ideal für die Erstellung hochperformanter asynchroner Dienste eignet. + +Es ist sehr einfach und intuitiv. Es ist so konzipiert, dass es leicht erweiterbar ist und über modulare Komponenten verfügt. + +Es bietet: + +* Eine sehr beeindruckende Leistung. +* WebSocket-Unterstützung. +* Hintergrundtasks im selben Prozess. +* Events für das Hoch- und Herunterfahren. +* Testclient basierend auf HTTPX. +* CORS, GZip, statische Dateien, Streamende Responses. +* Session- und Cookie-Unterstützung. +* 100 % Testabdeckung. +* 100 % Typannotierte Codebasis. +* Wenige starke Abhängigkeiten. + +Starlette ist derzeit das schnellste getestete Python-Framework. Nur übertroffen von Uvicorn, welches kein Framework, sondern ein Server ist. + +Starlette bietet alle grundlegenden Funktionen eines Web-Microframeworks. + +Es bietet jedoch keine automatische Datenvalidierung, Serialisierung oder Dokumentation. + +Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw. + +!!! note "Technische Details" + ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. + + Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. + +!!! check "**FastAPI** verwendet es, um" + Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. + + Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. + + Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. + +### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> + +Uvicorn ist ein blitzschneller ASGI-Server, der auf uvloop und httptools basiert. + +Es handelt sich nicht um ein Webframework, sondern um einen Server. Beispielsweise werden keine Tools für das Routing von Pfaden bereitgestellt. Das ist etwas, was ein Framework wie Starlette (oder **FastAPI**) zusätzlich bieten würde. + +Es ist der empfohlene Server für Starlette und **FastAPI**. + +!!! check "**FastAPI** empfiehlt es als" + Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. + + Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. + + Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. + +## Benchmarks und Geschwindigkeit + +Um den Unterschied zwischen Uvicorn, Starlette und FastAPI zu verstehen, zu vergleichen und zu sehen, lesen Sie den Abschnitt über [Benchmarks](benchmarks.md){.internal-link target=_blank}. From 1da96eff26516ba6c459af2538531b538e4dfefc Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:26:37 +0100 Subject: [PATCH 225/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/body-updates.md`=20(#10396)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/body-updates.md | 165 ++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 docs/de/docs/tutorial/body-updates.md diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md new file mode 100644 index 000000000..2b3716d6f --- /dev/null +++ b/docs/de/docs/tutorial/body-updates.md @@ -0,0 +1,165 @@ +# Body – Aktualisierungen + +## Ersetzendes Aktualisieren mit `PUT` + +Um einen Artikel zu aktualisieren, können Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT" class="external-link" target="_blank">HTTP `PUT`</a> Operation verwenden. + +Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas zu konvertieren, das als JSON gespeichert werden kann (in z. B. einer NoSQL-Datenbank). Zum Beispiel, um ein `datetime` in einen `str` zu konvertieren. + +=== "Python 3.10+" + + ```Python hl_lines="28-33" + {!> ../../../docs_src/body_updates/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-35" + {!> ../../../docs_src/body_updates/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="30-35" + {!> ../../../docs_src/body_updates/tutorial001.py!} + ``` + +`PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. + +### Warnung bezüglich des Ersetzens + +Das bedeutet, dass, wenn Sie den Artikel `bar` aktualisieren wollen, mittels `PUT` und folgendem Body: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +das Eingabemodell nun den Defaultwert `"tax": 10.5` hat, weil Sie das bereits gespeicherte Attribut `"tax": 20.2` nicht mit übergeben haben. + +Die Daten werden darum mit einem „neuen“ `tax`-Wert von `10.5` abgespeichert. + +## Teilweises Ersetzen mit `PATCH` + +Sie können auch die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH" class="external-link" target="_blank">HTTP `PATCH`</a> Operation verwenden, um Daten *teilweise* zu ersetzen. + +Das bedeutet, sie senden nur die Daten, die Sie aktualisieren wollen, der Rest bleibt unverändert. + +!!! note "Hinweis" + `PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`. + + Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen. + + Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf. + + Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden. + +### Pydantics `exclude_unset`-Parameter verwenden + +Wenn Sie Teil-Aktualisierungen entgegennehmen, ist der `exclude_unset`-Parameter in der `.model_dump()`-Methode von Pydantic-Modellen sehr nützlich. + +Wie in `item.model_dump(exclude_unset=True)`. + +!!! info + In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + + Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen. + +Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte: + +=== "Python 3.10+" + + ```Python hl_lines="32" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="34" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="34" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +### Pydantics `update`-Parameter verwenden + +Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben. + +!!! info + In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt. + + Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können. + +Wie in `stored_item_model.model_copy(update=update_data)`: + +=== "Python 3.10+" + + ```Python hl_lines="33" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="35" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="35" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +### Rekapitulation zum teilweisen Ersetzen + +Zusammengefasst, um Teil-Ersetzungen vorzunehmen: + +* (Optional) verwenden Sie `PATCH` statt `PUT`. +* Lesen Sie die bereits gespeicherten Daten aus. +* Fügen Sie diese in ein Pydantic-Modell ein. +* Erzeugen Sie aus dem empfangenen Modell ein `dict` ohne Defaultwerte (mittels `exclude_unset`). + * So ersetzen Sie nur die tatsächlich vom Benutzer gesetzten Werte, statt dass bereits gespeicherte Werte mit Defaultwerten des Modells überschrieben werden. +* Erzeugen Sie eine Kopie ihres gespeicherten Modells, wobei Sie die Attribute mit den empfangenen Teil-Ersetzungen aktualisieren (mittels des `update`-Parameters). +* Konvertieren Sie das kopierte Modell zu etwas, das in ihrer Datenbank gespeichert werden kann (indem Sie beispielsweise `jsonable_encoder` verwenden). + * Das ist vergleichbar dazu, die `.model_dump()`-Methode des Modells erneut aufzurufen, aber es wird sicherstellen, dass die Werte zu Daten konvertiert werden, die ihrerseits zu JSON konvertiert werden können, zum Beispiel `datetime` zu `str`. +* Speichern Sie die Daten in Ihrer Datenbank. +* Geben Sie das aktualisierte Modell zurück. + +=== "Python 3.10+" + + ```Python hl_lines="28-35" + {!> ../../../docs_src/body_updates/tutorial002_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="30-37" + {!> ../../../docs_src/body_updates/tutorial002_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="30-37" + {!> ../../../docs_src/body_updates/tutorial002.py!} + ``` + +!!! tip "Tipp" + Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. + + Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde. + +!!! note "Hinweis" + Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. + + Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`). + + Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden. From 71c60bc5f56d0d18dfa88852722f41d2b4ae2224 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:26:47 +0100 Subject: [PATCH 226/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/extra-models.md`=20(#10351)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/extra-models.md | 257 ++++++++++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 docs/de/docs/tutorial/extra-models.md diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md new file mode 100644 index 000000000..cdf16c4ba --- /dev/null +++ b/docs/de/docs/tutorial/extra-models.md @@ -0,0 +1,257 @@ +# Extramodelle + +Fahren wir beim letzten Beispiel fort. Es gibt normalerweise mehrere zusammengehörende Modelle. + +Insbesondere Benutzermodelle, denn: + +* Das **hereinkommende Modell** sollte ein Passwort haben können. +* Das **herausgehende Modell** sollte kein Passwort haben. +* Das **Datenbankmodell** sollte wahrscheinlich ein <abbr title='Ein aus scheinbar zufälligen Zeichen bestehender „Fingerabdruck“ eines Textes. Der Inhalt des Textes kann nicht eingesehen werden.'>gehashtes</abbr> Passwort haben. + +!!! danger "Gefahr" + Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. + + Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist. + +## Mehrere Modelle + +Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. + +=== "Python 3.10+" + + ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" + {!> ../../../docs_src/extra_models/tutorial001_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" + {!> ../../../docs_src/extra_models/tutorial001.py!} + ``` + +!!! info + In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + + Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +### Über `**user_in.dict()` + +#### Pydantic's `.dict()` + +`user_in` ist ein Pydantic-Modell der Klasse `UserIn`. + +Pydantic-Modelle haben eine `.dict()`-Methode, die ein `dict` mit den Daten des Modells zurückgibt. + +Wenn wir also ein Pydantic-Objekt `user_in` erstellen, etwa so: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +und wir rufen seine `.dict()`-Methode auf: + +```Python +user_dict = user_in.dict() +``` + +dann haben wir jetzt in der Variable `user_dict` ein `dict` mit den gleichen Daten (es ist ein `dict` statt eines Pydantic-Modellobjekts). + +Wenn wir es ausgeben: + +```Python +print(user_dict) +``` + +bekommen wir ein Python-`dict`: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### Ein `dict` entpacken + +Wenn wir ein `dict` wie `user_dict` nehmen, und es einer Funktion (oder Klassenmethode) mittels `**user_dict` übergeben, wird Python es „entpacken“. Es wird die Schlüssel und Werte von `user_dict` direkt als Schlüsselwort-Argumente übergeben. + +Wenn wir also das `user_dict` von oben nehmen und schreiben: + +```Python +UserInDB(**user_dict) +``` + +dann ist das ungefähr äquivalent zu: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +Oder, präziser, `user_dict` wird direkt verwendet, welche Werte es auch immer haben mag: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### Ein Pydantic-Modell aus den Inhalten eines anderen erstellen. + +Da wir in obigem Beispiel `user_dict` mittels `user_in.dict()` erzeugt haben, ist dieser Code: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +äquivalent zu: + +```Python +UserInDB(**user_in.dict()) +``` + +... weil `user_in.dict()` ein `dict` ist, und dann lassen wir Python es „entpacken“, indem wir es `UserInDB` übergeben, mit vorangestelltem `**`. + +Wir erhalten also ein Pydantic-Modell aus den Daten eines anderen Pydantic-Modells. + +#### Ein `dict` entpacken und zusätzliche Schlüsselwort-Argumente + +Und dann fügen wir ein noch weiteres Schlüsselwort-Argument hinzu, `hashed_password=hashed_password`: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +... was am Ende ergibt: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +!!! warning "Achtung" + Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. + +## Verdopplung vermeiden + +Reduzierung von Code-Verdoppelung ist eine der Kern-Ideen von **FastAPI**. + +Weil Verdoppelung von Code die Wahrscheinlichkeit von Fehlern, Sicherheitsproblemen, Desynchronisation (Code wird nur an einer Stelle verändert, aber nicht an einer anderen), usw. erhöht. + +Unsere Modelle teilen alle eine Menge der Daten und verdoppeln Attribut-Namen und -Typen. + +Das können wir besser machen. + +Wir deklarieren ein `UserBase`-Modell, das als Basis für unsere anderen Modelle dient. Dann können wir Unterklassen erstellen, die seine Attribute (Typdeklarationen, Validierungen, usw.) erben. + +Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch wie gehabt funktionieren. + +Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): + +=== "Python 3.10+" + + ```Python hl_lines="7 13-14 17-18 21-22" + {!> ../../../docs_src/extra_models/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 15-16 19-20 23-24" + {!> ../../../docs_src/extra_models/tutorial002.py!} + ``` + +## `Union`, oder `anyOf` + +Sie können deklarieren, dass eine Response eine <abbr title="Union – Verbund, Einheit‚ Vereinigung: Eines von Mehreren">`Union`</abbr> mehrerer Typen ist, sprich, einer dieser Typen. + +Das wird in OpenAPI mit `anyOf` angezeigt. + +Um das zu tun, verwenden Sie Pythons Standard-Typhinweis <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: + +!!! note "Hinweis" + Listen Sie, wenn Sie eine <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a> definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. + +=== "Python 3.10+" + + ```Python hl_lines="1 14-15 18-20 33" + {!> ../../../docs_src/extra_models/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 14-15 18-20 33" + {!> ../../../docs_src/extra_models/tutorial003.py!} + ``` + +### `Union` in Python 3.10 + +In diesem Beispiel übergeben wir dem Argument `response_model` den Wert `Union[PlaneItem, CarItem]`. + +Da wir es als **Wert einem Argument überreichen**, statt es als **Typannotation** zu verwenden, müssen wir `Union` verwenden, selbst in Python 3.10. + +Wenn es eine Typannotation gewesen wäre, hätten wir auch den vertikalen Trennstrich verwenden können, wie in: + +```Python +some_variable: PlaneItem | CarItem +``` + +Aber wenn wir das in der Zuweisung `response_model=PlaneItem | CarItem` machen, erhalten wir eine Fehlermeldung, da Python versucht, eine **ungültige Operation** zwischen `PlaneItem` und `CarItem` durchzuführen, statt es als Typannotation zu interpretieren. + +## Listen von Modellen + +Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. + +Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): + +=== "Python 3.9+" + + ```Python hl_lines="18" + {!> ../../../docs_src/extra_models/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 20" + {!> ../../../docs_src/extra_models/tutorial004.py!} + ``` + +## Response mit beliebigem `dict` + +Sie könne auch eine Response deklarieren, die ein beliebiges `dict` zurückgibt, bei dem nur die Typen der Schlüssel und der Werte bekannt sind, ohne ein Pydantic-Modell zu verwenden. + +Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein nicht wissen (was für ein Pydantic-Modell notwendig ist). + +In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): + +=== "Python 3.9+" + + ```Python hl_lines="6" + {!> ../../../docs_src/extra_models/tutorial005_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 8" + {!> ../../../docs_src/extra_models/tutorial005.py!} + ``` + +## Zusammenfassung + +Verwenden Sie gerne mehrere Pydantic-Modelle und vererben Sie je nach Bedarf. + +Sie brauchen kein einzelnes Datenmodell pro Einheit, wenn diese Einheit verschiedene Zustände annehmen kann. So wie unsere Benutzer-„Einheit“, welche einen Zustand mit `password`, einen mit `password_hash` und einen ohne Passwort hatte. From a8127fe48f7497be52ab754fa791827d8a3fd8df Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:26:58 +0100 Subject: [PATCH 227/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/response-model.md`=20(#10345)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/response-model.md | 486 ++++++++++++++++++++++++ 1 file changed, 486 insertions(+) create mode 100644 docs/de/docs/tutorial/response-model.md diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md new file mode 100644 index 000000000..d5b92e0f9 --- /dev/null +++ b/docs/de/docs/tutorial/response-model.md @@ -0,0 +1,486 @@ +# Responsemodell – Rückgabetyp + +Sie können den Typ der <abbr title="Response – Antwort: Daten, die zum anfragenden Client zurückgeschickt werden">Response</abbr> deklarieren, indem Sie den **Rückgabetyp** der *Pfadoperation* annotieren. + +Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten von Funktions-**Parametern** machen; verwenden Sie Pydantic-Modelle, Listen, Dicts und skalare Werte wie Nummern, Booleans, usw. + +=== "Python 3.10+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18 23" + {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18 23" + {!> ../../../docs_src/response_model/tutorial001_01.py!} + ``` + +FastAPI wird diesen Rückgabetyp verwenden, um: + +* Die zurückzugebenden Daten zu **validieren**. + * Wenn die Daten ungültig sind (Sie haben z. B. ein Feld vergessen), bedeutet das, *Ihr* Anwendungscode ist fehlerhaft, er gibt nicht zurück, was er sollte, und daher wird ein <abbr title="Server-Fehler">Server-Error</abbr> ausgegeben, statt falscher Daten. So können Sie und ihre Clients sicher sein, dass diese die erwarteten Daten, in der richtigen Form erhalten. +* In der OpenAPI *Pfadoperation* ein **JSON-Schema** für die Response hinzuzufügen. + * Dieses wird von der **automatischen Dokumentation** verwendet. + * Es wird auch von automatisch Client-Code-generierenden Tools verwendet. + +Aber am wichtigsten: + +* Es wird die Ausgabedaten auf das **limitieren und filtern**, was im Rückgabetyp definiert ist. + * Das ist insbesondere für die **Sicherheit** wichtig, mehr dazu unten. + +## `response_model`-Parameter + +Es gibt Fälle, da möchten oder müssen Sie Daten zurückgeben, die nicht genau dem entsprechen, was der Typ deklariert. + +Zum Beispiel könnten Sie **ein Dict zurückgeben** wollen, oder ein Datenbank-Objekt, aber **es als Pydantic-Modell deklarieren**. Auf diese Weise übernimmt das Pydantic-Modell alle Datendokumentation, -validierung, usw. für das Objekt, welches Sie zurückgeben (z. B. ein Dict oder ein Datenbank-Objekt). + +Würden Sie eine hierfür eine Rückgabetyp-Annotation verwenden, dann würden Tools und Editoren (korrekterweise) Fehler ausgeben, die Ihnen sagen, dass Ihre Funktion einen Typ zurückgibt (z. B. ein Dict), der sich unterscheidet von dem, was Sie deklariert haben (z. B. ein Pydantic-Modell). + +In solchen Fällen können Sie statt des Rückgabetyps den **Pfadoperation-Dekorator**-Parameter `response_model` verwenden. + +Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* usw. + +=== "Python 3.10+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 22 24-27" + {!> ../../../docs_src/response_model/tutorial001.py!} + ``` + +!!! note "Hinweis" + Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. + +`response_model` nimmt denselben Typ entgegen, den Sie auch für ein Pydantic-Modellfeld deklarieren würden, also etwa ein Pydantic-Modell, aber es kann auch z. B. eine `list`e von Pydantic-Modellen sein, wie etwa `List[Item]`. + +FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**. + +!!! tip "Tipp" + Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als <abbr title='„Irgend etwas“'>`Any`</abbr> deklarieren. + + So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`. + +### `response_model`-Priorität + +Wenn sowohl Rückgabetyp als auch `response_model` deklariert sind, hat `response_model` die Priorität und wird von FastAPI bevorzugt verwendet. + +So können Sie korrekte Typannotationen zu ihrer Funktion hinzufügen, die von ihrem Editor und Tools wie mypy verwendet werden. Und dennoch übernimmt FastAPI die Validierung und Dokumentation, usw., der Daten anhand von `response_model`. + +Sie können auch `response_model=None` verwenden, um das Erstellen eines Responsemodells für diese *Pfadoperation* zu unterbinden. Sie könnten das tun wollen, wenn sie Dinge annotieren, die nicht gültige Pydantic-Felder sind. Ein Beispiel dazu werden Sie in einer der Abschnitte unten sehen. + +## Dieselben Eingabedaten zurückgeben + +Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: + +=== "Python 3.10+" + + ```Python hl_lines="7 9" + {!> ../../../docs_src/response_model/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11" + {!> ../../../docs_src/response_model/tutorial002.py!} + ``` + +!!! info + Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. + + Z. B. `pip install email-validator` + oder `pip install pydantic[email]`. + +Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: + +=== "Python 3.10+" + + ```Python hl_lines="16" + {!> ../../../docs_src/response_model/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/response_model/tutorial002.py!} + ``` + +Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. + +Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das Passwort sendet. + +Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken. + +!!! danger "Gefahr" + Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. + +## Ausgabemodell hinzufügen + +Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: + +=== "Python 3.10+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 11 16" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: + +=== "Python 3.10+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: + +=== "Python 3.10+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial003.py!} + ``` + +Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). + +### `response_model` oder Rückgabewert + +Da unsere zwei Modelle in diesem Fall unterschiedlich sind, würde, wenn wir den Rückgabewert der Funktion als `UserOut` deklarieren, der Editor sich beschweren, dass wir einen ungültigen Typ zurückgeben, weil das unterschiedliche Klassen sind. + +Darum müssen wir es in diesem Fall im `response_model`-Parameter deklarieren. + +... aber lesen Sie weiter, um zu sehen, wie man das anders lösen kann. + +## Rückgabewert und Datenfilterung + +Führen wir unser vorheriges Beispiel fort. Wir wollten **die Funktion mit einem Typ annotieren**, aber etwas zurückgeben, das **weniger Daten** enthält. + +Wir möchten auch, dass FastAPI die Daten weiterhin, dem Responsemodell entsprechend, **filtert**. + +Im vorherigen Beispiel mussten wir den `response_model`-Parameter verwenden, weil die Klassen unterschiedlich waren. Das bedeutet aber auch, wir bekommen keine Unterstützung vom Editor und anderen Tools, die den Funktions-Rückgabewert überprüfen. + +Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Modell einige der Daten **filtert/entfernt**, so wie in diesem Beispiel. + +Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. + +=== "Python 3.10+" + + ```Python hl_lines="7-10 13-14 18" + {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-13 15-16 20" + {!> ../../../docs_src/response_model/tutorial003_01.py!} + ``` + +Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. + +Wie funktioniert das? Schauen wir uns das mal an. 🤓 + +### Typannotationen und Tooling + +Sehen wir uns zunächst an, wie Editor, mypy und andere Tools dies sehen würden. + +`BaseUser` verfügt über die Basis-Felder. Dann erbt `UserIn` von `BaseUser` und fügt das Feld `Passwort` hinzu, sodass dass es nun alle Felder beider Modelle hat. + +Wir annotieren den Funktionsrückgabetyp als `BaseUser`, geben aber tatsächlich eine `UserIn`-Instanz zurück. + +Für den Editor, mypy und andere Tools ist das kein Problem, da `UserIn` eine Unterklasse von `BaseUser` ist (Salopp: `UserIn` ist ein `BaseUser`). Es handelt sich um einen *gültigen* Typ, solange irgendetwas überreicht wird, das ein `BaseUser` ist. + +### FastAPI Datenfilterung + +FastAPI seinerseits wird den Rückgabetyp sehen und sicherstellen, dass das, was zurückgegeben wird, **nur** diejenigen Felder enthält, welche im Typ deklariert sind. + +FastAPI macht intern mehrere Dinge mit Pydantic, um sicherzustellen, dass obige Ähnlichkeitsregeln der Klassenvererbung nicht auf die Filterung der zurückgegebenen Daten angewendet werden, sonst könnten Sie am Ende mehr Daten zurückgeben als gewollt. + +Auf diese Weise erhalten Sie das beste beider Welten: Sowohl Typannotationen mit **Tool-Unterstützung** als auch **Datenfilterung**. + +## Anzeige in der Dokumentation + +Wenn Sie sich die automatische Dokumentation betrachten, können Sie sehen, dass Eingabe- und Ausgabemodell beide ihr eigenes JSON-Schema haben: + +<img src="/img/tutorial/response-model/image01.png"> + +Und beide Modelle werden auch in der interaktiven API-Dokumentation verwendet: + +<img src="/img/tutorial/response-model/image02.png"> + +## Andere Rückgabetyp-Annotationen + +Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydantic-Feld ist, und Sie annotieren es in der Funktion nur, um Unterstützung von Tools zu erhalten (Editor, mypy, usw.). + +### Eine Response direkt zurückgeben + +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!} +``` + +Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. + +Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch `JSONResponse` Unterklassen von `Response` sind, die Typannotation ist daher korrekt. + +### Eine Unterklasse von Response annotieren + +Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. + +```Python hl_lines="8-9" +{!> ../../../docs_src/response_model/tutorial003_03.py!} +``` + +Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. + +### Ungültige Rückgabetyp-Annotationen + +Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pydantic-Typ ist (z. B. ein Datenbank-Objekt), und Sie annotieren es so in der Funktion, wird FastAPI versuchen, ein Pydantic-Responsemodell von dieser Typannotation zu erstellen, und scheitern. + +Das gleiche wird passieren, wenn Sie eine <abbr title='Eine Union mehrerer Typen bedeutet: „Irgendeiner dieser Typen“'>Union</abbr> mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/response_model/tutorial003_04.py!} + ``` + +... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. + +### Responsemodell deaktivieren + +Beim Beispiel oben fortsetzend, mögen Sie vielleicht die standardmäßige Datenvalidierung, -Dokumentation, -Filterung, usw., die von FastAPI durchgeführt wird, nicht haben. + +Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unterstützung von Editoren und Typcheckern (z. B. mypy) zu erhalten. + +In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/response_model/tutorial003_05.py!} + ``` + +Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 + +## Parameter für die Enkodierung des Responsemodells + +Ihr Responsemodell könnte Defaultwerte haben, wie: + +=== "Python 3.10+" + + ```Python hl_lines="9 11-12" + {!> ../../../docs_src/response_model/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11 13-14" + {!> ../../../docs_src/response_model/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11 13-14" + {!> ../../../docs_src/response_model/tutorial004.py!} + ``` + +* `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. +* `tax: float = 10.5` hat einen Defaultwert `10.5`. +* `tags: List[str] = []` hat eine leere Liste als Defaultwert: `[]`. + +Aber Sie möchten diese vielleicht vom Resultat ausschließen, wenn Sie gar nicht gesetzt wurden. + +Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Datenbank haben, und Sie möchten nicht ellenlange JSON-Responses voller Defaultwerte senden. + +### Den `response_model_exclude_unset`-Parameter verwenden + +Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: + +=== "Python 3.10+" + + ```Python hl_lines="22" + {!> ../../../docs_src/response_model/tutorial004_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial004_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/response_model/tutorial004.py!} + ``` + +Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. + +Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wird (ohne die Defaultwerte) die Response sein: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info + In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + + Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +!!! info + FastAPI verwendet `.dict()` von Pydantic Modellen, <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">mit dessen `exclude_unset`-Parameter</a>, um das zu erreichen. + +!!! info + Sie können auch: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + verwenden, wie in der <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic Dokumentation</a> für `exclude_defaults` und `exclude_none` beschrieben. + +#### Daten mit Werten für Felder mit Defaultwerten + +Aber wenn ihre Daten Werte für Modellfelder mit Defaultwerten haben, wie etwa der Artikel mit der ID `bar`: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +dann werden diese Werte in der Response enthalten sein. + +#### Daten mit den gleichen Werten wie die Defaultwerte + +Wenn Daten die gleichen Werte haben wie ihre Defaultwerte, wie etwa der Artikel mit der ID `baz`: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, dass, obwohl `description`, `tax`, und `tags` die gleichen Werte haben wie ihre Defaultwerte, sie explizit gesetzt wurden (statt dass sie von den Defaultwerten genommen wurden). + +Diese Felder werden also in der JSON-Response enthalten sein. + +!!! tip "Tipp" + Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. + + Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein. + +### `response_model_include` und `response_model_exclude` + +Sie können auch die Parameter `response_model_include` und `response_model_exclude` im **Pfadoperation-Dekorator** verwenden. + +Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, die eingeschlossen (ohne die Anderen) oder ausgeschlossen (nur die Anderen) werden sollen. + +Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen. + +!!! tip "Tipp" + Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. + + Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen. + + Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. + +=== "Python 3.10+" + + ```Python hl_lines="29 35" + {!> ../../../docs_src/response_model/tutorial005_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31 37" + {!> ../../../docs_src/response_model/tutorial005.py!} + ``` + +!!! tip "Tipp" + Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. + + Äquivalent zu `set(["name", "description"])`. + +#### `list`en statt `set`s verwenden + +Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: + +=== "Python 3.10+" + + ```Python hl_lines="29 35" + {!> ../../../docs_src/response_model/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="31 37" + {!> ../../../docs_src/response_model/tutorial006.py!} + ``` + +## Zusammenfassung + +Verwenden Sie den Parameter `response_model` im *Pfadoperation-Dekorator*, um Responsemodelle zu definieren, und besonders, um private Daten herauszufiltern. + +Verwenden Sie `response_model_exclude_unset`, um nur explizit gesetzte Werte zurückzugeben. From a2d42e32d220a7f0473ec7992b4e8a04eb1cd415 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:27:06 +0100 Subject: [PATCH 228/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/security/oauth2-jwt.md`=20(#1?= =?UTF-8?q?0522)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/security/oauth2-jwt.md | 393 +++++++++++++++++++ 1 file changed, 393 insertions(+) create mode 100644 docs/de/docs/tutorial/security/oauth2-jwt.md diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..9f43cccc9 --- /dev/null +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,393 @@ +# OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens + +Da wir nun über den gesamten Sicherheitsablauf verfügen, machen wir die Anwendung tatsächlich sicher, indem wir <abbr title="JSON Web Tokens">JWT</abbr>-Tokens und sicheres Passwort-Hashing verwenden. + +Diesen Code können Sie tatsächlich in Ihrer Anwendung verwenden, die Passwort-Hashes in Ihrer Datenbank speichern, usw. + +Wir bauen auf dem vorherigen Kapitel auf. + +## Über JWT + +JWT bedeutet „JSON Web Tokens“. + +Es ist ein Standard, um ein JSON-Objekt in einem langen, kompakten String ohne Leerzeichen zu kodieren. Das sieht so aus: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +Da er nicht verschlüsselt ist, kann jeder die Informationen aus dem Inhalt wiederherstellen. + +Aber er ist signiert. Wenn Sie also einen von Ihnen gesendeten Token zurückerhalten, können Sie überprüfen, ob Sie ihn tatsächlich gesendet haben. + +Auf diese Weise können Sie einen Token mit einer Gültigkeitsdauer von beispielsweise einer Woche erstellen. Und wenn der Benutzer am nächsten Tag mit dem Token zurückkommt, wissen Sie, dass der Benutzer immer noch bei Ihrem System angemeldet ist. + +Nach einer Woche läuft der Token ab und der Benutzer wird nicht autorisiert und muss sich erneut anmelden, um einen neuen Token zu erhalten. Und wenn der Benutzer (oder ein Dritter) versuchen würde, den Token zu ändern, um das Ablaufdatum zu ändern, würden Sie das entdecken, weil die Signaturen nicht übereinstimmen würden. + +Wenn Sie mit JWT-Tokens spielen und sehen möchten, wie sie funktionieren, schauen Sie sich <a href="https://jwt.io/" class="external-link" target="_blank">https://jwt.io</a> an. + +## `python-jose` installieren. + +Wir müssen <abbr title="JOSE: JavaScript Object Signing and Encryption">`python-jose`</abbr> installieren, um die JWT-Tokens in Python zu generieren und zu verifizieren: + +<div class="termy"> + +```console +$ pip install "python-jose[cryptography]" + +---> 100% +``` + +</div> + +<a href="https://github.com/mpdavis/python-jose" class="external-link" target="_blank">python-jose</a> erfordert zusätzlich ein kryptografisches Backend. + +Hier verwenden wir das empfohlene: <a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>. + +!!! tip "Tipp" + Dieses Tutorial verwendete zuvor <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>. + + Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen. + +## Passwort-Hashing + +„Hashing“ bedeutet: Konvertieren eines Inhalts (in diesem Fall eines Passworts) in eine Folge von Bytes (ein schlichter String), die wie Kauderwelsch aussieht. + +Immer wenn Sie genau den gleichen Inhalt (genau das gleiche Passwort) übergeben, erhalten Sie genau den gleichen Kauderwelsch. + +Sie können jedoch nicht vom Kauderwelsch zurück zum Passwort konvertieren. + +### Warum Passwort-Hashing verwenden? + +Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Ihrer Benutzer, sondern nur die Hashes. + +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). + +## `passlib` installieren + +PassLib ist ein großartiges Python-Package, um Passwort-Hashes zu handhaben. + +Es unterstützt viele sichere Hashing-Algorithmen und Werkzeuge, um mit diesen zu arbeiten. + +Der empfohlene Algorithmus ist „Bcrypt“. + +Installieren Sie also PassLib mit Bcrypt: + +<div class="termy"> + +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +</div> + +!!! tip "Tipp" + Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. + + So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden. + + Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden. + +## Die Passwörter hashen und überprüfen + +Importieren Sie die benötigten Tools aus `passlib`. + +Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet. + +!!! tip "Tipp" + Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. + + Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen. + + Und mit allen gleichzeitig kompatibel sein. + +Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen. + +Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespeicherten Hash übereinstimmt. + +Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. + +=== "Python 3.10+" + + ```Python hl_lines="7 48 55-56 59-60 69-75" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="7 48 55-56 59-60 69-75" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7 49 56-57 60-61 70-76" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! note "Hinweis" + Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +## JWT-Token verarbeiten + +Importieren Sie die installierten Module. + +Erstellen Sie einen zufälligen geheimen Schlüssel, der zum Signieren der JWT-Tokens verwendet wird. + +Um einen sicheren zufälligen geheimen Schlüssel zu generieren, verwenden Sie den folgenden Befehl: + +<div class="termy"> + +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +</div> + +Und kopieren Sie die Ausgabe in die Variable `SECRET_KEY` (verwenden Sie nicht die im Beispiel). + +Erstellen Sie eine Variable `ALGORITHM` für den Algorithmus, der zum Signieren des JWT-Tokens verwendet wird, und setzen Sie sie auf `"HS256"`. + +Erstellen Sie eine Variable für das Ablaufdatum des Tokens. + +Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verwendet wird. + +Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. + +=== "Python 3.10+" + + ```Python hl_lines="6 12-14 28-30 78-86" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="6 12-14 28-30 78-86" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="6 13-15 29-31 79-87" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +## Die Abhängigkeiten aktualisieren + +Aktualisieren Sie `get_current_user`, um den gleichen Token wie zuvor zu erhalten, dieses Mal jedoch unter Verwendung von JWT-Tokens. + +Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktuellen Benutzer zurück. + +Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. + +=== "Python 3.10+" + + ```Python hl_lines="89-106" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="89-106" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="90-107" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="89-106" + {!> ../../../docs_src/security/tutorial004.py!} + ``` + +## Die *Pfadoperation* `/token` aktualisieren + +Erstellen Sie ein <abbr title="Zeitdifferenz">`timedelta`</abbr> mit der Ablaufzeit des Tokens. + +Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. + +=== "Python 3.10+" + + ```Python hl_lines="117-132" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="117-132" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="118-133" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +### Technische Details zum JWT-„Subjekt“ `sub` + +Die JWT-Spezifikation besagt, dass es einen Schlüssel `sub` mit dem Subjekt des Tokens gibt. + +Die Verwendung ist optional, aber dort würden Sie die Identifikation des Benutzers speichern, daher verwenden wir das hier. + +JWT kann auch für andere Dinge verwendet werden, abgesehen davon, einen Benutzer zu identifizieren und ihm zu erlauben, Operationen direkt auf Ihrer API auszuführen. + +Sie könnten beispielsweise ein „Auto“ oder einen „Blog-Beitrag“ identifizieren. + +Anschließend könnten Sie Berechtigungen für diese Entität hinzufügen, etwa „Fahren“ (für das Auto) oder „Bearbeiten“ (für den Blog). + +Und dann könnten Sie diesen JWT-Token einem Benutzer (oder Bot) geben und dieser könnte ihn verwenden, um diese Aktionen auszuführen (das Auto fahren oder den Blog-Beitrag bearbeiten), ohne dass er überhaupt ein Konto haben müsste, einfach mit dem JWT-Token, den Ihre API dafür generiert hat. + +Mit diesen Ideen kann JWT für weitaus anspruchsvollere Szenarien verwendet werden. + +In diesen Fällen könnten mehrere dieser Entitäten die gleiche ID haben, sagen wir `foo` (ein Benutzer `foo`, ein Auto `foo` und ein Blog-Beitrag `foo`). + +Deshalb, um ID-Kollisionen zu vermeiden, könnten Sie beim Erstellen des JWT-Tokens für den Benutzer, dem Wert des `sub`-Schlüssels ein Präfix, z. B. `username:` voranstellen. In diesem Beispiel hätte der Wert von `sub` also auch `username:johndoe` sein können. + +Der wesentliche Punkt ist, dass der `sub`-Schlüssel in der gesamten Anwendung eine eindeutige Kennung haben sollte, und er sollte ein String sein. + +## Es testen + +Führen Sie den Server aus und gehen Sie zur Dokumentation: <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Die Benutzeroberfläche sieht wie folgt aus: + +<img src="/img/tutorial/security/image07.png"> + +Melden Sie sich bei der Anwendung auf die gleiche Weise wie zuvor an. + +Verwenden Sie die Anmeldeinformationen: + +Benutzername: `johndoe` +Passwort: `secret`. + +!!! check + Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version. + +<img src="/img/tutorial/security/image08.png"> + +Rufen Sie den Endpunkt `/users/me/` auf, Sie erhalten die Response: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + +<img src="/img/tutorial/security/image09.png"> + +Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Daten nur den Token enthalten. Das Passwort wird nur bei der ersten Anfrage gesendet, um den Benutzer zu authentisieren und diesen Zugriffstoken zu erhalten, aber nicht mehr danach: + +<img src="/img/tutorial/security/image10.png"> + +!!! note "Hinweis" + Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. + +## Fortgeschrittene Verwendung mit `scopes` + +OAuth2 hat ein Konzept von <abbr title="Geltungsbereiche">„Scopes“</abbr>. + +Sie können diese verwenden, um einem JWT-Token einen bestimmten Satz von Berechtigungen zu übergeben. + +Anschließend können Sie diesen Token einem Benutzer direkt oder einem Dritten geben, damit diese mit einer Reihe von Einschränkungen mit Ihrer API interagieren können. + +Wie Sie sie verwenden und wie sie in **FastAPI** integriert sind, erfahren Sie später im **Handbuch für fortgeschrittene Benutzer**. + +## Zusammenfassung + +Mit dem, was Sie bis hier gesehen haben, können Sie eine sichere **FastAPI**-Anwendung mithilfe von Standards wie OAuth2 und JWT einrichten. + +In fast jedem Framework wird die Handhabung der Sicherheit recht schnell zu einem ziemlich komplexen Thema. + +Viele Packages, die es stark vereinfachen, müssen viele Kompromisse beim Datenmodell, der Datenbank und den verfügbaren Funktionen eingehen. Und einige dieser Pakete, die die Dinge zu sehr vereinfachen, weisen tatsächlich Sicherheitslücken auf. + +--- + +**FastAPI** geht bei keiner Datenbank, keinem Datenmodell oder Tool Kompromisse ein. + +Es gibt Ihnen die volle Flexibilität, diejenigen auszuwählen, die am besten zu Ihrem Projekt passen. + +Und Sie können viele gut gepflegte und weit verbreitete Packages wie `passlib` und `python-jose` direkt verwenden, da **FastAPI** keine komplexen Mechanismen zur Integration externer Pakete erfordert. + +Aber es bietet Ihnen die Werkzeuge, um den Prozess so weit wie möglich zu vereinfachen, ohne Kompromisse bei Flexibilität, Robustheit oder Sicherheit einzugehen. + +Und Sie können sichere Standardprotokolle wie OAuth2 auf relativ einfache Weise verwenden und implementieren. + +Im **Handbuch für fortgeschrittene Benutzer** erfahren Sie mehr darüber, wie Sie OAuth2-„Scopes“ für ein feingranuliertes Berechtigungssystem verwenden, das denselben Standards folgt. OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter, usw. verwendet wird, um Drittanbieteranwendungen zu autorisieren, im Namen ihrer Benutzer mit ihren APIs zu interagieren. From 150601066450b676b649077560eb111f2bac8253 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:27:14 +0100 Subject: [PATCH 229/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/static-files.md`=20(#10584)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/static-files.md | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/de/docs/tutorial/static-files.md diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md new file mode 100644 index 000000000..1e289e120 --- /dev/null +++ b/docs/de/docs/tutorial/static-files.md @@ -0,0 +1,39 @@ +# Statische Dateien + +Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisch bereitstellen. + +## `StaticFiles` verwenden + +* Importieren Sie `StaticFiles`. +* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. + +```Python hl_lines="2 6" +{!../../../docs_src/static_files/tutorial001.py!} +``` + +!!! note "Technische Details" + Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. + + **FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +### Was ist „Mounten“? + +„Mounten“ bedeutet das Hinzufügen einer vollständigen „unabhängigen“ Anwendung an einem bestimmten Pfad, die sich dann um die Handhabung aller Unterpfade kümmert. + +Dies unterscheidet sich von der Verwendung eines `APIRouter`, da eine gemountete Anwendung völlig unabhängig ist. Die OpenAPI und Dokumentation Ihrer Hauptanwendung enthalten nichts von der gemounteten Anwendung, usw. + +Weitere Informationen hierzu finden Sie im [Handbuch für fortgeschrittene Benutzer](../advanced/index.md){.internal-link target=_blank}. + +## Einzelheiten + +Das erste `"/static"` bezieht sich auf den Unterpfad, auf dem diese „Unteranwendung“ „gemountet“ wird. Daher wird jeder Pfad, der mit `"/static"` beginnt, von ihr verarbeitet. + +Das `directory="static"` bezieht sich auf den Namen des Verzeichnisses, das Ihre statischen Dateien enthält. + +Das `name="static"` gibt dieser Unteranwendung einen Namen, der intern von **FastAPI** verwendet werden kann. + +Alle diese Parameter können anders als "`static`" lauten, passen Sie sie an die Bedürfnisse und spezifischen Details Ihrer eigenen Anwendung an. + +## Weitere Informationen + +Weitere Details und Optionen finden Sie in der <a href="https://www.starlette.io/staticfiles/" class="external-link" target="_blank">Dokumentation von Starlette zu statischen Dateien</a>. From f5410ce24a10182f0ed0c3ca8ecee5f88279c988 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:27:23 +0100 Subject: [PATCH 230/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/path-operation-advanced-confi?= =?UTF-8?q?guration.md`=20(#10612)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-operation-advanced-configuration.md | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 docs/de/docs/advanced/path-operation-advanced-configuration.md diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md new file mode 100644 index 000000000..406a08e9e --- /dev/null +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -0,0 +1,192 @@ +# Fortgeschrittene Konfiguration der Pfadoperation + +## OpenAPI operationId + +!!! warning "Achtung" + Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. + +Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll. + +Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. + +```Python hl_lines="6" +{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +``` + +### Verwendung des Namens der *Pfadoperation-Funktion* als operationId + +Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, können Sie über alle iterieren und die `operation_id` jeder *Pfadoperation* mit deren `APIRoute.name` überschreiben. + +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!} +``` + +!!! tip "Tipp" + Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. + +!!! warning "Achtung" + Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. + + Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. + +## Von OpenAPI ausschließen + +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!} +``` + +## Fortgeschrittene Beschreibung mittels Docstring + +Sie können die verwendeten Zeilen aus dem Docstring einer *Pfadoperation-Funktion* einschränken, die für OpenAPI verwendet werden. + +Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, dass **FastAPI** die für OpenAPI verwendete Ausgabe an dieser Stelle abschneidet. + +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!} +``` + +## Zusätzliche Responses + +Sie haben wahrscheinlich gesehen, wie man das `response_model` und den `status_code` für eine *Pfadoperation* deklariert. + +Das definiert die Metadaten der Haupt-Response einer *Pfadoperation*. + +Sie können auch zusätzliche Responses mit deren Modellen, Statuscodes usw. deklarieren. + +Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es unter [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} lesen. + +## OpenAPI-Extra + +Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. + +!!! note "Technische Details" + In der OpenAPI-Spezifikation wird das <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operationsobjekt</a> genannt. + +Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet. + +Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. + +Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. + +!!! tip "Tipp" + Dies ist ein Low-Level Erweiterungspunkt. + + Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. + +Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden. + +### OpenAPI-Erweiterungen + +Dieses `openapi_extra` kann beispielsweise hilfreich sein, um <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions" class="external-link" target="_blank">OpenAPI-Erweiterungen</a> zu deklarieren: + +```Python hl_lines="6" +{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +``` + +Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. + +<img src="/img/tutorial/path-operation-advanced-configuration/image01.png"> + +Und wenn Sie die resultierende OpenAPI sehen (unter `/openapi.json` in Ihrer API), sehen Sie Ihre Erweiterung auch als Teil der spezifischen *Pfadoperation*: + +```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" + } + } + } +} +``` + +### Benutzerdefiniertes OpenAPI-*Pfadoperation*-Schema + +Das Dictionary in `openapi_extra` wird mit dem automatisch generierten OpenAPI-Schema für die *Pfadoperation* zusammengeführt (mittels Deep Merge). + +Sie können dem automatisch generierten Schema also zusätzliche Daten hinzufügen. + +Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigenen Code zu lesen und zu validieren, ohne die automatischen Funktionen von FastAPI mit Pydantic zu verwenden, aber Sie könnten den Request trotzdem im OpenAPI-Schema definieren wollen. + +Das könnte man mit `openapi_extra` machen: + +```Python hl_lines="20-37 39-40" +{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +``` + +In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON <abbr title="von einem einfachen Format, wie Bytes, in Python-Objekte konvertieren">geparst</abbr>, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. + +Dennoch können wir das zu erwartende Schema für den Requestbody deklarieren. + +### Benutzerdefinierter OpenAPI-Content-Type + +Mit demselben Trick könnten Sie ein Pydantic-Modell verwenden, um das JSON-Schema zu definieren, das dann im benutzerdefinierten Abschnitt des OpenAPI-Schemas für die *Pfadoperation* enthalten ist. + +Und Sie könnten dies auch tun, wenn der Datentyp in der Anfrage nicht JSON ist. + +In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON: + +=== "Pydantic v2" + + ```Python hl_lines="17-22 24" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} + ``` + +=== "Pydantic v1" + + ```Python hl_lines="17-22 24" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} + ``` + +!!! info + In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. + +Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren. + +Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das bedeutet, dass FastAPI nicht einmal versucht, den Request-Payload als JSON zu parsen. + +Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren: + +=== "Pydantic v2" + + ```Python hl_lines="26-33" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} + ``` + +=== "Pydantic v1" + + ```Python hl_lines="26-33" + {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} + ``` + +!!! info + In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. + +!!! tip "Tipp" + Hier verwenden wir dasselbe Pydantic-Modell wieder. + + Aber genauso hätten wir es auch auf andere Weise validieren können. From 43c6e408e4dadda7496f4fa148958323684f9ac2 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:27:59 +0100 Subject: [PATCH 231/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/bigger-applications.md`=20(#1?= =?UTF-8?q?0554)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/bigger-applications.md | 506 +++++++++++++++++++ 1 file changed, 506 insertions(+) create mode 100644 docs/de/docs/tutorial/bigger-applications.md diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..66dee0a9a --- /dev/null +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -0,0 +1,506 @@ +# Größere Anwendungen – mehrere Dateien + +Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, dass Sie alles in einer einzigen Datei unterbringen können. + +**FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität. + +!!! info + Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints. + +## Eine Beispiel-Dateistruktur + +Nehmen wir an, Sie haben eine Dateistruktur wie diese: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +│ ├── dependencies.py +│ └── routers +│ │ ├── __init__.py +│ │ ├── items.py +│ │ └── users.py +│ └── internal +│ ├── __init__.py +│ └── admin.py +``` + +!!! tip "Tipp" + Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. + + Das ermöglicht den Import von Code aus einer Datei in eine andere. + + In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben: + + ``` + from app.routers import items + ``` + +* Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`. +* Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`. +* Es gibt auch eine Datei `app/dependencies.py`, genau wie `app/main.py` ist sie ein „Modul“: `app.dependencies`. +* Es gibt ein Unterverzeichnis `app/routers/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein „Python-Subpackage“: `app.routers`. +* Die Datei `app/routers/items.py` befindet sich in einem Package, `app/routers/`, also ist sie ein Submodul: `app.routers.items`. +* Das Gleiche gilt für `app/routers/users.py`, es ist ein weiteres Submodul: `app.routers.users`. +* Es gibt auch ein Unterverzeichnis `app/internal/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein weiteres „Python-Subpackage“: `app.internal`. +* Und die Datei `app/internal/admin.py` ist ein weiteres Submodul: `app.internal.admin`. + +<img src="/img/tutorial/bigger-applications/package.svg"> + +Die gleiche Dateistruktur mit Kommentaren: + +``` +. +├── app # „app“ ist ein Python-Package +│ ├── __init__.py # diese Datei macht „app“ zu einem „Python-Package“ +│ ├── main.py # „main“-Modul, z. B. import app.main +│ ├── dependencies.py # „dependencies“-Modul, z. B. import app.dependencies +│ └── routers # „routers“ ist ein „Python-Subpackage“ +│ │ ├── __init__.py # macht „routers“ zu einem „Python-Subpackage“ +│ │ ├── items.py # „items“-Submodul, z. B. import app.routers.items +│ │ └── users.py # „users“-Submodul, z. B. import app.routers.users +│ └── internal # „internal“ ist ein „Python-Subpackage“ +│ ├── __init__.py # macht „internal“ zu einem „Python-Subpackage“ +│ └── admin.py # „admin“-Submodul, z. B. import app.internal.admin +``` + +## `APIRouter` + +Nehmen wir an, die Datei, die nur für die Verwaltung von Benutzern zuständig ist, ist das Submodul unter `/app/routers/users.py`. + +Sie möchten die *Pfadoperationen* für Ihre Benutzer vom Rest des Codes trennen, um ihn organisiert zu halten. + +Aber es ist immer noch Teil derselben **FastAPI**-Anwendung/Web-API (es ist Teil desselben „Python-Packages“). + +Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen. + +### `APIRouter` importieren + +Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Pfadoperationen* mit `APIRouter` + +Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren. + +Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen. + +Alle die gleichen Optionen werden unterstützt. + +Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw. + +!!! tip "Tipp" + In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. + +Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`. + +## Abhängigkeiten + +Wir sehen, dass wir einige Abhängigkeiten benötigen, die an mehreren Stellen der Anwendung verwendet werden. + +Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`) ein. + +Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen: + +=== "Python 3.9+" + + ```Python hl_lines="3 6-8" title="app/dependencies.py" + {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 5-7" title="app/dependencies.py" + {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="1 4-6" title="app/dependencies.py" + {!> ../../../docs_src/bigger_applications/app/dependencies.py!} + ``` + +!!! tip "Tipp" + Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. + + Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen. + +## Ein weiteres Modul mit `APIRouter`. + +Nehmen wir an, Sie haben im Modul unter `app/routers/items.py` auch die Endpunkte, die für die Verarbeitung von Artikeln („Items“) aus Ihrer Anwendung vorgesehen sind. + +Sie haben *Pfadoperationen* für: + +* `/items/` +* `/items/{item_id}` + +Es ist alles die gleiche Struktur wie bei `app/routers/users.py`. + +Aber wir wollen schlauer sein und den Code etwas vereinfachen. + +Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben: + +* Pfad-`prefix`: `/items`. +* `tags`: (nur ein Tag: `items`). +* Zusätzliche `responses`. +* `dependencies`: Sie alle benötigen die von uns erstellte `X-Token`-Abhängigkeit. + +Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +... darf das Präfix kein abschließendes `/` enthalten. + +Das Präfix lautet in diesem Fall also `/items`. + +Wir können auch eine Liste von `tags` und zusätzliche `responses` hinzufügen, die auf alle in diesem Router enthaltenen *Pfadoperationen* angewendet werden. + +Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden. + +!!! tip "Tipp" + Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird. + +Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten: + +* `/items/` +* `/items/{item_id}` + +... wie wir es beabsichtigt hatten. + +* Sie werden mit einer Liste von Tags gekennzeichnet, die einen einzelnen String `"items"` enthält. + * Diese „Tags“ sind besonders nützlich für die automatischen interaktiven Dokumentationssysteme (unter Verwendung von OpenAPI). +* Alle enthalten die vordefinierten `responses`. +* Für alle diese *Pfadoperationen* wird die Liste der `dependencies` ausgewertet/ausgeführt, bevor sie selbst ausgeführt werden. + * Wenn Sie außerdem Abhängigkeiten in einer bestimmten *Pfadoperation* deklarieren, **werden diese ebenfalls ausgeführt**. + * Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten. + * Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen. + +!!! tip "Tipp" + `dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden. + +!!! check + Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden. + +### Die Abhängigkeiten importieren + +Der folgende Code befindet sich im Modul `app.routers.items`, also in der Datei `app/routers/items.py`. + +Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` importieren, also aus der Datei `app/dependencies.py`. + +Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Wie relative Importe funktionieren + +!!! tip "Tipp" + Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. + +Ein einzelner Punkt `.`, wie in: + +```Python +from .dependencies import get_token_header +``` + +würde bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* finde das Modul `dependencies` (eine imaginäre Datei unter `app/routers/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Aber diese Datei existiert nicht, unsere Abhängigkeiten befinden sich in einer Datei unter `app/dependencies.py`. + +Erinnern Sie sich, wie unsere Anwendungs-/Dateistruktur aussieht: + +<img src="/img/tutorial/bigger-applications/package.svg"> + +--- + +Die beiden Punkte `..`, wie in: + +```Python +from ..dependencies import get_token_header +``` + +bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* gehe zum übergeordneten Package (das Verzeichnis `app/`) ... +* und finde dort das Modul `dependencies` (die Datei unter `app/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Das funktioniert korrekt! 🎉 + +--- + +Das Gleiche gilt, wenn wir drei Punkte `...` verwendet hätten, wie in: + +```Python +from ...dependencies import get_token_header +``` + +Das würde bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* gehe zum übergeordneten Package (das Verzeichnis `app/`) ... +* gehe dann zum übergeordneten Package dieses Packages (es gibt kein übergeordnetes Package, `app` ist die oberste Ebene 😱) ... +* und finde dort das Modul `dependencies` (die Datei unter `app/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Das würde sich auf ein Paket oberhalb von `app/` beziehen, mit seiner eigenen Datei `__init__.py`, usw. Aber das haben wir nicht. Das würde in unserem Beispiel also einen Fehler auslösen. 🚨 + +Aber jetzt wissen Sie, wie es funktioniert, sodass Sie relative Importe in Ihren eigenen Anwendungen verwenden können, egal wie komplex diese sind. 🤓 + +### Einige benutzerdefinierte `tags`, `responses`, und `dependencies` hinzufügen + +Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperation* hinzu, da wir sie zum `APIRouter` hinzugefügt haben. + +Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +!!! tip "Tipp" + Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. + + Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`. + +## Das Haupt-`FastAPI`. + +Sehen wir uns nun das Modul unter `app/main.py` an. + +Hier importieren und verwenden Sie die Klasse `FastAPI`. + +Dies ist die Hauptdatei Ihrer Anwendung, die alles zusammen bindet. + +Und da sich der Großteil Ihrer Logik jetzt in seinem eigenen spezifischen Modul befindet, wird die Hauptdatei recht einfach sein. + +### `FastAPI` importieren + +Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse. + +Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +### Den `APIRouter` importieren + +Jetzt importieren wir die anderen Submodule, die `APIRouter` haben: + +```Python hl_lines="4-5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren. + +### Wie das Importieren funktioniert + +Die Sektion: + +```Python +from .routers import items, users +``` + +bedeutet: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/main.py`) befindet (das Verzeichnis `app/`) ... +* Suche nach dem Subpackage `routers` (das Verzeichnis unter `app/routers/`) ... +* und importiere daraus die Submodule `items` (die Datei unter `app/routers/items.py`) und `users` (die Datei unter `app/routers/users.py`) ... + +Das Modul `items` verfügt über eine Variable `router` (`items.router`). Das ist dieselbe, die wir in der Datei `app/routers/items.py` erstellt haben, es ist ein `APIRouter`-Objekt. + +Und dann machen wir das gleiche für das Modul `users`. + +Wir könnten sie auch wie folgt importieren: + +```Python +from app.routers import items, users +``` + +!!! info + Die erste Version ist ein „relativer Import“: + + ```Python + from .routers import items, users + ``` + + Die zweite Version ist ein „absoluter Import“: + + ```Python + from app.routers import items, users + ``` + + Um mehr über Python-Packages und -Module zu erfahren, lesen Sie <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">die offizielle Python-Dokumentation über Module</a>. + +### Namenskollisionen vermeiden + +Wir importieren das Submodul `items` direkt, anstatt nur seine Variable `router` zu importieren. + +Das liegt daran, dass wir im Submodul `users` auch eine weitere Variable namens `router` haben. + +Wenn wir eine nach der anderen importiert hätten, etwa: + +```Python +from .routers.items import router +from .routers.users import router +``` + +würde der `router` von `users` den von `items` überschreiben und wir könnten sie nicht gleichzeitig verwenden. + +Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt: + +```Python hl_lines="5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + + +### Die `APIRouter` für `users` und `items` inkludieren + +Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +!!! info + `users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`. + + Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`. + +Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen. + +Es wird alle Routen von diesem Router als Teil von dieser inkludieren. + +!!! note "Technische Details" + Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. + + Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre. + +!!! check + Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen. + + Dies dauert Mikrosekunden und geschieht nur beim Start. + + Es hat also keinen Einfluss auf die Leistung. ⚡ + +### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen + +Stellen wir uns nun vor, dass Ihre Organisation Ihnen die Datei `app/internal/admin.py` gegeben hat. + +Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, die Ihre Organisation zwischen mehreren Projekten teilt. + +In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen. + +Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben: + +```Python hl_lines="14-17" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können. + +Das Ergebnis ist, dass in unserer Anwendung jede der *Pfadoperationen* aus dem Modul `admin` Folgendes haben wird: + +* Das Präfix `/admin`. +* Den Tag `admin`. +* Die Abhängigkeit `get_token_header`. +* Die Response `418`. 🍵 + +Dies wirkt sich jedoch nur auf diesen `APIRouter` in unserer Anwendung aus, nicht auf anderen Code, der ihn verwendet. + +So könnten beispielsweise andere Projekte denselben `APIRouter` mit einer anderen Authentifizierungsmethode verwenden. + +### Eine *Pfadoperation* hinzufügen + +Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen. + +Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. + +!!! info "Sehr technische Details" + **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. + + --- + + Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert. + + Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten. + + Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen. + +## Es in der automatischen API-Dokumentation ansehen + +Führen Sie nun `uvicorn` aus, indem Sie das Modul `app.main` und die Variable `app` verwenden: + +<div class="termy"> + +```console +$ uvicorn app.main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +und öffnen Sie die Dokumentation unter <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Sie sehen die automatische API-Dokumentation, einschließlich der Pfade aller Submodule, mit den richtigen Pfaden (und Präfixen) und den richtigen Tags: + +<img src="/img/tutorial/bigger-applications/image01.png"> + +## Den gleichen Router mehrmals mit unterschiedlichem `prefix` inkludieren + +Sie können `.include_router()` auch mehrmals mit *demselben* Router und unterschiedlichen Präfixen verwenden. + +Dies könnte beispielsweise nützlich sein, um dieselbe API unter verschiedenen Präfixen verfügbar zu machen, z. B. `/api/v1` und `/api/latest`. + +Dies ist eine fortgeschrittene Verwendung, die Sie möglicherweise nicht wirklich benötigen, aber für den Fall, dass Sie sie benötigen, ist sie vorhanden. + +## Einen `APIRouter` in einen anderen einfügen + +Auf die gleiche Weise, wie Sie einen `APIRouter` in eine `FastAPI`-Anwendung einbinden können, können Sie einen `APIRouter` in einen anderen `APIRouter` einbinden, indem Sie Folgendes verwenden: + +```Python +router.include_router(other_router) +``` + +Stellen Sie sicher, dass Sie dies tun, bevor Sie `router` in die `FastAPI`-App einbinden, damit auch die *Pfadoperationen* von `other_router` inkludiert werden. From 6de6e672f456f25a856cae0d6ebc6afb9d29a10d Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:28:08 +0100 Subject: [PATCH 232/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/security/http-basic-auth.md`?= =?UTF-8?q?=20(#10651)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/http-basic-auth.md | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 docs/de/docs/advanced/security/http-basic-auth.md diff --git a/docs/de/docs/advanced/security/http-basic-auth.md b/docs/de/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..9f9c0cf7d --- /dev/null +++ b/docs/de/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,164 @@ +# HTTP Basic Auth + +Für die einfachsten Fälle können Sie <abbr title="HTTP-Basisauthentifizierung">HTTP Basic Auth</abbr> verwenden. + +Bei HTTP Basic Auth erwartet die Anwendung einen Header, der einen Benutzernamen und ein Passwort enthält. + +Wenn sie diesen nicht empfängt, gibt sie den HTTP-Error 401 „Unauthorized“ zurück. + +Und gibt einen Header `WWW-Authenticate` mit dem Wert `Basic` und einem optionalen `realm`-Parameter („Bereich“) zurück. + +Dadurch wird der Browser angewiesen, die integrierte Eingabeaufforderung für einen Benutzernamen und ein Passwort anzuzeigen. + +Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser diese automatisch im Header. + +## Einfaches HTTP Basic Auth + +* Importieren Sie `HTTPBasic` und `HTTPBasicCredentials`. +* Erstellen Sie mit `HTTPBasic` ein „`security`-Schema“. +* Verwenden Sie dieses `security` mit einer Abhängigkeit in Ihrer *Pfadoperation*. +* Diese gibt ein Objekt vom Typ `HTTPBasicCredentials` zurück: + * Es enthält den gesendeten `username` und das gesendete `password`. + +=== "Python 3.9+" + + ```Python hl_lines="4 8 12" + {!> ../../../docs_src/security/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="2 7 11" + {!> ../../../docs_src/security/tutorial006_an.py!} + ``` + +=== "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!} + ``` + +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: + +<img src="/img/tutorial/security/image12.png"> + +## Den Benutzernamen überprüfen + +Hier ist ein vollständigeres Beispiel. + +Verwenden Sie eine Abhängigkeit, um zu überprüfen, ob Benutzername und Passwort korrekt sind. + +Verwenden Sie dazu das Python-Standardmodul <a href="https://docs.python.org/3/library/secrets.html" class="external-link" target="_blank">`secrets`</a>, um den Benutzernamen und das Passwort zu überprüfen. + +`secrets.compare_digest()` benötigt `bytes` oder einen `str`, welcher nur ASCII-Zeichen (solche der englischen Sprache) enthalten darf, das bedeutet, dass es nicht mit Zeichen wie `á`, wie in `Sebastián`, funktionieren würde. + +Um dies zu lösen, konvertieren wir zunächst den `username` und das `password` in UTF-8-codierte `bytes`. + +Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist. + +=== "Python 3.9+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an.py!} + ``` + +=== "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!} + ``` + +Dies wäre das gleiche wie: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Einen Error zurückgeben + ... +``` + +Aber durch die Verwendung von `secrets.compare_digest()` ist dieser Code sicher vor einer Art von Angriffen, die „Timing-Angriffe“ genannt werden. + +### Timing-Angriffe + +Aber was ist ein „Timing-Angriff“? + +Stellen wir uns vor, dass einige Angreifer versuchen, den Benutzernamen und das Passwort zu erraten. + +Und sie senden eine Anfrage mit dem Benutzernamen `johndoe` und dem Passwort `love123`. + +Dann würde der Python-Code in Ihrer Anwendung etwa so aussehen: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Aber genau in dem Moment, in dem Python das erste `j` in `johndoe` mit dem ersten `s` in `stanleyjobson` vergleicht, gibt es `False` zurück, da es bereits weiß, dass diese beiden Strings nicht identisch sind, und denkt, „Es besteht keine Notwendigkeit, weitere Berechnungen mit dem Vergleich der restlichen Buchstaben zu verschwenden“. Und Ihre Anwendung wird zurückgeben „Incorrect username or password“. + +Doch dann versuchen es die Angreifer mit dem Benutzernamen `stanleyjobsox` und dem Passwort `love123`. + +Und Ihr Anwendungscode macht etwa Folgendes: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Python muss das gesamte `stanleyjobso` in `stanleyjobsox` und `stanleyjobson` vergleichen, bevor es erkennt, dass beide Zeichenfolgen nicht gleich sind. Daher wird es einige zusätzliche Mikrosekunden dauern, bis die Antwort „Incorrect username or password“ erfolgt. + +#### Die Zeit zum Antworten hilft den Angreifern + +Wenn die Angreifer zu diesem Zeitpunkt feststellen, dass der Server einige Mikrosekunden länger braucht, um die Antwort „Incorrect username or password“ zu senden, wissen sie, dass sie _etwas_ richtig gemacht haben, einige der Anfangsbuchstaben waren richtig. + +Und dann können sie es noch einmal versuchen, wohl wissend, dass es wahrscheinlich eher etwas mit `stanleyjobsox` als mit `johndoe` zu tun hat. + +#### Ein „professioneller“ Angriff + +Natürlich würden die Angreifer das alles nicht von Hand versuchen, sondern ein Programm dafür schreiben, möglicherweise mit Tausenden oder Millionen Tests pro Sekunde. Und würden jeweils nur einen zusätzlichen richtigen Buchstaben erhalten. + +Aber so hätten die Angreifer in wenigen Minuten oder Stunden mit der „Hilfe“ unserer Anwendung den richtigen Benutzernamen und das richtige Passwort erraten, indem sie die Zeitspanne zur Hilfe nehmen, die diese zur Beantwortung benötigt. + +#### Das Problem beheben mittels `secrets.compare_digest()` + +Aber in unserem Code verwenden wir tatsächlich `secrets.compare_digest()`. + +Damit wird, kurz gesagt, der Vergleich von `stanleyjobsox` mit `stanleyjobson` genauso lange dauern wie der Vergleich von `johndoe` mit `stanleyjobson`. Und das Gleiche gilt für das Passwort. + +So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, vor dieser ganzen Klasse von Sicherheitsangriffen geschützt. + +### Den Error zurückgeben + +Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt: + +=== "Python 3.9+" + + ```Python hl_lines="26-30" + {!> ../../../docs_src/security/tutorial007_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="26-30" + {!> ../../../docs_src/security/tutorial007_an.py!} + ``` + +=== "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!} + ``` From c196794f24bd0dc33f045caad620ce4962be5d02 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:28:17 +0100 Subject: [PATCH 233/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20German=20transl?= =?UTF-8?q?ation=20for=20`docs/de/docs/index.md`=20(#10283)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/index.md | 479 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 479 insertions(+) create mode 100644 docs/de/docs/index.md diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md new file mode 100644 index 000000000..cf5a2b2d6 --- /dev/null +++ b/docs/de/docs/index.md @@ -0,0 +1,479 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + +<p align="center"> + <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> +</p> +<p align="center"> + <em>FastAPI Framework, hochperformant, leicht zu erlernen, schnell zu programmieren, einsatzbereit</em> +</p> +<p align="center"> +<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +</a> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +</a> +<a href="https://pypi.org/project/fastapi" target="_blank"> + <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package-Version"> +</a> +<a href="https://pypi.org/project/fastapi" target="_blank"> + <img src="https://img.shields.io/pypi/pyversions/fastapi.svg?color=%2334D058" alt="Unterstützte Python-Versionen"> +</a> +</p> + +--- + +**Dokumentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> + +**Quellcode**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> + +--- + +FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python 3.8+ auf Basis von Standard-Python-Typhinweisen. + +Seine Schlüssel-Merkmale sind: + +* **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (Dank Starlette und Pydantic). [Eines der schnellsten verfügbaren Python-Frameworks](#performanz). + +* **Schnell zu programmieren**: Erhöhen Sie die Geschwindigkeit bei der Entwicklung von Funktionen um etwa 200 % bis 300 %. * +* **Weniger Bugs**: Verringern Sie die von Menschen (Entwicklern) verursachten Fehler um etwa 40 %. * +* **Intuitiv**: Exzellente Editor-Unterstützung. <abbr title="auch bekannt als Autovervollständigung, Autocompletion, IntelliSense">Code-Vervollständigung</abbr> überall. Weniger Debuggen. +* **Einfach**: So konzipiert, dass es einfach zu benutzen und zu erlernen ist. Weniger Zeit für das Lesen der Dokumentation. +* **Kurz**: Minimieren Sie die Verdoppelung von Code. Mehrere Funktionen aus jeder Parameterdeklaration. Weniger Bugs. +* **Robust**: Erhalten Sie produktionsreifen Code. Mit automatischer, interaktiver Dokumentation. +* **Standards-basiert**: Basierend auf (und vollständig kompatibel mit) den offenen Standards für APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (früher bekannt als Swagger) und <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>. + +<small>* Schätzung auf Basis von Tests in einem internen Entwicklungsteam, das Produktionsanwendungen erstellt.</small> + +## Sponsoren + +<!-- sponsors --> + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor -%} +{%- for sponsor in sponsors.silver -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +<!-- /sponsors --> + +<a href="https://fastapi.tiangolo.com/de/fastapi-people/#sponsoren" class="external-link" target="_blank">Andere Sponsoren</a> + +## Meinungen + +„_[...] Ich verwende **FastAPI** heutzutage sehr oft. [...] Ich habe tatsächlich vor, es für alle **ML-Dienste meines Teams bei Microsoft** zu verwenden. Einige davon werden in das Kernprodukt **Windows** und einige **Office**-Produkte integriert._“ + +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(Ref)</small></a></div> + +--- + +„_Wir haben die **FastAPI**-Bibliothek genommen, um einen **REST**-Server zu erstellen, der abgefragt werden kann, um **Vorhersagen** zu erhalten. [für Ludwig]_“ + +<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, und Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(Ref)</small></a></div> + +--- + +„_**Netflix** freut sich, die Open-Source-Veröffentlichung unseres **Krisenmanagement**-Orchestrierung-Frameworks bekannt zu geben: **Dispatch**! [erstellt mit **FastAPI**]_“ + +<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(Ref)</small></a></div> + +--- + +„_Ich bin überglücklich mit **FastAPI**. Es macht so viel Spaß!_“ + +<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong>Host des <a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> Podcast</strong> <a href="https://twitter.com/brianokken/status/1112220079972728832" target="_blank"><small>(Ref)</small></a></div> + +--- + +„_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._“ + +<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong>Autor von <a href="https://www.hug.rest/" target="_blank">Hug</a></strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(Ref)</small></a></div> + +--- + +„_Wenn Sie ein **modernes Framework** zum Erstellen von REST-APIs erlernen möchten, schauen Sie sich **FastAPI** an. [...] Es ist schnell, einfach zu verwenden und leicht zu erlernen [...]_“ + +„_Wir haben zu **FastAPI** für unsere **APIs** gewechselt [...] Ich denke, es wird Ihnen gefallen [...]_“ + +<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong>Gründer von <a href="https://explosion.ai" target="_blank">Explosion AI</a> - Autoren von <a href="https://spacy.io" target="_blank">spaCy</a></strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(Ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(Ref)</small></a></div> + +--- + +„_Falls irgendjemand eine Produktions-Python-API erstellen möchte, kann ich **FastAPI** wärmstens empfehlen. Es ist **wunderschön konzipiert**, **einfach zu verwenden** und **hoch skalierbar**; es ist zu einer **Schlüsselkomponente** in unserer API-First-Entwicklungsstrategie geworden und treibt viele Automatisierungen und Dienste an, wie etwa unseren virtuellen TAC-Ingenieur._“ + +<div style="text-align: right; margin-right: 10%;">Deon Pillsbury - <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/" target="_blank"><small>(Ref)</small></a></div> + +--- + +## **Typer**, das FastAPI der CLIs + +<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a> + +Wenn Sie eine <abbr title="Command Line Interface – Kommandozeilen-Schnittstelle">CLI</abbr>-Anwendung für das Terminal erstellen, anstelle einer Web-API, schauen Sie sich <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a> an. + +**Typer** ist die kleine Schwester von FastAPI. Und es soll das **FastAPI der CLIs** sein. ⌨️ 🚀 + +## Anforderungen + +Python 3.8+ + +FastAPI steht auf den Schultern von Giganten: + +* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> für die Webanteile. +* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> für die Datenanteile. + +## Installation + +<div class="termy"> + +```console +$ pip install fastapi + +---> 100% +``` + +</div> + +Sie benötigen außerdem einen <abbr title="Asynchronous Server Gateway Interface – Asynchrone Server-Verbindungsschnittstelle">ASGI</abbr>-Server. Für die Produktumgebung beispielsweise <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oder <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. + +<div class="termy"> + +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +</div> + +## Beispiel + +### Erstellung + +* Erstellen Sie eine Datei `main.py` mit: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +<details markdown="1"> +<summary>Oder verwenden Sie <code>async def</code> ...</summary> + +Wenn Ihr Code `async` / `await` verwendet, benutzen Sie `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Anmerkung**: + +Wenn Sie das nicht kennen, schauen Sie sich den Abschnitt _„In Eile?“_ über <a href="https://fastapi.tiangolo.com/de/async/#in-eile" target="_blank">`async` und `await` in der Dokumentation</a> an. +</details> + +### Starten + +Führen Sie den Server aus: + +<div class="termy"> + +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +</div> + +<details markdown="1"> +<summary>Was macht der Befehl <code>uvicorn main:app --reload</code> ...</summary> + +Der Befehl `uvicorn main:app` bezieht sich auf: + +* `main`: die Datei `main.py` (das Python-„Modul“). +* `app`: das Objekt, das innerhalb von `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. +* `--reload`: lässt den Server nach Codeänderungen neu starten. Tun Sie das nur während der Entwicklung. + +</details> + +### Testen + +Öffnen Sie Ihren Browser unter <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>. + +Sie erhalten die JSON-Response: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Damit haben Sie bereits eine API erstellt, welche: + +* HTTP-Anfragen auf den _Pfaden_ `/` und `/items/{item_id}` entgegennimmt. +* Beide _Pfade_ erhalten `GET` <em>Operationen</em> (auch bekannt als HTTP _Methoden_). +* Der _Pfad_ `/items/{item_id}` hat einen _Pfadparameter_ `item_id`, der ein `int` sein sollte. +* Der _Pfad_ `/items/{item_id}` hat einen optionalen `str` _Query Parameter_ `q`. + +### Interaktive API-Dokumentation + +Gehen Sie nun auf <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Sie sehen die automatische interaktive API-Dokumentation (bereitgestellt von <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>): + + + +### Alternative API-Dokumentation + +Gehen Sie jetzt auf <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>. + +Sie sehen die alternative automatische Dokumentation (bereitgestellt von <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>): + + + +## Beispiel Aktualisierung + +Ändern Sie jetzt die Datei `main.py`, um den <abbr title="Body – Körper, Inhalt: Der eigentliche Inhalt einer Nachricht, nicht die Metadaten">Body</abbr> einer `PUT`-Anfrage zu empfangen. + +Deklarieren Sie den Body mithilfe von Standard-Python-Typen, dank Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +Der Server sollte automatisch neu geladen werden (weil Sie oben `--reload` zum Befehl `uvicorn` hinzugefügt haben). + +### Aktualisierung der interaktiven API-Dokumentation + +Gehen Sie jetzt auf <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +* Die interaktive API-Dokumentation wird automatisch aktualisiert, einschließlich des neuen Bodys: + + + +* Klicken Sie auf die Taste „Try it out“, damit können Sie die Parameter ausfüllen und direkt mit der API interagieren: + + + +* Klicken Sie dann auf die Taste „Execute“, die Benutzeroberfläche wird mit Ihrer API kommunizieren, sendet die Parameter, holt die Ergebnisse und zeigt sie auf dem Bildschirm an: + + + +### Aktualisierung der alternativen API-Dokumentation + +Und nun gehen Sie auf <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>. + +* Die alternative Dokumentation wird ebenfalls den neuen Abfrageparameter und -inhalt widerspiegeln: + + + +### Zusammenfassung + +Zusammengefasst deklarieren Sie **einmal** die Typen von Parametern, Body, etc. als Funktionsparameter. + +Das machen Sie mit modernen Standard-Python-Typen. + +Sie müssen keine neue Syntax, Methoden oder Klassen einer bestimmten Bibliothek usw. lernen. + +Nur Standard-**Python 3.8+**. + +Zum Beispiel für ein `int`: + +```Python +item_id: int +``` + +oder für ein komplexeres `Item`-Modell: + +```Python +item: Item +``` + +... und mit dieser einen Deklaration erhalten Sie: + +* Editor-Unterstützung, einschließlich: + * Code-Vervollständigung. + * Typprüfungen. +* Validierung von Daten: + * Automatische und eindeutige Fehler, wenn die Daten ungültig sind. + * Validierung auch für tief verschachtelte JSON-Objekte. +* <abbr title="auch bekannt als: Serialisierung, Parsen, Marshalling">Konvertierung</abbr> von Eingabedaten: Aus dem Netzwerk kommend, zu Python-Daten und -Typen. Lesen von: + * JSON. + * Pfad-Parametern. + * Abfrage-Parametern. + * Cookies. + * Header-Feldern. + * Formularen. + * Dateien. +* <abbr title="auch bekannt als: Serialisierung, Parsen, Marshalling">Konvertierung</abbr> von Ausgabedaten: Konvertierung von Python-Daten und -Typen zu Netzwerkdaten (als JSON): + * Konvertieren von Python-Typen (`str`, `int`, `float`, `bool`, `list`, usw.). + * `Datetime`-Objekte. + * `UUID`-Objekte. + * Datenbankmodelle. + * ... und viele mehr. +* Automatische interaktive API-Dokumentation, einschließlich 2 alternativer Benutzeroberflächen: + * Swagger UI. + * ReDoc. + +--- + +Um auf das vorherige Codebeispiel zurückzukommen, **FastAPI** wird: + +* Überprüfen, dass es eine `item_id` im Pfad für `GET`- und `PUT`-Anfragen gibt. +* Überprüfen, ob die `item_id` vom Typ `int` für `GET`- und `PUT`-Anfragen ist. + * Falls nicht, wird dem Client ein nützlicher, eindeutiger Fehler angezeigt. +* Prüfen, ob es einen optionalen Abfrageparameter namens `q` (wie in `http://127.0.0.1:8000/items/foo?q=somequery`) für `GET`-Anfragen gibt. + * Da der `q`-Parameter mit `= None` deklariert ist, ist er optional. + * Ohne das `None` wäre er erforderlich (wie der Body im Fall von `PUT`). +* Bei `PUT`-Anfragen an `/items/{item_id}` den Body als JSON lesen: + * Prüfen, ob er ein erforderliches Attribut `name` hat, das ein `str` sein muss. + * Prüfen, ob er ein erforderliches Attribut `price` hat, das ein `float` sein muss. + * Prüfen, ob er ein optionales Attribut `is_offer` hat, das ein `bool` sein muss, falls vorhanden. + * All dies würde auch für tief verschachtelte JSON-Objekte funktionieren. +* Automatisch von und nach JSON konvertieren. +* Alles mit OpenAPI dokumentieren, welches verwendet werden kann von: + * Interaktiven Dokumentationssystemen. + * Automatisch Client-Code generierenden Systemen für viele Sprachen. +* Zwei interaktive Dokumentation-Webschnittstellen direkt zur Verfügung stellen. + +--- + +Wir haben nur an der Oberfläche gekratzt, aber Sie bekommen schon eine Vorstellung davon, wie das Ganze funktioniert. + +Versuchen Sie, diese Zeile zu ändern: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +... von: + +```Python + ... "item_name": item.name ... +``` + +... zu: + +```Python + ... "item_price": item.price ... +``` + +... und sehen Sie, wie Ihr Editor die Attribute automatisch ausfüllt und ihre Typen kennt: + + + +Für ein vollständigeres Beispiel, mit weiteren Funktionen, siehe das <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - Benutzerhandbuch</a>. + +**Spoiler-Alarm**: Das Tutorial - Benutzerhandbuch enthält: + +* Deklaration von **Parametern** von anderen verschiedenen Stellen wie: **Header-Felder**, **Cookies**, **Formularfelder** und **Dateien**. +* Wie man **Validierungseinschränkungen** wie `maximum_length` oder `regex` setzt. +* Ein sehr leistungsfähiges und einfach zu bedienendes System für **<abbr title="Dependency Injection – Einbringen von Abhängigkeiten: Auch bekannt als Komponenten, Ressourcen, Provider, Services, Injectables">Dependency Injection</abbr>**. +* Sicherheit und Authentifizierung, einschließlich Unterstützung für **OAuth2** mit **JWT-Tokens** und **HTTP-Basic**-Authentifizierung. +* Fortgeschrittenere (aber ebenso einfache) Techniken zur Deklaration **tief verschachtelter JSON-Modelle** (dank Pydantic). +* **GraphQL** Integration mit <a href="https://strawberry.rocks" class="external-link" target="_blank">Strawberry</a> und anderen Bibliotheken. +* Viele zusätzliche Funktionen (dank Starlette) wie: + * **WebSockets** + * extrem einfache Tests auf Basis von `httpx` und `pytest` + * **CORS** + * **Cookie Sessions** + * ... und mehr. + +## Performanz + +Unabhängige TechEmpower-Benchmarks zeigen **FastAPI**-Anwendungen, die unter Uvicorn laufen, als <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">eines der schnellsten verfügbaren Python-Frameworks</a>, nur noch hinter Starlette und Uvicorn selbst (intern von FastAPI verwendet). + +Um mehr darüber zu erfahren, siehe den Abschnitt <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>. + +## Optionale Abhängigkeiten + +Wird von Pydantic verwendet: + +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - für E-Mail-Validierung. +* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - für die Verwaltung von Einstellungen. +* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - für zusätzliche Typen, mit Pydantic zu verwenden. + +Wird von Starlette verwendet: + +* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - erforderlich, wenn Sie den `TestClient` verwenden möchten. +* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - erforderlich, wenn Sie die Standardkonfiguration für Templates verwenden möchten. +* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - erforderlich, wenn Sie Formulare mittels `request.form()` <abbr title="Konvertieren des Strings, der aus einer HTTP-Anfrage stammt, nach Python-Daten">„parsen“</abbr> möchten. +* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - erforderlich für `SessionMiddleware` Unterstützung. +* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - erforderlich für Starlette's `SchemaGenerator` Unterstützung (Sie brauchen das wahrscheinlich nicht mit FastAPI). +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - erforderlich, wenn Sie `UJSONResponse` verwenden möchten. + +Wird von FastAPI / Starlette verwendet: + +* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - für den Server, der Ihre Anwendung lädt und serviert. +* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - erforderlich, wenn Sie `ORJSONResponse` verwenden möchten. + +Sie können diese alle mit `pip install "fastapi[all]"` installieren. + +## Lizenz + +Dieses Projekt ist unter den Bedingungen der MIT-Lizenz lizenziert. From 6e47b3256edd7627e0e934d7a3199fef52ae8736 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:28:29 +0100 Subject: [PATCH 234/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/handling-errors.md`=20(#10379?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/handling-errors.md | 259 +++++++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 docs/de/docs/tutorial/handling-errors.md diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..af658b971 --- /dev/null +++ b/docs/de/docs/tutorial/handling-errors.md @@ -0,0 +1,259 @@ +# Fehlerbehandlung + +Es gibt viele Situationen, in denen Sie einem Client, der Ihre API benutzt, einen Fehler zurückgeben müssen. + +Dieser Client könnte ein Browser mit einem Frontend, Code von jemand anderem, ein <abbr title="Internet of Things – Internet der Dinge: Geräte, die über das Internet Informationen austauschen">IoT</abbr>-Gerät, usw., sein. + +Sie müssten beispielsweise einem Client sagen: + +* Dass er nicht die notwendigen Berechtigungen hat, eine Aktion auszuführen. +* Dass er zu einer Ressource keinen Zugriff hat. +* Dass die Ressource, auf die er zugreifen möchte, nicht existiert. +* usw. + +In diesen Fällen geben Sie normalerweise einen **HTTP-Statuscode** im Bereich **400** (400 bis 499) zurück. + +Das ist vergleichbar mit den HTTP-Statuscodes im Bereich 200 (von 200 bis 299). Diese „200“er Statuscodes bedeuten, dass der Request in einem bestimmten Aspekt ein „Success“ („Erfolg“) war. + +Die Statuscodes im 400er-Bereich bedeuten hingegen, dass es einen Fehler gab. + +Erinnern Sie sich an all diese **404 Not Found** Fehler (und Witze)? + +## `HTTPException` verwenden + +Um HTTP-Responses mit Fehlern zum Client zurückzugeben, verwenden Sie `HTTPException`. + +### `HTTPException` importieren + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### Eine `HTTPException` in Ihrem Code auslösen + +`HTTPException` ist eine normale Python-<abbr title="Exception – Ausnahme, Fehler: Python-Objekt, das einen Fehler nebst Metadaten repräsentiert">Exception</abbr> mit einigen zusätzlichen Daten, die für APIs relevant sind. + +Weil es eine Python-Exception ist, geben Sie sie nicht zurück, (`return`), sondern Sie lösen sie aus (`raise`). + +Das bedeutet auch, wenn Sie in einer Hilfsfunktion sind, die Sie von ihrer *Pfadoperation-Funktion* aus aufrufen, und Sie lösen eine `HTTPException` von innerhalb dieser Hilfsfunktion aus, dann wird der Rest der *Pfadoperation-Funktion* nicht ausgeführt, sondern der Request wird sofort abgebrochen und der HTTP-Error der `HTTP-Exception` wird zum Client gesendet. + +Der Vorteil, eine Exception auszulösen (`raise`), statt sie zurückzugeben (`return`) wird im Abschnitt über Abhängigkeiten und Sicherheit klarer werden. + +Im folgenden Beispiel lösen wir, wenn der Client eine ID anfragt, die nicht existiert, eine Exception mit dem Statuscode `404` aus. + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### Die resultierende Response + +Wenn der Client `http://example.com/items/foo` anfragt (ein `item_id` `"foo"`), erhält dieser Client einen HTTP-Statuscode 200 und folgende JSON-Response: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existierendes `item_id` `"bar"`), erhält er einen HTTP-Statuscode 404 (der „Not Found“-Fehler), und eine JSON-Response wie folgt: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! 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`. + + Zum Beispiel ein `dict`, eine `list`, usw. + + Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert. + +## Benutzerdefinierte Header hinzufügen + +Es gibt Situationen, da ist es nützlich, dem HTTP-Error benutzerdefinierte Header hinzufügen zu können, etwa in einigen Sicherheitsszenarien. + +Sie müssen das wahrscheinlich nicht direkt in ihrem Code verwenden. + +Aber falls es in einem fortgeschrittenen Szenario notwendig ist, können Sie benutzerdefinierte Header wie folgt hinzufügen: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## Benutzerdefinierte Exceptionhandler definieren + +Sie können benutzerdefinierte <abbr title="Exceptionhandler – Ausnahmebehandler: Funktion, die sich um die Bearbeitung einer Exception kümmert">Exceptionhandler</abbr> hinzufügen, mithilfe <a href="https://www.starlette.io/exceptions/" class="external-link" target="_blank">derselben Werkzeuge für Exceptions von Starlette</a>. + +Nehmen wir an, Sie haben eine benutzerdefinierte Exception `UnicornException`, die Sie (oder eine Bibliothek, die Sie verwenden) `raise`n könnten. + +Und Sie möchten diese Exception global mit FastAPI handhaben. + +Sie könnten einen benutzerdefinierten Exceptionhandler mittels `@app.exception_handler()` hinzufügen: + +```Python hl_lines="5-7 13-18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +Wenn Sie nun `/unicorns/yolo` anfragen, `raise`d die *Pfadoperation* eine `UnicornException`. + +Aber diese wird von `unicorn_exception_handler` gehandhabt. + +Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-Inhalt: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`. + +## Die Default-Exceptionhandler überschreiben + +**FastAPI** hat einige Default-Exceptionhandler. + +Diese Handler kümmern sich darum, Default-JSON-Responses zurückzugeben, wenn Sie eine `HTTPException` `raise`n, und wenn der Request ungültige Daten enthält. + +Sie können diese Exceptionhandler mit ihren eigenen überschreiben. + +### Requestvalidierung-Exceptions überschreiben + +Wenn ein Request ungültige Daten enthält, löst **FastAPI** intern einen `RequestValidationError` aus. + +Und bietet auch einen Default-Exceptionhandler dafür. + +Um diesen zu überschreiben, importieren Sie den `RequestValidationError` und verwenden Sie ihn in `@app.exception_handler(RequestValidationError)`, um Ihren Exceptionhandler zu dekorieren. + +Der Exceptionhandler wird einen `Request` und die Exception entgegennehmen. + +```Python hl_lines="2 14-16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +Wenn Sie nun `/items/foo` besuchen, erhalten Sie statt des Default-JSON-Errors: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +eine Textversion: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` vs. `ValidationError` + +!!! warning "Achtung" + Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. + +`RequestValidationError` ist eine Unterklasse von Pydantics <a href="https://pydantic-docs.helpmanual.io/usage/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. + +**FastAPI** verwendet diesen, sodass Sie, wenn Sie ein Pydantic-Modell für `response_model` verwenden, und ihre Daten fehlerhaft sind, einen Fehler in ihrem Log sehen. + +Aber der Client/Benutzer sieht ihn nicht. Stattdessen erhält der Client einen <abbr title="Interner Server-Fehler">„Internal Server Error“</abbr> mit einem HTTP-Statuscode `500`. + +Das ist, wie es sein sollte, denn wenn Sie einen Pydantic-`ValidationError` in Ihrer *Response* oder irgendwo sonst in ihrem Code haben (es sei denn, im *Request* des Clients), ist das tatsächlich ein Bug in ihrem Code. + +Und während Sie den Fehler beheben, sollten ihre Clients/Benutzer keinen Zugriff auf interne Informationen über den Fehler haben, da das eine Sicherheitslücke aufdecken könnte. + +### den `HTTPException`-Handler überschreiben + +Genauso können Sie den `HTTPException`-Handler überschreiben. + +Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zurückgeben wollen: + +```Python hl_lines="3-4 9-11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "Technische Details" + Sie können auch `from starlette.responses import PlainTextResponse` verwenden. + + **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +### Den `RequestValidationError`-Body verwenden + +Der `RequestValidationError` enthält den empfangenen `body` mit den ungültigen Daten. + +Sie könnten diesen verwenden, während Sie Ihre Anwendung entwickeln, um den Body zu loggen und zu debuggen, ihn zum Benutzer zurückzugeben, usw. + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial005.py!} +``` + +Jetzt versuchen Sie, einen ungültigen Artikel zu senden: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Sie erhalten eine Response, die Ihnen sagt, dass die Daten ungültig sind, und welche den empfangenen Body enthält. + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIs `HTTPException` vs. Starlettes `HTTPException` + +**FastAPI** hat seine eigene `HTTPException`. + +Und **FastAPI**s `HTTPException`-Fehlerklasse erbt von Starlettes `HTTPException`-Fehlerklasse. + +Der einzige Unterschied besteht darin, dass **FastAPIs** `HTTPException` alles für das Feld `detail` akzeptiert, was nach JSON konvertiert werden kann, während Starlettes `HTTPException` nur Strings zulässt. + +Sie können also weiterhin **FastAPI**s `HTTPException` wie üblich in Ihrem Code auslösen. + +Aber wenn Sie einen Exceptionhandler registrieren, registrieren Sie ihn für Starlettes `HTTPException`. + +Auf diese Weise wird Ihr Handler, wenn irgendein Teil von Starlettes internem Code, oder eine Starlette-Erweiterung, oder -Plugin eine Starlette-`HTTPException` auslöst, in der Lage sein, diese zu fangen und zu handhaben. + +Damit wir in diesem Beispiel beide `HTTPException`s im selben Code haben können, benennen wir Starlettes Exception um zu `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI**s Exceptionhandler wiederverwenden + +Wenn Sie die Exception zusammen mit denselben Default-Exceptionhandlern von **FastAPI** verwenden möchten, können Sie die Default-Exceptionhandler von `fastapi.Exception_handlers` importieren und wiederverwenden: + +```Python hl_lines="2-5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +In diesem Beispiel `print`en Sie nur den Fehler mit einer sehr ausdrucksstarken Nachricht, aber Sie sehen, worauf wir hinauswollen. Sie können mit der Exception etwas machen und dann einfach die Default-Exceptionhandler wiederverwenden. From ffabc36cafa59031b023ca30056c503538d5f10a Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:28:59 +0100 Subject: [PATCH 235/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/path-params.md`=20(#10290)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Georg Wicke-Arndt <g.wicke-arndt@outlook.com> --- docs/de/docs/tutorial/path-params.md | 254 +++++++++++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 docs/de/docs/tutorial/path-params.md diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md new file mode 100644 index 000000000..8c8f2e008 --- /dev/null +++ b/docs/de/docs/tutorial/path-params.md @@ -0,0 +1,254 @@ +# Pfad-Parameter + +Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-<abbr title="Format-String – Formatierter String: Der String enthält Variablen, die mit geschweiften Klammern umschlossen sind. Solche Stellen werden durch den Wert der Variable ersetzt">Format-Strings</abbr> verwendet wird: + +```Python hl_lines="6-7" +{!../../../docs_src/path_params/tutorial001.py!} +``` + +Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben. + +Wenn Sie dieses Beispiel ausführen und auf <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a> gehen, sehen Sie als Response: + +```JSON +{"item_id":"foo"} +``` + +## Pfad-Parameter mit Typen + +Sie können den Typ eines Pfad-Parameters in der Argumentliste der Funktion deklarieren, mit Standard-Python-Typannotationen: + +```Python hl_lines="7" +{!../../../docs_src/path_params/tutorial002.py!} +``` + +In diesem Fall wird `item_id` als `int` deklariert, also als Ganzzahl. + +!!! check + Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw. + +## Daten-<abbr title="Auch bekannt als: Serialisierung, Parsen, Marshalling">Konversion</abbr> + +Wenn Sie dieses Beispiel ausführen und Ihren Browser unter <a href="http://127.0.0.1:8000/items/3" class="external-link" target="_blank">http://127.0.0.1:8000/items/3</a> öffnen, sehen Sie als Response: + +```JSON +{"item_id":3} +``` + +!!! check + Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String `"3"`, also ein `str`. + + Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch <abbr title="Den String, der von einer HTTP Anfrage kommt, in Python-Objekte konvertieren">„parsen“</abbr>. + +## Datenvalidierung + +Wenn Sie aber im Browser <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a> besuchen, erhalten Sie eine hübsche HTTP-Fehlermeldung: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` + +Der Pfad-Parameter `item_id` hatte den Wert `"foo"`, was kein `int` ist. + +Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> + +!!! check + Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung. + + Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war. + + Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert. + +## Dokumentation + +Wenn Sie die Seite <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> in Ihrem Browser öffnen, sehen Sie eine automatische, interaktive API-Dokumentation: + +<img src="/img/tutorial/path-params/image01.png"> + +!!! check + Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche). + + Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist. + +## Nützliche Standards. Alternative Dokumentation + +Und weil das generierte Schema vom <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md" class="external-link" target="_blank">OpenAPI</a>-Standard kommt, gibt es viele kompatible Tools. + +Zum Beispiel bietet **FastAPI** selbst eine alternative API-Dokumentation (verwendet ReDoc), welche Sie unter <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a> einsehen können: + +<img src="/img/tutorial/path-params/image02.png"> + +Und viele weitere kompatible Tools. Inklusive Codegenerierung für viele Sprachen. + +## Pydantic + +Die ganze Datenvalidierung wird hinter den Kulissen von <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> durchgeführt, Sie profitieren also von dessen Vorteilen. Und Sie wissen, dass Sie in guten Händen sind. + +Sie können für Typ Deklarationen auch `str`, `float`, `bool` und viele andere komplexe Datentypen verwenden. + +Mehrere davon werden wir in den nächsten Kapiteln erkunden. + +## Die Reihenfolge ist wichtig + +Wenn Sie *Pfadoperationen* erstellen, haben Sie manchmal einen fixen Pfad. + +Etwa `/users/me`, um Daten über den aktuellen Benutzer zu erhalten. + +Und Sie haben auch einen Pfad `/users/{user_id}`, um Daten über einen spezifischen Benutzer zu erhalten, mittels einer Benutzer-ID. + +Weil *Pfadoperationen* in ihrer Reihenfolge ausgewertet werden, müssen Sie sicherstellen, dass der Pfad `/users/me` vor `/users/{user_id}` deklariert wurde: + +```Python hl_lines="6 11" +{!../../../docs_src/path_params/tutorial003.py!} +``` + +Ansonsten würde der Pfad für `/users/{user_id}` auch `/users/me` auswerten, und annehmen, dass ein Parameter `user_id` mit dem Wert `"me"` übergeben wurde. + +Sie können eine Pfadoperation auch nicht erneut definieren: + +```Python hl_lines="6 11" +{!../../../docs_src/path_params/tutorial003b.py!} +``` + +Die erste Definition wird immer verwendet werden, da ihr Pfad zuerst übereinstimmt. + +## Vordefinierte Parameterwerte + +Wenn Sie eine *Pfadoperation* haben, welche einen *Pfad-Parameter* hat, aber Sie wollen, dass dessen gültige Werte vordefiniert sind, können Sie ein Standard-Python <abbr title="Enumeration, oder kurz Enum – Aufzählung">`Enum`</abbr> verwenden. + +### Erstellen Sie eine `Enum`-Klasse + +Importieren Sie `Enum` und erstellen Sie eine Unterklasse, die von `str` und `Enum` erbt. + +Indem Sie von `str` erben, weiß die API Dokumentation, dass die Werte des Enums vom Typ `str` sein müssen, und wird in der Lage sein, korrekt zu rendern. + +Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaubten Werte sein werden: + +```Python hl_lines="1 6-9" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +!!! info + <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerationen (oder kurz Enums)</a> gibt es in Python seit Version 3.4. + +!!! tip "Tipp" + Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von <abbr title="Genau genommen, Deep-Learning-Modellarchitekturen">Modellen</abbr> für maschinelles Lernen. + +### Deklarieren Sie einen *Pfad-Parameter* + +Dann erstellen Sie einen *Pfad-Parameter*, der als Typ die gerade erstellte Enum-Klasse hat (`ModelName`): + +```Python hl_lines="16" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +### Testen Sie es in der API-Dokumentation + +Weil die erlaubten Werte für den *Pfad-Parameter* nun vordefiniert sind, kann die interaktive Dokumentation sie als Auswahl-Drop-Down anzeigen: + +<img src="/img/tutorial/path-params/image03.png"> + +### Mit Python-*<abbr title="Enumeration – Aufzählung">Enums</abbr>* arbeiten + +Der *Pfad-Parameter* wird ein *<abbr title="Member – Mitglied: Einer der möglichen Werte einer Enumeration">Member</abbr> eines Enums* sein. + +#### *Enum-Member* vergleichen + +Sie können ihn mit einem Member Ihres Enums `ModelName` vergleichen: + +```Python hl_lines="17" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +#### *Enum-Wert* erhalten + +Den tatsächlichen Wert (in diesem Fall ein `str`) erhalten Sie via `model_name.value`, oder generell, `ihr_enum_member.value`: + +```Python hl_lines="20" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +!!! tip "Tipp" + Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. + +#### *Enum-Member* zurückgeben + +Sie können *Enum-Member* in ihrer *Pfadoperation* zurückgeben, sogar verschachtelt in einem JSON-Body (z. B. als `dict`). + +Diese werden zu ihren entsprechenden Werten konvertiert (in diesem Fall Strings), bevor sie zum Client übertragen werden: + +```Python hl_lines="18 21 23" +{!../../../docs_src/path_params/tutorial005.py!} +``` + +In Ihrem Client erhalten Sie eine JSON-Response, wie etwa: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Pfad Parameter die Pfade enthalten + +Angenommen, Sie haben eine *Pfadoperation* mit einem Pfad `/files/{file_path}`. + +Aber `file_path` soll selbst einen *Pfad* enthalten, etwa `home/johndoe/myfile.txt`. + +Sprich, die URL für diese Datei wäre etwas wie: `/files/home/johndoe/myfile.txt`. + +### OpenAPI Unterstützung + +OpenAPI bietet nicht die Möglichkeit, dass ein *Pfad-Parameter* seinerseits einen *Pfad* enthalten kann, das würde zu Szenarios führen, die schwierig zu testen und zu definieren sind. + +Trotzdem können Sie das in **FastAPI** tun, indem Sie eines der internen Tools von Starlette verwenden. + +Die Dokumentation würde weiterhin funktionieren, allerdings wird nicht dokumentiert werden, dass der Parameter ein Pfad sein sollte. + +### Pfad Konverter + +Mittels einer Option direkt von Starlette können Sie einen *Pfad-Parameter* deklarieren, der einen Pfad enthalten soll, indem Sie eine URL wie folgt definieren: + +``` +/files/{file_path:path} +``` + +In diesem Fall ist der Name des Parameters `file_path`. Der letzte Teil, `:path`, sagt aus, dass der Parameter ein *Pfad* sein soll. + +Sie verwenden das also wie folgt: + +```Python hl_lines="6" +{!../../../docs_src/path_params/tutorial004.py!} +``` + +!!! tip "Tipp" + Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. + + In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`. + +## Zusammenfassung + +In **FastAPI** erhalten Sie mittels kurzer, intuitiver Typdeklarationen: + +* Editor-Unterstützung: Fehlerprüfungen, Codevervollständigung, usw. +* Daten "<abbr title="Den String, der von einer HTTP Anfrage kommt, nach Python-Daten konvertieren">parsen</abbr>" +* Datenvalidierung +* API-Annotationen und automatische Dokumentation + +Und Sie müssen sie nur einmal deklarieren. + +Das ist wahrscheinlich der sichtbarste Unterschied zwischen **FastAPI** und alternativen Frameworks (abgesehen von der reinen Performanz). From b2835136a6586657bad79b7f8e95b6cb42472ee4 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:29:25 +0100 Subject: [PATCH 236/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20German=20transl?= =?UTF-8?q?ation=20for=20`docs/de/docs/python-types.md`=20(#10287)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/python-types.md | 537 +++++++++++++++++++++++++++++++++++ 1 file changed, 537 insertions(+) create mode 100644 docs/de/docs/python-types.md diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md new file mode 100644 index 000000000..d11a193dd --- /dev/null +++ b/docs/de/docs/python-types.md @@ -0,0 +1,537 @@ +# Einführung in Python-Typen + +Python hat Unterstützung für optionale „Typhinweise“ (Englisch: „Type Hints“). Auch „Typ Annotationen“ genannt. + +Diese **„Typhinweise“** oder -Annotationen sind eine spezielle Syntax, die es erlaubt, den <abbr title="Zum Beispiel: str, int, float, bool">Typ</abbr> einer Variablen zu deklarieren. + +Durch das Deklarieren von Typen für Ihre Variablen können Editoren und Tools bessere Unterstützung bieten. + +Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typhinweise. Sie deckt nur das Minimum ab, das nötig ist, um diese mit **FastAPI** zu verwenden ... was tatsächlich sehr wenig ist. + +**FastAPI** basiert vollständig auf diesen Typhinweisen, sie geben der Anwendung viele Vorteile und Möglichkeiten. + +Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen. + +!!! note "Hinweis" + Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +## Motivation + +Fangen wir mit einem einfachen Beispiel an: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +Dieses Programm gibt aus: + +``` +John Doe +``` + +Die Funktion macht Folgendes: + +* Nimmt einen `first_name` und `last_name`. +* Schreibt den ersten Buchstaben eines jeden Wortes groß, mithilfe von `title()`. +* <abbr title="Füge zu einer Einheit zusammen, eins nach dem anderen.">Verkettet</abbr> sie mit einem Leerzeichen in der Mitte. + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### Bearbeiten Sie es + +Es ist ein sehr einfaches Programm. + +Aber nun stellen Sie sich vor, Sie würden es selbst schreiben. + +Irgendwann sind die Funktions-Parameter fertig, Sie starten mit der Definition des Körpers ... + +Aber dann müssen Sie „diese Methode aufrufen, die den ersten Buchstaben in Großbuchstaben umwandelt“. + +War es `upper`? War es `uppercase`? `first_uppercase`? `capitalize`? + +Dann versuchen Sie es mit dem langjährigen Freund des Programmierers, der Editor-Autovervollständigung. + +Sie geben den ersten Parameter der Funktion ein, `first_name`, dann einen Punkt (`.`) und drücken `Strg+Leertaste`, um die Vervollständigung auszulösen. + +Aber leider erhalten Sie nichts Nützliches: + +<img src="/img/python-types/image01.png"> + +### Typen hinzufügen + +Lassen Sie uns eine einzelne Zeile aus der vorherigen Version ändern. + +Wir ändern den folgenden Teil, die Parameter der Funktion, von: + +```Python + first_name, last_name +``` + +zu: + +```Python + first_name: str, last_name: str +``` + +Das war's. + +Das sind die „Typhinweise“: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist: + +```Python + first_name="john", last_name="doe" +``` + +Das ist eine andere Sache. + +Wir verwenden Doppelpunkte (`:`), nicht Gleichheitszeichen (`=`). + +Und das Hinzufügen von Typhinweisen ändert normalerweise nichts an dem, was ohne sie passieren würde. + +Aber jetzt stellen Sie sich vor, Sie sind wieder mitten in der Erstellung dieser Funktion, aber mit Typhinweisen. + +An derselben Stelle versuchen Sie, die Autovervollständigung mit „Strg+Leertaste“ auszulösen, und Sie sehen: + +<img src="/img/python-types/image02.png"> + +Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der es „Klick“ macht: + +<img src="/img/python-types/image03.png"> + +## Mehr Motivation + +Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung: + +<img src="/img/python-types/image04.png"> + +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!} +``` + +## Deklarieren von Typen + +Sie haben gerade den Haupt-Einsatzort für die Deklaration von Typhinweisen gesehen. Als Funktionsparameter. + +Das ist auch meistens, wie sie in **FastAPI** verwendet werden. + +### Einfache Typen + +Sie können alle Standard-Python-Typen deklarieren, nicht nur `str`. + +Zum Beispiel diese: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### Generische Typen mit Typ-Parametern + +Es gibt Datenstrukturen, die andere Werte enthalten können, wie etwa `dict`, `list`, `set` und `tuple`. Die inneren Werte können auch ihren eigenen Typ haben. + +Diese Typen mit inneren Typen werden „**generische**“ Typen genannt. Es ist möglich, sie mit ihren inneren Typen zu deklarieren. + +Um diese Typen und die inneren Typen zu deklarieren, können Sie Pythons Standardmodul `typing` verwenden. Es existiert speziell für die Unterstützung dieser Typhinweise. + +#### Neuere Python-Versionen + +Die Syntax, welche `typing` verwendet, ist **kompatibel** mit allen Versionen, von Python 3.6 aufwärts zu den neuesten, inklusive Python 3.9, Python 3.10, usw. + +Mit der Weiterentwicklung von Python kommen **neuere Versionen** heraus, mit verbesserter Unterstützung für Typannotationen, und in vielen Fällen müssen Sie gar nicht mehr das `typing`-Modul importieren, um Typannotationen zu schreiben. + +Wenn Sie eine neuere Python-Version für Ihr Projekt wählen können, werden Sie aus dieser zusätzlichen Vereinfachung Nutzen ziehen können. + +In der gesamten Dokumentation gibt es Beispiele, welche kompatibel mit unterschiedlichen Python-Versionen sind (wenn es Unterschiede gibt). + +Zum Beispiel bedeutet „**Python 3.6+**“, dass das Beispiel kompatibel mit Python 3.6 oder höher ist (inklusive 3.7, 3.8, 3.9, 3.10, usw.). Und „**Python 3.9+**“ bedeutet, es ist kompatibel mit Python 3.9 oder höher (inklusive 3.10, usw.). + +Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die Beispiele für die neueste Version, diese werden die **beste und einfachste Syntax** haben, zum Beispiel, „**Python 3.10+**“. + +#### Liste + +Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll. + +=== "Python 3.9+" + + Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). + + Als Typ nehmen Sie `list`. + + Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006_py39.py!} + ``` + +=== "Python 3.8+" + + Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + + Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). + + Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. + + Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + + ```Python hl_lines="4" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + +!!! tip "Tipp" + Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. + + In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber). + +Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`. + +!!! tip "Tipp" + Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. + +Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen: + +<img src="/img/python-types/image05.png"> + +Ohne Typen ist das fast unmöglich zu erreichen. + +Beachten Sie, dass die Variable `item` eines der Elemente in der Liste `items` ist. + +Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet entsprechende Unterstützung. + +#### Tupel und Menge + +Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`: + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial007_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial007.py!} + ``` + +Das bedeutet: + +* Die Variable `items_t` ist ein `tuple` mit 3 Elementen, einem `int`, einem weiteren `int` und einem `str`. +* Die Variable `items_s` ist ein `set`, und jedes seiner Elemente ist vom Typ `bytes`. + +#### Dict + +Um ein `dict` zu definieren, übergeben Sie zwei Typ-Parameter, getrennt durch Kommas. + +Der erste Typ-Parameter ist für die Schlüssel des `dict`. + +Der zweite Typ-Parameter ist für die Werte des `dict`: + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008.py!} + ``` + +Das bedeutet: + +* Die Variable `prices` ist ein `dict`: + * Die Schlüssel dieses `dict` sind vom Typ `str` (z. B. die Namen der einzelnen Artikel). + * Die Werte dieses `dict` sind vom Typ `float` (z. B. der Preis jedes Artikels). + +#### <abbr title="Union – Verbund, Einheit‚ Vereinigung: Eines von Mehreren">Union</abbr> + +Sie können deklarieren, dass eine Variable einer von **verschiedenen Typen** sein kann, zum Beispiel ein `int` oder ein `str`. + +In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von `typing` verwenden und die möglichen Typen innerhalb der eckigen Klammern auflisten. + +In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> aufzulisten. + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008b_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008b.py!} + ``` + +In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann. + +#### Vielleicht `None` + +Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` sein kann. + +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!} +``` + +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. + +`Optional[Something]` ist tatsächlich eine Abkürzung für `Union[Something, None]`, diese beiden sind äquivalent. + +Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial009_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009.py!} + ``` + +=== "Python 3.8+ Alternative" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009b.py!} + ``` + +#### `Union` oder `Optional` verwenden? + +Wenn Sie eine Python-Version unterhalb 3.10 verwenden, hier ist mein sehr **subjektiver** Standpunkt dazu: + +* 🚨 Vermeiden Sie `Optional[SomeType]` +* Stattdessen ✨ **verwenden Sie `Union[SomeType, None]`** ✨. + +Beide sind äquivalent und im Hintergrund dasselbe, aber ich empfehle `Union` statt `Optional`, weil das Wort „**optional**“ impliziert, dass dieser Wert, zum Beispiel als Funktionsparameter, optional ist. Tatsächlich bedeutet es aber nur „Der Wert kann `None` sein“, selbst wenn der Wert nicht optional ist und benötigt wird. + +Ich denke, `Union[SomeType, None]` ist expliziter bezüglich seiner Bedeutung. + +Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie und Ihre Teamkollegen über den Code denken. + +Nehmen wir zum Beispiel diese Funktion: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c.py!} +``` + +Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen: + +```Python +say_hi() # Oh, nein, das löst einen Fehler aus! 😱 +``` + +Der `name` Parameter wird **immer noch benötigt** (nicht *optional*), weil er keinen Default-Wert hat. `name` akzeptiert aber dennoch `None` als Wert: + +```Python +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!} +``` + +Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎 + +#### Generische Typen + +Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt. + +=== "Python 3.10+" + + Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + + * `list` + * `tuple` + * `set` + * `dict` + + Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: + + * `Union` + * `Optional` (so wie unter Python 3.8) + * ... und andere. + + In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher. + +=== "Python 3.9+" + + Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + + * `list` + * `tuple` + * `set` + * `dict` + + Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: + + * `Union` + * `Optional` + * ... und andere. + +=== "Python 3.8+" + + * `List` + * `Tuple` + * `Set` + * `Dict` + * `Union` + * `Optional` + * ... und andere. + +### Klassen als Typen + +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!} +``` + +Dann können Sie eine Variable vom Typ `Person` deklarieren: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Und wiederum bekommen Sie die volle Editor-Unterstützung: + +<img src="/img/python-types/image06.png"> + +Beachten Sie, das bedeutet: „`one_person` ist eine **Instanz** der Klasse `Person`“. + +Es bedeutet nicht: „`one_person` ist die **Klasse** genannt `Person`“. + +## Pydantic Modelle + +<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> ist eine Python-Bibliothek für die Validierung von Daten. + +Sie deklarieren die „Form“ der Daten als Klassen mit Attributen. + +Und jedes Attribut hat einen Typ. + +Dann erzeugen Sie eine Instanz dieser Klasse mit einigen Werten, und Pydantic validiert die Werte, konvertiert sie in den passenden Typ (falls notwendig) und gibt Ihnen ein Objekt mit allen Daten. + +Und Sie erhalten volle Editor-Unterstützung für dieses Objekt. + +Ein Beispiel aus der offiziellen Pydantic Dokumentation: + +=== "Python 3.10+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011.py!} + ``` + +!!! info + Um mehr über <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an</a>. + +**FastAPI** basiert vollständig auf Pydantic. + +Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank} sehen. + +!!! tip "Tipp" + Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> mehr erfahren. + +## Typhinweise mit Metadaten-Annotationen + +Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`. + +=== "Python 3.9+" + + In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013_py39.py!} + ``` + +=== "Python 3.8+" + + In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`. + + Es wird bereits mit **FastAPI** installiert sein. + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013.py!} + ``` + +Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`. + +Aber Sie können `Annotated` nutzen, um **FastAPI** mit Metadaten zu versorgen, die ihm sagen, wie sich ihre Anwendung verhalten soll. + +Wichtig ist, dass **der erste *Typ-Parameter***, den Sie `Annotated` übergeben, der **tatsächliche Typ** ist. Der Rest sind Metadaten für andere Tools. + +Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standard-Python ist. 😎 + +Später werden Sie sehen, wie **mächtig** es sein kann. + +!!! tip "Tipp" + Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ + + Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀 + +## Typhinweise in **FastAPI** + +**FastAPI** macht sich diese Typhinweise zunutze, um mehrere Dinge zu tun. + +Mit **FastAPI** deklarieren Sie Parameter mit Typhinweisen, und Sie erhalten: + +* **Editorunterstützung**. +* **Typ-Prüfungen**. + +... und **FastAPI** verwendet dieselben Deklarationen, um: + +* **Anforderungen** zu definieren: aus Anfrage-Pfadparametern, Abfrageparametern, Header-Feldern, Bodys, Abhängigkeiten, usw. +* **Daten umzuwandeln**: aus der Anfrage in den erforderlichen Typ. +* **Daten zu validieren**: aus jeder Anfrage: + * **Automatische Fehler** generieren, die an den Client zurückgegeben werden, wenn die Daten ungültig sind. +* Die API mit OpenAPI zu **dokumentieren**: + * Die dann von den Benutzeroberflächen der automatisch generierten interaktiven Dokumentation verwendet wird. + +Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das in Aktion sehen im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank}. + +Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt. + +!!! info + Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">der „Cheat Sheet“ von `mypy`</a>. From 36dca65339b40b5ad911251172a1915aa0496c6b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 20:29:38 +0000 Subject: [PATCH 237/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 00cf21f45..7d5d525cb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update German translation for `docs/de/docs/features.md`. PR [#10284](https://github.com/tiangolo/fastapi/pull/10284) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/server-workers.md`. PR [#10747](https://github.com/tiangolo/fastapi/pull/10747) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/docker.md`. PR [#10759](https://github.com/tiangolo/fastapi/pull/10759) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/how-to/index.md`. PR [#10769](https://github.com/tiangolo/fastapi/pull/10769) by [@nilslindemann](https://github.com/nilslindemann). From cd19ede25e9c8b4fa7ca2bd7be08a84e139a5d27 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:29:57 +0100 Subject: [PATCH 238/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/help-fastapi.md`=20(#10455)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/help-fastapi.md | 262 +++++++++++++++++++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 docs/de/docs/help-fastapi.md diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md new file mode 100644 index 000000000..bdc07e55f --- /dev/null +++ b/docs/de/docs/help-fastapi.md @@ -0,0 +1,262 @@ +# FastAPI helfen – Hilfe erhalten + +Gefällt Ihnen **FastAPI**? + +Möchten Sie FastAPI, anderen Benutzern und dem Autor helfen? + +Oder möchten Sie Hilfe zu **FastAPI** erhalten? + +Es gibt sehr einfache Möglichkeiten zu helfen (manche erfordern nur ein oder zwei Klicks). + +Und es gibt auch viele Möglichkeiten, Hilfe zu bekommen. + +## Newsletter abonnieren + +Sie können den (unregelmäßig erscheinenden) [**FastAPI and Friends**-Newsletter](newsletter.md){.internal-link target=_blank} abonnieren, um auf dem Laufenden zu bleiben: + +* Neuigkeiten über FastAPI and Friends 🚀 +* Anleitungen 📝 +* Funktionen ✨ +* Breaking Changes 🚨 +* Tipps und Tricks ✅ +## FastAPI auf Twitter folgen + +<a href="https://twitter.com/fastapi" class="external-link" target="_blank">Folgen Sie @fastapi auf **Twitter**</a>, um die neuesten Nachrichten über **FastAPI** zu erhalten. 🐦 + +## **FastAPI** auf GitHub einen Stern geben + +Sie können FastAPI auf GitHub „starren“ (durch Klicken auf den Stern-Button oben rechts): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ + +Durch das Hinzufügen eines Sterns können andere Benutzer es leichter finden und sehen, dass es für andere bereits nützlich war. + +## Das GitHub-Repository auf Releases beobachten + +Sie können FastAPI in GitHub beobachten (Klicken Sie oben rechts auf den Button „watch“): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 + +Dort können Sie „Releases only“ auswählen. + +Auf diese Weise erhalten Sie Benachrichtigungen (per E-Mail), wenn es einen neuen Release (eine neue Version) von **FastAPI** mit Fehlerbehebungen und neuen Funktionen gibt. + +## Mit dem Autor vernetzen + +Sie können sich mit <a href="https://tiangolo.com" class="external-link" target="_blank">mir (Sebastián Ramírez / `tiangolo`)</a>, dem Autor, verbinden. + +Insbesondere: + +* <a href="https://github.com/tiangolo" class="external-link" target="_blank"> Folgen Sie mir auf **GitHub**</a>. + * Finden Sie andere Open-Source-Projekte, die ich erstellt habe und die Ihnen helfen könnten. + * Folgen Sie mir, um mitzubekommen, wenn ich ein neues Open-Source-Projekt erstelle. +* <a href="https://twitter.com/tiangolo" class="external-link" target="_blank">Folgen Sie mir auf **Twitter**</a> oder <a href="https://fosstodon.org/@tiangolo" class="external-link" target="_blank">Mastodon</a>. + * Berichten Sie mir, wie Sie FastAPI verwenden (das höre ich gerne). + * Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche. + * Sie können auch <a href="https://twitter.com/fastapi" class="external-link" target="_blank">@fastapi auf Twitter folgen</a> (ein separates Konto). +* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">Folgen Sie mir auf **LinkedIn**</a>. + * Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche (obwohl ich Twitter häufiger verwende 🤷♂). +* Lesen Sie, was ich schreibe (oder folgen Sie mir) auf <a href="https://dev.to/tiangolo" class="external-link" target="_blank">**Dev.to**</a> oder <a href="https://medium.com/@tiangolo" class="external-link" target="_blank">**Medium**</a>. + * Lesen Sie andere Ideen, Artikel, und erfahren Sie mehr über die von mir erstellten Tools. + * Folgen Sie mir, um zu lesen, wenn ich etwas Neues veröffentliche. + +## Über **FastAPI** tweeten + +<a href="https://twitter.com/compose/tweet?text=Ich liebe @fastapi, weil ... https://github.com/tiangolo/fastapi" class="external-link" target= "_blank">Tweeten Sie über **FastAPI**</a> und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉 + +Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, in welchem Projekt/Unternehmen Sie es verwenden, usw. + +## Für FastAPI abstimmen + +* <a href="https://www.slant.co/options/34241/~fastapi-review" class="external-link" target="_blank">Stimmen Sie für **FastAPI** auf Slant</a >. +* <a href="https://alternativeto.net/software/fastapi/about/" class="external-link" target="_blank">Stimmen Sie für **FastAPI** auf AlternativeTo</a>. +* <a href="https://stackshare.io/pypi-fastapi" class="external-link" target="_blank">Berichten Sie auf StackShare, dass Sie **FastAPI** verwenden</a>. + +## Anderen bei Fragen auf GitHub helfen + +Sie können versuchen, anderen bei ihren Fragen zu helfen: + +* <a href="https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub-Diskussionen</a> +* <a href="https://github.com/tiangolo/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub-Issues</a> + +In vielen Fällen kennen Sie möglicherweise bereits die Antwort auf diese Fragen. 🤓 + +Wenn Sie vielen Menschen bei ihren Fragen helfen, werden Sie offizieller [FastAPI-Experte](fastapi-people.md#experten){.internal-link target=_blank}. 🎉 + +Denken Sie aber daran, der wichtigste Punkt ist: Versuchen Sie, freundlich zu sein. Die Leute bringen ihre Frustrationen mit und fragen in vielen Fällen nicht auf die beste Art und Weise, aber versuchen Sie dennoch so gut wie möglich, freundlich zu sein. 🤗 + +Die **FastAPI**-Community soll freundlich und einladend sein. Und auch kein Mobbing oder respektloses Verhalten gegenüber anderen akzeptieren. Wir müssen uns umeinander kümmern. + +--- + +So helfen Sie anderen bei Fragen (in Diskussionen oder Problemen): + +### Die Frage verstehen + +* Fragen Sie sich, ob Sie verstehen, was das **Ziel** und der Anwendungsfall der fragenden Person ist. + +* Überprüfen Sie dann, ob die Frage (die überwiegende Mehrheit sind Fragen) **klar** ist. + +* In vielen Fällen handelt es sich bei der gestellten Frage um eine Lösung, die der Benutzer sich vorstellt, aber es könnte eine **bessere** Lösung geben. Wenn Sie das Problem und den Anwendungsfall besser verstehen, können Sie eine bessere **Alternativlösung** vorschlagen. + +* Wenn Sie die Frage nicht verstehen können, fragen Sie nach weiteren **Details**. + +### Das Problem reproduzieren + +In den meisten Fällen und bei den meisten Fragen ist etwas mit dem von der Person erstellten **eigenen Quellcode** los. + +In vielen Fällen wird nur ein Fragment des Codes gepostet, aber das reicht nicht aus, um **das Problem zu reproduzieren**. + +* Sie können die Person darum bitten, ein <a href="https://stackoverflow.com/help/minimal-reproducible-example" class="external-link" target="_blank">minimales, reproduzierbares Beispiel</a> bereitzustellen, welches Sie **kopieren, einfügen** und lokal ausführen können, um den gleichen Fehler oder das gleiche Verhalten zu sehen, das die Person sieht, oder um ihren Anwendungsfall besser zu verstehen. + +* Wenn Sie in Geberlaune sind, können Sie versuchen, selbst ein solches Beispiel zu erstellen, nur basierend auf der Beschreibung des Problems. Denken Sie jedoch daran, dass dies viel Zeit in Anspruch nehmen kann und dass es besser sein kann, zunächst um eine Klärung des Problems zu bitten. + +### Lösungen vorschlagen + +* Nachdem Sie die Frage verstanden haben, können Sie eine mögliche **Antwort** geben. + +* In vielen Fällen ist es besser, das **zugrunde liegende Problem oder den Anwendungsfall** zu verstehen, da es möglicherweise einen besseren Weg zur Lösung gibt als das, was die Person versucht. + +### Um Schließung bitten + +Wenn die Person antwortet, besteht eine hohe Chance, dass Sie ihr Problem gelöst haben. Herzlichen Glückwunsch, **Sie sind ein Held**! 🦸 + +* Wenn es tatsächlich das Problem gelöst hat, können Sie sie darum bitten: + + * In GitHub-Diskussionen: den Kommentar als **Antwort** zu markieren. + * In GitHub-Issues: Das Issue zu **schließen**. + +## Das GitHub-Repository beobachten + +Sie können FastAPI auf GitHub „beobachten“ (Klicken Sie oben rechts auf die Schaltfläche „watch“): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank" >https://github.com/tiangolo/fastapi</a>. 👀 + +Wenn Sie dann „Watching“ statt „Releases only“ auswählen, erhalten Sie Benachrichtigungen, wenn jemand ein neues Issue eröffnet oder eine neue Frage stellt. Sie können auch spezifizieren, dass Sie nur über neue Issues, Diskussionen, PRs, usw. benachrichtigt werden möchten. + +Dann können Sie versuchen, bei der Lösung solcher Fragen zu helfen. + +## Fragen stellen + +Sie können im GitHub-Repository <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">eine neue Frage erstellen</a>, zum Beispiel: + +* Stellen Sie eine **Frage** oder bitten Sie um Hilfe mit einem **Problem**. +* Schlagen Sie eine neue **Funktionalität** vor. + +**Hinweis**: Wenn Sie das tun, bitte ich Sie, auch anderen zu helfen. 😉 + +## Pull Requests prüfen + +Sie können mir helfen, Pull Requests von anderen zu überprüfen (Review). + +Noch einmal, bitte versuchen Sie Ihr Bestes, freundlich zu sein. 🤗 + +--- + +Hier ist, was Sie beachten sollten und wie Sie einen Pull Request überprüfen: + +### Das Problem verstehen + +* Stellen Sie zunächst sicher, dass Sie **das Problem verstehen**, welches der Pull Request zu lösen versucht. Möglicherweise gibt es eine längere Diskussion dazu in einer GitHub-Diskussion oder einem GitHub-Issue. + +* Es besteht auch eine gute Chance, dass der Pull Request nicht wirklich benötigt wird, da das Problem auf **andere Weise** gelöst werden kann. Dann können Sie das vorschlagen oder danach fragen. + +### Der Stil ist nicht so wichtig + +* Machen Sie sich nicht zu viele Gedanken über Dinge wie den Stil von Commit-Nachrichten, ich werde den Commit manuell zusammenführen und anpassen. + +* Machen Sie sich auch keine Sorgen über Stilregeln, es gibt bereits automatisierte Tools, die das überprüfen. + +Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich direkt darum oder füge zusätzliche Commits mit den erforderlichen Änderungen hinzu. + +### Den Code überprüfen + +* Prüfen und lesen Sie den Code, fragen Sie sich, ob er Sinn macht, **führen Sie ihn lokal aus** und testen Sie, ob er das Problem tatsächlich löst. + +* Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben. + +!!! info + Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. + + Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 + + Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 + +* Wenn der PR irgendwie vereinfacht werden kann, fragen Sie ruhig danach, aber seien Sie nicht zu wählerisch, es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die wesentlichen Dinge konzentriert. + +### Tests + +* Helfen Sie mir zu überprüfen, dass der PR **Tests** hat. + +* Überprüfen Sie, dass diese Tests vor dem PR **fehlschlagen**. 🚨 + +* Überprüfen Sie, dass diese Tests nach dem PR **bestanden** werden. ✅ + +* Viele PRs haben keine Tests. Sie können den Autor daran **erinnern**, Tests hinzuzufügen, oder Sie können sogar selbst einige Tests **vorschlagen**. Das ist eines der Dinge, die die meiste Zeit in Anspruch nehmen, und dabei können Sie viel helfen. + +* Kommentieren Sie auch hier anschließend, was Sie versucht haben, sodass ich weiß, dass Sie es überprüft haben. 🤓 + +## Einen Pull Request erstellen + +Sie können zum Quellcode mit Pull Requests [beitragen](contributing.md){.internal-link target=_blank}, zum Beispiel: + +* Um einen Tippfehler zu beheben, den Sie in der Dokumentation gefunden haben. +* Um einen Artikel, ein Video oder einen Podcast über FastAPI zu teilen, den Sie erstellt oder gefunden haben, indem Sie <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">diese Datei bearbeiten</a>. + * Stellen Sie sicher, dass Sie Ihren Link am Anfang des entsprechenden Abschnitts einfügen. +* Um zu helfen, [die Dokumentation in Ihre Sprache zu übersetzen](contributing.md#ubersetzungen){.internal-link target=_blank}. + * Sie können auch dabei helfen, die von anderen erstellten Übersetzungen zu überprüfen (Review). +* Um neue Dokumentationsabschnitte vorzuschlagen. +* Um ein bestehendes Problem / einen bestehenden Bug zu beheben. + * Stellen Sie sicher, dass Sie Tests hinzufügen. +* Um eine neue Funktionalität hinzuzufügen. + * Stellen Sie sicher, dass Sie Tests hinzufügen. + * Stellen Sie sicher, dass Sie Dokumentation hinzufügen, falls das notwendig ist. + +## FastAPI pflegen + +Helfen Sie mir, **FastAPI** instand zu halten! 🤓 + +Es gibt viel zu tun, und das meiste davon können **SIE** tun. + +Die Hauptaufgaben, die Sie jetzt erledigen können, sind: + +* [Helfen Sie anderen bei Fragen auf GitHub](#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} (siehe Abschnitt oben). +* [Prüfen Sie Pull Requests](#pull-requests-prufen){.internal-link target=_blank} (siehe Abschnitt oben). + +Diese beiden Dinge sind es, die **die meiste Zeit in Anspruch nehmen**. Das ist die Hauptarbeit bei der Wartung von FastAPI. + +Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalten** und sorgen dafür, dass es weiterhin **schneller und besser voranschreitet**. 🚀 + +## Beim Chat mitmachen + +Treten Sie dem 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord-Chatserver</a> 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. + +!!! tip "Tipp" + Wenn Sie Fragen haben, stellen Sie sie bei <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Diskussionen</a>, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. + + Nutzen Sie den Chat nur für andere allgemeine Gespräche. + +### Den Chat nicht für Fragen verwenden + +Bedenken Sie, da Chats mehr „freie Konversation“ ermöglichen, dass es verlockend ist, Fragen zu stellen, die zu allgemein und schwierig zu beantworten sind, sodass Sie möglicherweise keine Antworten erhalten. + +Auf GitHub hilft Ihnen die Vorlage dabei, die richtige Frage zu schreiben, sodass Sie leichter eine gute Antwort erhalten oder das Problem sogar selbst lösen können, noch bevor Sie fragen. Und auf GitHub kann ich sicherstellen, dass ich immer alles beantworte, auch wenn es einige Zeit dauert. Ich persönlich kann das mit den Chat-Systemen nicht machen. 😅 + +Unterhaltungen in den Chat-Systemen sind außerdem nicht so leicht durchsuchbar wie auf GitHub, sodass Fragen und Antworten möglicherweise im Gespräch verloren gehen. Und nur die auf GitHub machen einen [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank}, Sie werden also höchstwahrscheinlich mehr Aufmerksamkeit auf GitHub erhalten. + +Auf der anderen Seite gibt es Tausende von Benutzern in den Chat-Systemen, sodass die Wahrscheinlichkeit hoch ist, dass Sie dort fast immer jemanden zum Reden finden. 😄 + +## Den Autor sponsern + +Sie können den Autor (mich) auch über <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub-Sponsoren</a> finanziell unterstützen. + +Dort könnten Sie mir als Dankeschön einen Kaffee spendieren ☕️. 😄 + +Und Sie können auch Silber- oder Gold-Sponsor für FastAPI werden. 🏅🎉 + +## Die Tools sponsern, die FastAPI unterstützen + +Wie Sie in der Dokumentation gesehen haben, steht FastAPI auf den Schultern von Giganten, Starlette und Pydantic. + +Sie können auch sponsern: + +* <a href="https://github.com/sponsors/samuelcolvin" class="external-link" target="_blank">Samuel Colvin (Pydantic)</a> +* <a href="https://github.com/sponsors/encode" class="external-link" target="_blank">Encode (Starlette, Uvicorn)</a> + +--- + +Danke! 🚀 From 7292a59a48c6b7412dedbd33dd128f0a97131881 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:30:07 +0100 Subject: [PATCH 239/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/behind-a-proxy.md`=20(#10675)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/behind-a-proxy.md | 350 ++++++++++++++++++++++++ 1 file changed, 350 insertions(+) create mode 100644 docs/de/docs/advanced/behind-a-proxy.md diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md new file mode 100644 index 000000000..ad0a92e28 --- /dev/null +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -0,0 +1,350 @@ +# Hinter einem Proxy + +In manchen Situationen müssen Sie möglicherweise einen **Proxy**-Server wie Traefik oder Nginx verwenden, mit einer Konfiguration, die ein zusätzliches Pfadpräfix hinzufügt, das von Ihrer Anwendung nicht gesehen wird. + +In diesen Fällen können Sie `root_path` verwenden, um Ihre Anwendung zu konfigurieren. + +Der `root_path` („Wurzelpfad“) ist ein Mechanismus, der von der ASGI-Spezifikation bereitgestellt wird (auf der FastAPI via Starlette aufbaut). + +Der `root_path` wird verwendet, um diese speziellen Fälle zu handhaben. + +Und er wird auch intern beim Mounten von Unteranwendungen verwendet. + +## Proxy mit einem abgetrennten Pfadpräfix + +Ein Proxy mit einem abgetrennten Pfadpräfix bedeutet in diesem Fall, dass Sie einen Pfad unter `/app` in Ihrem Code deklarieren könnten, dann aber, eine Ebene darüber, den Proxy hinzufügen, der Ihre **FastAPI**-Anwendung unter einem Pfad wie `/api/v1` platziert. + +In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1/app` bereitgestellt. + +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!} +``` + +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. + +Bis hierher würde alles wie gewohnt funktionieren. + +Wenn Sie dann jedoch die Benutzeroberfläche der integrierten Dokumentation (das Frontend) öffnen, wird angenommen, dass sich das OpenAPI-Schema unter `/openapi.json` anstelle von `/api/v1/openapi.json` befindet. + +Das Frontend (das im Browser läuft) würde also versuchen, `/openapi.json` zu erreichen und wäre nicht in der Lage, das OpenAPI-Schema abzurufen. + +Da wir für unsere Anwendung einen Proxy mit dem Pfadpräfix `/api/v1` haben, muss das Frontend das OpenAPI-Schema unter `/api/v1/openapi.json` abrufen. + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy auf http://0.0.0.0:9999/api/v1/app"] +server["Server auf http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +!!! tip "Tipp" + Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. + +Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel: + +```JSON hl_lines="4-8" +{ + "openapi": "3.1.0", + // Hier mehr Einstellungen + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // Hier mehr Einstellungen + } +} +``` + +In diesem Beispiel könnte der „Proxy“ etwa **Traefik** sein. Und der Server wäre so etwas wie **Uvicorn**, auf dem Ihre FastAPI-Anwendung ausgeführt wird. + +### Bereitstellung des `root_path` + +Um dies zu erreichen, können Sie die Kommandozeilenoption `--root-path` wie folgt verwenden: + +<div class="termy"> + +```console +$ uvicorn main:app --root-path /api/v1 + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. + +!!! note "Technische Details" + Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. + + Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. + +### Überprüfen des aktuellen `root_path` + +Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Anfrage verwendet wird. Er ist Teil des `scope`-Dictionarys (das ist Teil der ASGI-Spezifikation). + +Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. + +```Python hl_lines="8" +{!../../../docs_src/behind_a_proxy/tutorial001.py!} +``` + +Wenn Sie Uvicorn dann starten mit: + +<div class="termy"> + +```console +$ uvicorn main:app --root-path /api/v1 + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +wäre die Response etwa: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Festlegen des `root_path` in der FastAPI-Anwendung + +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!} +``` + +Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. + +### Über `root_path` + +Beachten Sie, dass der Server (Uvicorn) diesen `root_path` für nichts anderes außer die Weitergabe an die Anwendung verwendet. + +Aber wenn Sie mit Ihrem Browser auf <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000/app</a> gehen, sehen Sie die normale Antwort: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Es wird also nicht erwartet, dass unter `http://127.0.0.1:8000/api/v1/app` darauf zugegriffen wird. + +Uvicorn erwartet, dass der Proxy unter `http://127.0.0.1:8000/app` auf Uvicorn zugreift, und dann liegt es in der Verantwortung des Proxys, das zusätzliche `/api/v1`-Präfix darüber hinzuzufügen. + +## Über Proxys mit einem abgetrennten Pfadpräfix + +Bedenken Sie, dass ein Proxy mit abgetrennten Pfadpräfix nur eine von vielen Konfigurationsmöglichkeiten ist. + +Wahrscheinlich wird in vielen Fällen die Standardeinstellung sein, dass der Proxy kein abgetrenntes Pfadpräfix hat. + +In einem solchen Fall (ohne ein abgetrenntes Pfadpräfix) würde der Proxy auf etwas wie `https://myawesomeapp.com` lauschen, und wenn der Browser dann zu `https://myawesomeapp.com/api/v1/` wechselt, und Ihr Server (z. B. Uvicorn) auf `http://127.0.0.1:8000` lauscht, würde der Proxy (ohne ein abgetrenntes Pfadpräfix) über denselben Pfad auf Uvicorn zugreifen: `http://127.0.0.1:8000/api/v1/app`. + +## Lokal testen mit Traefik + +Sie können das Experiment mit einem abgetrennten Pfadpräfix ganz einfach lokal ausführen, indem Sie <a href="https://docs.traefik.io/" class="external-link" target="_blank">Traefik</a> verwenden. + +<a href="https://github.com/containous/traefik/releases" class="external-link" target="_blank">Laden Sie Traefik herunter</a>, es ist eine einzelne Binärdatei, Sie können die komprimierte Datei extrahieren und sie direkt vom Terminal aus ausführen. + +Dann erstellen Sie eine Datei `traefik.toml` mit: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. + +!!! tip "Tipp" + Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. + +Erstellen Sie nun die andere Datei `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +Diese Datei konfiguriert Traefik, das Pfadpräfix `/api/v1` zu verwenden. + +Und dann leitet Traefik seine Anfragen an Ihren Uvicorn weiter, der unter `http://127.0.0.1:8000` läuft. + +Starten Sie nun Traefik: + +<div class="termy"> + +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +</div> + +Und jetzt starten Sie Ihre Anwendung mit Uvicorn, indem Sie die Option `--root-path` verwenden: + +<div class="termy"> + +```console +$ uvicorn main:app --root-path /api/v1 + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +### Die Responses betrachten + +Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: <a href="http://127.0.0.1:8000/app" class="external-link" target="_blank">http://127.0.0.1:8000/app</a>, sehen Sie die normale Response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +!!! tip "Tipp" + Beachten Sie, dass, obwohl Sie unter `http://127.0.0.1:8000/app` darauf zugreifen, als `root_path` angezeigt wird `/api/v1`, welches aus der Option `--root-path` stammt. + +Öffnen Sie nun die URL mit dem Port für Traefik, einschließlich des Pfadpräfixes: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>. + +Wir bekommen die gleiche Response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Diesmal jedoch unter der URL mit dem vom Proxy bereitgestellten Präfixpfad: `/api/v1`. + +Die Idee hier ist natürlich, dass jeder über den Proxy auf die Anwendung zugreifen soll, daher ist die Version mit dem Pfadpräfix `/api/v1` die „korrekte“. + +Und die von Uvicorn direkt bereitgestellte Version ohne Pfadpräfix (`http://127.0.0.1:8000/app`) wäre ausschließlich für den Zugriff durch den _Proxy_ (Traefik) bestimmt. + +Dies demonstriert, wie der Proxy (Traefik) das Pfadpräfix verwendet und wie der Server (Uvicorn) den `root_path` aus der Option `--root-path` verwendet. + +### Es in der Dokumentationsoberfläche betrachten + +Jetzt folgt der spaßige Teil. ✨ + +Der „offizielle“ Weg, auf die Anwendung zuzugreifen, wäre über den Proxy mit dem von uns definierten Pfadpräfix. Wenn Sie also die von Uvicorn direkt bereitgestellte Dokumentationsoberfläche ohne das Pfadpräfix in der URL ausprobieren, wird es erwartungsgemäß nicht funktionieren, da erwartet wird, dass der Zugriff über den Proxy erfolgt. + +Sie können das unter <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> sehen: + +<img src="/img/tutorial/behind-a-proxy/image01.png"> + +Wenn wir jedoch unter der „offiziellen“ URL, über den Proxy mit Port `9999`, unter `/api/v1/docs`, auf die Dokumentationsoberfläche zugreifen, funktioniert es ordnungsgemäß! 🎉 + +Sie können das unter <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> testen: + +<img src="/img/tutorial/behind-a-proxy/image02.png"> + +Genau so, wie wir es wollten. ✔️ + +Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`server` in OpenAPI mit der von `root_path` bereitgestellten URL zu erstellen. + +## Zusätzliche Server + +!!! warning "Achtung" + Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. + +Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`. + +Sie können aber auch andere alternative `server` bereitstellen, beispielsweise wenn Sie möchten, dass *dieselbe* Dokumentationsoberfläche mit einer Staging- und Produktionsumgebung interagiert. + +Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es einen `root_path` gibt (da Ihre API hinter einem Proxy läuft), fügt **FastAPI** einen „Server“ mit diesem `root_path` am Anfang der Liste ein. + +Zum Beispiel: + +```Python hl_lines="4-7" +{!../../../docs_src/behind_a_proxy/tutorial003.py!} +``` + +Erzeugt ein OpenAPI-Schema, wie: + +```JSON hl_lines="5-7" +{ + "openapi": "3.1.0", + // Hier mehr Einstellungen + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // Hier mehr Einstellungen + } +} +``` + +!!! tip "Tipp" + Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. + +In der Dokumentationsoberfläche unter <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> würde es so aussehen: + +<img src="/img/tutorial/behind-a-proxy/image03.png"> + +!!! tip "Tipp" + Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. + +### Den automatischen Server von `root_path` deaktivieren + +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!} +``` + +Dann wird er nicht in das OpenAPI-Schema aufgenommen. + +## Mounten einer Unteranwendung + +Wenn Sie gleichzeitig eine Unteranwendung mounten (wie beschrieben in [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}) und einen Proxy mit `root_path` verwenden wollen, können Sie das normal tun, wie Sie es erwarten würden. + +FastAPI verwendet intern den `root_path` auf intelligente Weise, sodass es einfach funktioniert. ✨ From c9ab68264432e36b8420782d0b39eef0d9305743 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:30:18 +0100 Subject: [PATCH 240/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/deployment/cloud.md`=20(#10746)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/cloud.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 docs/de/docs/deployment/cloud.md diff --git a/docs/de/docs/deployment/cloud.md b/docs/de/docs/deployment/cloud.md new file mode 100644 index 000000000..2d70fe4e5 --- /dev/null +++ b/docs/de/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# FastAPI-Deployment bei Cloud-Anbietern + +Sie können praktisch **jeden Cloud-Anbieter** für das <abbr title="Bereitstellen der fertigen Anwendung für die Endbenutzer">Deployment</abbr> Ihrer FastAPI-Anwendung verwenden. + +In den meisten Fällen verfügen die Haupt-Cloud-Anbieter über Anleitungen zum Deployment von FastAPI. + +## Cloud-Anbieter – Sponsoren + +Einige Cloud-Anbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, dies gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 + +Vielleicht möchten Sie deren Dienste ausprobieren und deren Anleitungen folgen: + +* <a href="https://docs.platform.sh/languages/python.html?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" class="external-link" target="_blank">Platform.sh</a> +* <a href="https://docs.porter.run/language-specific-guides/fastapi" class="external-link" target="_blank">Porter</a> +* <a href="https://docs.withcoherence.com/docs/configuration/frameworks?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024#fast-api-example" class="external-link" target="_blank">Coherence</a> From c457f320d911426ddce9475c95bfbdf76af2ac6c Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sat, 30 Mar 2024 21:30:59 +0100 Subject: [PATCH 241/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/advanced/events.md`=20(#10693)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/events.md | 162 ++++++++++++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 docs/de/docs/advanced/events.md diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md new file mode 100644 index 000000000..e29f61ab9 --- /dev/null +++ b/docs/de/docs/advanced/events.md @@ -0,0 +1,162 @@ +# Lifespan-Events + +Sie können Logik (Code) definieren, die ausgeführt werden soll, bevor die Anwendung **hochfährt**. Dies bedeutet, dass dieser Code **einmal** ausgeführt wird, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**. + +Auf die gleiche Weise können Sie Logik (Code) definieren, die ausgeführt werden soll, wenn die Anwendung **heruntergefahren** wird. In diesem Fall wird dieser Code **einmal** ausgeführt, **nachdem** möglicherweise **viele Requests** bearbeitet wurden. + +Da dieser Code ausgeführt wird, bevor die Anwendung **beginnt**, Requests entgegenzunehmen, und unmittelbar, nachdem sie die Bearbeitung von Requests **abgeschlossen hat**, deckt er die gesamte **Lebensdauer – „Lifespan“** – der Anwendung ab (das Wort „Lifespan“ wird gleich wichtig sein 😉). + +Dies kann sehr nützlich sein, um **Ressourcen** einzurichten, die Sie in der gesamten Anwendung verwenden wollen und die von Requests **gemeinsam genutzt** werden und/oder die Sie anschließend **aufräumen** müssen. Zum Beispiel ein Pool von Datenbankverbindungen oder das Laden eines gemeinsam genutzten Modells für maschinelles Lernen. + +## Anwendungsfall + +Beginnen wir mit einem Beispiel-**Anwendungsfall** und schauen uns dann an, wie wir ihn mit dieser Methode implementieren können. + +Stellen wir uns vor, Sie verfügen über einige **Modelle für maschinelles Lernen**, die Sie zur Bearbeitung von Requests verwenden möchten. 🤖 + +Die gleichen Modelle werden von den Requests gemeinsam genutzt, es handelt sich also nicht um ein Modell pro Request, pro Benutzer, oder ähnliches. + +Stellen wir uns vor, dass das Laden des Modells **eine ganze Weile dauern** kann, da viele **Daten von der Festplatte** gelesen werden müssen. Sie möchten das also nicht für jeden Request tun. + +Sie könnten das auf der obersten Ebene des Moduls/der Datei machen, aber das würde auch bedeuten, dass **das Modell geladen wird**, selbst wenn Sie nur einen einfachen automatisierten Test ausführen, dann wäre dieser Test **langsam**, weil er warten müsste, bis das Modell geladen ist, bevor er einen davon unabhängigen Teil des Codes ausführen könnte. + +Das wollen wir besser machen: Laden wir das Modell, bevor die Requests bearbeitet werden, aber unmittelbar bevor die Anwendung beginnt, Requests zu empfangen, und nicht, während der Code geladen wird. + +## Lifespan + +Sie können diese Logik beim *Hochfahren* und *Herunterfahren* mithilfe des `lifespan`-Parameters der `FastAPI`-App und eines „Kontextmanagers“ definieren (ich zeige Ihnen gleich, was das ist). + +Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an. + +Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt: + +```Python hl_lines="16 19" +{!../../../docs_src/events/tutorial003.py!} +``` + +Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*. + +Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden. + +!!! tip "Tipp" + Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. + + Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 + +### Lifespan-Funktion + +Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`. + +```Python hl_lines="14-19" +{!../../../docs_src/events/tutorial003.py!} +``` + +Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet. + +Und der Teil nach `yield` wird ausgeführt, **nachdem** die Anwendung beendet ist. + +### Asynchroner Kontextmanager + +Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen. + +Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt. + +```Python hl_lines="1 13" +{!../../../docs_src/events/tutorial003.py!} +``` + +Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden: + +```Python +with open("file.txt") as file: + file.read() +``` + +In neueren Versionen von Python gibt es auch einen **asynchronen Kontextmanager**. Sie würden ihn mit `async with` verwenden: + +```Python +async with lifespan(app): + await do_stuff() +``` + +Wenn Sie wie oben einen Kontextmanager oder einen asynchronen Kontextmanager erstellen, führt dieser vor dem Betreten des `with`-Blocks den Code vor dem `yield` aus, und nach dem Verlassen des `with`-Blocks wird er den Code nach dem `yield` ausführen. + +In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergeben ihn an FastAPI, damit es ihn verwenden kann. + +Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben. + +```Python hl_lines="22" +{!../../../docs_src/events/tutorial003.py!} +``` + +## Alternative Events (deprecated) + +!!! warning "Achtung" + Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. + + Sie können diesen Teil wahrscheinlich überspringen. + +Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird. + +Sie können <abbr title="Eventhandler – Ereignisbehandler: Funktion, die bei jedem Eintreten eines bestimmten Ereignisses ausgeführt wird">Eventhandler</abbr> (Funktionen) definieren, die ausgeführt werden sollen, bevor die Anwendung hochgefahren wird oder wenn die Anwendung heruntergefahren wird. + +Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. + +### `startup`-Event + +Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: + +```Python hl_lines="8" +{!../../../docs_src/events/tutorial001.py!} +``` + +In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten. + +Sie können mehr als eine Eventhandler-Funktion hinzufügen. + +Und Ihre Anwendung empfängt erst dann Anfragen, wenn alle `startup`-Eventhandler abgeschlossen sind. + +### `shutdown`-Event + +Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: + +```Python hl_lines="6" +{!../../../docs_src/events/tutorial002.py!} +``` + +Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. + +!!! info + In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. + +!!! tip "Tipp" + Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. + + Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. + + Aber `open()` verwendet nicht `async` und `await`. + + Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. + +### `startup` und `shutdown` zusammen + +Es besteht eine hohe Wahrscheinlichkeit, dass die Logik für Ihr *Hochfahren* und *Herunterfahren* miteinander verknüpft ist. Vielleicht möchten Sie etwas beginnen und es dann beenden, eine Ressource laden und sie dann freigeben usw. + +Bei getrennten Funktionen, die keine gemeinsame Logik oder Variablen haben, ist dies schwieriger, da Sie Werte in globalen Variablen speichern oder ähnliche Tricks verwenden müssen. + +Aus diesem Grund wird jetzt empfohlen, stattdessen `lifespan` wie oben erläutert zu verwenden. + +## Technische Details + +Nur ein technisches Detail für die neugierigen Nerds. 🤓 + +In der technischen ASGI-Spezifikation ist dies Teil des <a href="https://asgi.readthedocs.io/en/latest/specs/lifespan.html" class="external-link" target="_blank">Lifespan Protokolls</a> und definiert Events namens `startup` und `shutdown`. + +!!! info + Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlettes Lifespan-Dokumentation</a>. + + Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. + +## Unteranwendungen + +🚨 Beachten Sie, dass diese Lifespan-Events (Hochfahren und Herunterfahren) nur für die Hauptanwendung ausgeführt werden, nicht für [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}. From 975e0ab5acfb19556a0a9366a12395e1364d1140 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 20:57:36 +0000 Subject: [PATCH 242/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7d5d525cb..989f68e12 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/concepts.md`. PR [#10744](https://github.com/tiangolo/fastapi/pull/10744) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/features.md`. PR [#10284](https://github.com/tiangolo/fastapi/pull/10284) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/server-workers.md`. PR [#10747](https://github.com/tiangolo/fastapi/pull/10747) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/docker.md`. PR [#10759](https://github.com/tiangolo/fastapi/pull/10759) by [@nilslindemann](https://github.com/nilslindemann). From 914a82b41d66e27235bd5b23c0b3ff6a6fb82d33 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 20:58:13 +0000 Subject: [PATCH 243/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 989f68e12..fbbe56c07 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/manually.md`. PR [#10738](https://github.com/tiangolo/fastapi/pull/10738) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/concepts.md`. PR [#10744](https://github.com/tiangolo/fastapi/pull/10744) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/features.md`. PR [#10284](https://github.com/tiangolo/fastapi/pull/10284) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/server-workers.md`. PR [#10747](https://github.com/tiangolo/fastapi/pull/10747) by [@nilslindemann](https://github.com/nilslindemann). From 255366dff6f3f554d381acd8e626eb71b6543276 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 20:58:47 +0000 Subject: [PATCH 244/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index fbbe56c07..7a3c5d274 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/https.md`. PR [#10737](https://github.com/tiangolo/fastapi/pull/10737) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/manually.md`. PR [#10738](https://github.com/tiangolo/fastapi/pull/10738) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/concepts.md`. PR [#10744](https://github.com/tiangolo/fastapi/pull/10744) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/features.md`. PR [#10284](https://github.com/tiangolo/fastapi/pull/10284) by [@nilslindemann](https://github.com/nilslindemann). From 707c918381f60060a7480f3c81c12c036d1df184 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 20:59:30 +0000 Subject: [PATCH 245/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7a3c5d274..05f75e5f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/index.md`. PR [#10733](https://github.com/tiangolo/fastapi/pull/10733) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/https.md`. PR [#10737](https://github.com/tiangolo/fastapi/pull/10737) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/manually.md`. PR [#10738](https://github.com/tiangolo/fastapi/pull/10738) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/concepts.md`. PR [#10744](https://github.com/tiangolo/fastapi/pull/10744) by [@nilslindemann](https://github.com/nilslindemann). From 18e2ad57a3ab13d388f1f6460a317b22e1245ccd Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:00:04 +0000 Subject: [PATCH 246/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 05f75e5f6..7d86aadc6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/wsgi.md`. PR [#10713](https://github.com/tiangolo/fastapi/pull/10713) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/index.md`. PR [#10733](https://github.com/tiangolo/fastapi/pull/10733) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/https.md`. PR [#10737](https://github.com/tiangolo/fastapi/pull/10737) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/manually.md`. PR [#10738](https://github.com/tiangolo/fastapi/pull/10738) by [@nilslindemann](https://github.com/nilslindemann). From 7fc01579730036dff84e48d4e9168c526f9b7b36 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:00:42 +0000 Subject: [PATCH 247/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7d86aadc6..76ed99769 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/settings.md`. PR [#10709](https://github.com/tiangolo/fastapi/pull/10709) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/wsgi.md`. PR [#10713](https://github.com/tiangolo/fastapi/pull/10713) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/index.md`. PR [#10733](https://github.com/tiangolo/fastapi/pull/10733) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/https.md`. PR [#10737](https://github.com/tiangolo/fastapi/pull/10737) by [@nilslindemann](https://github.com/nilslindemann). From 20b8c512024b16b896d624cefd37465c8c2d625a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:01:27 +0000 Subject: [PATCH 248/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 76ed99769..d59c6a2a2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/openapi-callbacks.md`. PR [#10710](https://github.com/tiangolo/fastapi/pull/10710) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/settings.md`. PR [#10709](https://github.com/tiangolo/fastapi/pull/10709) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/wsgi.md`. PR [#10713](https://github.com/tiangolo/fastapi/pull/10713) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/index.md`. PR [#10733](https://github.com/tiangolo/fastapi/pull/10733) by [@nilslindemann](https://github.com/nilslindemann). From d371c69e479a333948ce6c8d9a76044e19cfbf33 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:02:03 +0000 Subject: [PATCH 249/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d59c6a2a2..0af747c8e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/testing-dependencies.md`. PR [#10706](https://github.com/tiangolo/fastapi/pull/10706) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/openapi-callbacks.md`. PR [#10710](https://github.com/tiangolo/fastapi/pull/10710) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/settings.md`. PR [#10709](https://github.com/tiangolo/fastapi/pull/10709) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/wsgi.md`. PR [#10713](https://github.com/tiangolo/fastapi/pull/10713) by [@nilslindemann](https://github.com/nilslindemann). From 9da3d78ab1a5e72f37dbcc6d32873d9ecaaab99c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:02:42 +0000 Subject: [PATCH 250/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0af747c8e..adab5bb90 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/testing-events.md`. PR [#10704](https://github.com/tiangolo/fastapi/pull/10704) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-dependencies.md`. PR [#10706](https://github.com/tiangolo/fastapi/pull/10706) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/openapi-callbacks.md`. PR [#10710](https://github.com/tiangolo/fastapi/pull/10710) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/settings.md`. PR [#10709](https://github.com/tiangolo/fastapi/pull/10709) by [@nilslindemann](https://github.com/nilslindemann). From 9bb85c64850e06fe5bda30bb7eef0350f1c8edb5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:03:34 +0000 Subject: [PATCH 251/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index adab5bb90..406564ee0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/testing-websockets.md`. PR [#10703](https://github.com/tiangolo/fastapi/pull/10703) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-events.md`. PR [#10704](https://github.com/tiangolo/fastapi/pull/10704) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-dependencies.md`. PR [#10706](https://github.com/tiangolo/fastapi/pull/10706) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/openapi-callbacks.md`. PR [#10710](https://github.com/tiangolo/fastapi/pull/10710) by [@nilslindemann](https://github.com/nilslindemann). From 31d3528c62738d37cb43bf5b87fc510ce787706b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:04:08 +0000 Subject: [PATCH 252/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 406564ee0..b6dfd2e2b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/websockets.md`. PR [#10687](https://github.com/tiangolo/fastapi/pull/10687) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-websockets.md`. PR [#10703](https://github.com/tiangolo/fastapi/pull/10703) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-events.md`. PR [#10704](https://github.com/tiangolo/fastapi/pull/10704) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-dependencies.md`. PR [#10706](https://github.com/tiangolo/fastapi/pull/10706) by [@nilslindemann](https://github.com/nilslindemann). From de45cc22aef6b5144087574228282a8eaa3c5838 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:04:38 +0000 Subject: [PATCH 253/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b6dfd2e2b..dc0d24fe9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/sub-applications.md`. PR [#10671](https://github.com/tiangolo/fastapi/pull/10671) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/websockets.md`. PR [#10687](https://github.com/tiangolo/fastapi/pull/10687) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-websockets.md`. PR [#10703](https://github.com/tiangolo/fastapi/pull/10703) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-events.md`. PR [#10704](https://github.com/tiangolo/fastapi/pull/10704) by [@nilslindemann](https://github.com/nilslindemann). From 8064a36a4f347312e85158d56a4c70c7154ad6b3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:05:28 +0000 Subject: [PATCH 254/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index dc0d24fe9..93dc05c1f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/middleware.md`. PR [#10668](https://github.com/tiangolo/fastapi/pull/10668) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/sub-applications.md`. PR [#10671](https://github.com/tiangolo/fastapi/pull/10671) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/websockets.md`. PR [#10687](https://github.com/tiangolo/fastapi/pull/10687) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/testing-websockets.md`. PR [#10703](https://github.com/tiangolo/fastapi/pull/10703) by [@nilslindemann](https://github.com/nilslindemann). From 6f4b0eb8f2f83e26b54dfa94bbdaaf7ab5023ac0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:06:05 +0000 Subject: [PATCH 255/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 93dc05c1f..eb1569859 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/dataclasses.md`. PR [#10667](https://github.com/tiangolo/fastapi/pull/10667) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/middleware.md`. PR [#10668](https://github.com/tiangolo/fastapi/pull/10668) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/sub-applications.md`. PR [#10671](https://github.com/tiangolo/fastapi/pull/10671) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/websockets.md`. PR [#10687](https://github.com/tiangolo/fastapi/pull/10687) by [@nilslindemann](https://github.com/nilslindemann). From 57e0af29b20eee7ec572add95d93bcab2765220a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:06:49 +0000 Subject: [PATCH 256/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index eb1569859..78e030c9a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/using-request-directly.md`. PR [#10653](https://github.com/tiangolo/fastapi/pull/10653) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/dataclasses.md`. PR [#10667](https://github.com/tiangolo/fastapi/pull/10667) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/middleware.md`. PR [#10668](https://github.com/tiangolo/fastapi/pull/10668) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/sub-applications.md`. PR [#10671](https://github.com/tiangolo/fastapi/pull/10671) by [@nilslindemann](https://github.com/nilslindemann). From 8d8ea4316e64968f4c8b1bc7de0b87c27a25b2b3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:07:21 +0000 Subject: [PATCH 257/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 78e030c9a..3985a7859 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/security/index.md`. PR [#10635](https://github.com/tiangolo/fastapi/pull/10635) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/using-request-directly.md`. PR [#10653](https://github.com/tiangolo/fastapi/pull/10653) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/dataclasses.md`. PR [#10667](https://github.com/tiangolo/fastapi/pull/10667) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/middleware.md`. PR [#10668](https://github.com/tiangolo/fastapi/pull/10668) by [@nilslindemann](https://github.com/nilslindemann). From ae80b91922d8285740047d0bc620a6fe1408ec9f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:09:23 +0000 Subject: [PATCH 258/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3985a7859..f18b13903 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/advanced-dependencies.md`. PR [#10633](https://github.com/tiangolo/fastapi/pull/10633) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/index.md`. PR [#10635](https://github.com/tiangolo/fastapi/pull/10635) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/using-request-directly.md`. PR [#10653](https://github.com/tiangolo/fastapi/pull/10653) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/dataclasses.md`. PR [#10667](https://github.com/tiangolo/fastapi/pull/10667) by [@nilslindemann](https://github.com/nilslindemann). From e12303e973376adb1a8ece7fb44c07b29b3c960c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:09:48 +0000 Subject: [PATCH 259/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f18b13903..d7a4741ac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/response-change-status-code.md`. PR [#10632](https://github.com/tiangolo/fastapi/pull/10632) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/advanced-dependencies.md`. PR [#10633](https://github.com/tiangolo/fastapi/pull/10633) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/index.md`. PR [#10635](https://github.com/tiangolo/fastapi/pull/10635) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/using-request-directly.md`. PR [#10653](https://github.com/tiangolo/fastapi/pull/10653) by [@nilslindemann](https://github.com/nilslindemann). From d576622aaee21da8bddf6cd66ed3e9714c22667a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:10:37 +0000 Subject: [PATCH 260/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d7a4741ac..693698636 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/response-headers.md`. PR [#10628](https://github.com/tiangolo/fastapi/pull/10628) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-change-status-code.md`. PR [#10632](https://github.com/tiangolo/fastapi/pull/10632) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/advanced-dependencies.md`. PR [#10633](https://github.com/tiangolo/fastapi/pull/10633) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/index.md`. PR [#10635](https://github.com/tiangolo/fastapi/pull/10635) by [@nilslindemann](https://github.com/nilslindemann). From e664e5e0f068a27174986fe0f7393206e42e8295 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:10:41 +0000 Subject: [PATCH 261/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 693698636..b6af3e1a5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/response-cookies.md`. PR [#10627](https://github.com/tiangolo/fastapi/pull/10627) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-headers.md`. PR [#10628](https://github.com/tiangolo/fastapi/pull/10628) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-change-status-code.md`. PR [#10632](https://github.com/tiangolo/fastapi/pull/10632) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/advanced-dependencies.md`. PR [#10633](https://github.com/tiangolo/fastapi/pull/10633) by [@nilslindemann](https://github.com/nilslindemann). From 472c69df834c64d98dd371f0689ff7c19dfd6613 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:10:50 +0000 Subject: [PATCH 262/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b6af3e1a5..bd47ae37b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/additional-responses.md`. PR [#10626](https://github.com/tiangolo/fastapi/pull/10626) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-cookies.md`. PR [#10627](https://github.com/tiangolo/fastapi/pull/10627) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-headers.md`. PR [#10628](https://github.com/tiangolo/fastapi/pull/10628) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-change-status-code.md`. PR [#10632](https://github.com/tiangolo/fastapi/pull/10632) by [@nilslindemann](https://github.com/nilslindemann). From d6c814a927727f080e664e1eb7911feb8c4a3daf Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:11:05 +0000 Subject: [PATCH 263/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bd47ae37b..52705c256 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/response-directly.md`. PR [#10618](https://github.com/tiangolo/fastapi/pull/10618) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/additional-responses.md`. PR [#10626](https://github.com/tiangolo/fastapi/pull/10626) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-cookies.md`. PR [#10627](https://github.com/tiangolo/fastapi/pull/10627) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-headers.md`. PR [#10628](https://github.com/tiangolo/fastapi/pull/10628) by [@nilslindemann](https://github.com/nilslindemann). From a25e4cad6d3a5b76aaccff2b35d708739a9a15cf Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:11:12 +0000 Subject: [PATCH 264/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 52705c256..0139987df 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/index.md`. PR [#10611](https://github.com/tiangolo/fastapi/pull/10611) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-directly.md`. PR [#10618](https://github.com/tiangolo/fastapi/pull/10618) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/additional-responses.md`. PR [#10626](https://github.com/tiangolo/fastapi/pull/10626) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-cookies.md`. PR [#10627](https://github.com/tiangolo/fastapi/pull/10627) by [@nilslindemann](https://github.com/nilslindemann). From 8a6ac936775d25acef2ed9db8e140fdb2f23da0e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:13:53 +0000 Subject: [PATCH 265/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0139987df..5bacc4a46 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/schema-extra-example.md`. PR [#10597](https://github.com/tiangolo/fastapi/pull/10597) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/index.md`. PR [#10611](https://github.com/tiangolo/fastapi/pull/10611) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-directly.md`. PR [#10618](https://github.com/tiangolo/fastapi/pull/10618) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/additional-responses.md`. PR [#10626](https://github.com/tiangolo/fastapi/pull/10626) by [@nilslindemann](https://github.com/nilslindemann). From 2f47119f706c4aca1d460036dc27eb41120f9a0b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:14:29 +0000 Subject: [PATCH 266/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5bacc4a46..2f8138af2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/testing.md`. PR [#10586](https://github.com/tiangolo/fastapi/pull/10586) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/schema-extra-example.md`. PR [#10597](https://github.com/tiangolo/fastapi/pull/10597) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/index.md`. PR [#10611](https://github.com/tiangolo/fastapi/pull/10611) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/response-directly.md`. PR [#10618](https://github.com/tiangolo/fastapi/pull/10618) by [@nilslindemann](https://github.com/nilslindemann). From 27b1bd12ff48a560c03fdfb6a7046f1b29b8be15 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:15:52 +0000 Subject: [PATCH 267/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f8138af2..fbce9c600 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/metadata.md`. PR [#10581](https://github.com/tiangolo/fastapi/pull/10581) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/testing.md`. PR [#10586](https://github.com/tiangolo/fastapi/pull/10586) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/schema-extra-example.md`. PR [#10597](https://github.com/tiangolo/fastapi/pull/10597) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/index.md`. PR [#10611](https://github.com/tiangolo/fastapi/pull/10611) by [@nilslindemann](https://github.com/nilslindemann). From 3242b13abf9f00bbbe5beb8fad498526c93f51eb Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:16:46 +0000 Subject: [PATCH 268/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index fbce9c600..616b4e314 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/async-tests.md`. PR [#10708](https://github.com/tiangolo/fastapi/pull/10708) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/metadata.md`. PR [#10581](https://github.com/tiangolo/fastapi/pull/10581) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/testing.md`. PR [#10586](https://github.com/tiangolo/fastapi/pull/10586) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/schema-extra-example.md`. PR [#10597](https://github.com/tiangolo/fastapi/pull/10597) by [@nilslindemann](https://github.com/nilslindemann). From 3afcf4e37011645cc915fb4d087ee222591a6414 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:17:14 +0000 Subject: [PATCH 269/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 616b4e314..d930d0f43 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/security/oauth2-scopes.md`. PR [#10643](https://github.com/tiangolo/fastapi/pull/10643) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/async-tests.md`. PR [#10708](https://github.com/tiangolo/fastapi/pull/10708) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/metadata.md`. PR [#10581](https://github.com/tiangolo/fastapi/pull/10581) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/testing.md`. PR [#10586](https://github.com/tiangolo/fastapi/pull/10586) by [@nilslindemann](https://github.com/nilslindemann). From de756f42fd4ef3dc0b6c045b1c339e9457088671 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:18:07 +0000 Subject: [PATCH 270/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d930d0f43..a7f4da466 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/templates.md`. PR [#10678](https://github.com/tiangolo/fastapi/pull/10678) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/oauth2-scopes.md`. PR [#10643](https://github.com/tiangolo/fastapi/pull/10643) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/async-tests.md`. PR [#10708](https://github.com/tiangolo/fastapi/pull/10708) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/metadata.md`. PR [#10581](https://github.com/tiangolo/fastapi/pull/10581) by [@nilslindemann](https://github.com/nilslindemann). From 19397b35dc2c328377dbb30c5e83a0a01ce07c28 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:18:45 +0000 Subject: [PATCH 271/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a7f4da466..9e7109560 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/alternatives.md`. PR [#10855](https://github.com/tiangolo/fastapi/pull/10855) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/templates.md`. PR [#10678](https://github.com/tiangolo/fastapi/pull/10678) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/oauth2-scopes.md`. PR [#10643](https://github.com/tiangolo/fastapi/pull/10643) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/async-tests.md`. PR [#10708](https://github.com/tiangolo/fastapi/pull/10708) by [@nilslindemann](https://github.com/nilslindemann). From 05c54c1cd9b9e728cc492e83ff868b17cc11ab13 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:19:30 +0000 Subject: [PATCH 272/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9e7109560..882b97892 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/body-updates.md`. PR [#10396](https://github.com/tiangolo/fastapi/pull/10396) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/alternatives.md`. PR [#10855](https://github.com/tiangolo/fastapi/pull/10855) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/templates.md`. PR [#10678](https://github.com/tiangolo/fastapi/pull/10678) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/oauth2-scopes.md`. PR [#10643](https://github.com/tiangolo/fastapi/pull/10643) by [@nilslindemann](https://github.com/nilslindemann). From f601756ab7f80a39e2190e2b0a97a330322cbb81 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:20:04 +0000 Subject: [PATCH 273/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 882b97892..1de48219c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/extra-models.md`. PR [#10351](https://github.com/tiangolo/fastapi/pull/10351) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/body-updates.md`. PR [#10396](https://github.com/tiangolo/fastapi/pull/10396) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/alternatives.md`. PR [#10855](https://github.com/tiangolo/fastapi/pull/10855) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/templates.md`. PR [#10678](https://github.com/tiangolo/fastapi/pull/10678) by [@nilslindemann](https://github.com/nilslindemann). From 51a6dd6114d39ac86f2e63ce47f029fa9b913b83 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:20:50 +0000 Subject: [PATCH 274/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1de48219c..cb90ebd35 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/response-model.md`. PR [#10345](https://github.com/tiangolo/fastapi/pull/10345) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/extra-models.md`. PR [#10351](https://github.com/tiangolo/fastapi/pull/10351) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/body-updates.md`. PR [#10396](https://github.com/tiangolo/fastapi/pull/10396) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/alternatives.md`. PR [#10855](https://github.com/tiangolo/fastapi/pull/10855) by [@nilslindemann](https://github.com/nilslindemann). From 090fcd68798fe544351186856863bd3b6ec59e33 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:21:36 +0000 Subject: [PATCH 275/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cb90ebd35..a0bf1c918 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/security/oauth2-jwt.md`. PR [#10522](https://github.com/tiangolo/fastapi/pull/10522) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/response-model.md`. PR [#10345](https://github.com/tiangolo/fastapi/pull/10345) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/extra-models.md`. PR [#10351](https://github.com/tiangolo/fastapi/pull/10351) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/body-updates.md`. PR [#10396](https://github.com/tiangolo/fastapi/pull/10396) by [@nilslindemann](https://github.com/nilslindemann). From 7e40dd9673c9e6908c19fb7d5a19011d1c6024f4 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:22:14 +0000 Subject: [PATCH 276/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a0bf1c918..976faed7c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/static-files.md`. PR [#10584](https://github.com/tiangolo/fastapi/pull/10584) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/oauth2-jwt.md`. PR [#10522](https://github.com/tiangolo/fastapi/pull/10522) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/response-model.md`. PR [#10345](https://github.com/tiangolo/fastapi/pull/10345) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/extra-models.md`. PR [#10351](https://github.com/tiangolo/fastapi/pull/10351) by [@nilslindemann](https://github.com/nilslindemann). From 9ad13c95a6cff7f011e0cebc7040af90bfc6402a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:22:47 +0000 Subject: [PATCH 277/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 976faed7c..4f8b6d880 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/path-operation-advanced-configuration.md`. PR [#10612](https://github.com/tiangolo/fastapi/pull/10612) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/static-files.md`. PR [#10584](https://github.com/tiangolo/fastapi/pull/10584) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/oauth2-jwt.md`. PR [#10522](https://github.com/tiangolo/fastapi/pull/10522) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/response-model.md`. PR [#10345](https://github.com/tiangolo/fastapi/pull/10345) by [@nilslindemann](https://github.com/nilslindemann). From a2ec91e205f2092f0ce72a09006d43d78ffe161c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:24:20 +0000 Subject: [PATCH 278/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4f8b6d880..1a6e10127 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/bigger-applications.md`. PR [#10554](https://github.com/tiangolo/fastapi/pull/10554) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/path-operation-advanced-configuration.md`. PR [#10612](https://github.com/tiangolo/fastapi/pull/10612) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/static-files.md`. PR [#10584](https://github.com/tiangolo/fastapi/pull/10584) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/security/oauth2-jwt.md`. PR [#10522](https://github.com/tiangolo/fastapi/pull/10522) by [@nilslindemann](https://github.com/nilslindemann). From e478f14fc4eaa03a93901e0b6bcf32f519e25036 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:24:55 +0000 Subject: [PATCH 279/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1a6e10127..97a64ec76 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#10651](https://github.com/tiangolo/fastapi/pull/10651) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/bigger-applications.md`. PR [#10554](https://github.com/tiangolo/fastapi/pull/10554) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/path-operation-advanced-configuration.md`. PR [#10612](https://github.com/tiangolo/fastapi/pull/10612) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/static-files.md`. PR [#10584](https://github.com/tiangolo/fastapi/pull/10584) by [@nilslindemann](https://github.com/nilslindemann). From b2cf3796805d6c1f466349dc95fa8232182fe1d7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:25:44 +0000 Subject: [PATCH 280/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 97a64ec76..1aa7c1a7a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update German translation for `docs/de/docs/index.md`. PR [#10283](https://github.com/tiangolo/fastapi/pull/10283) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#10651](https://github.com/tiangolo/fastapi/pull/10651) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/bigger-applications.md`. PR [#10554](https://github.com/tiangolo/fastapi/pull/10554) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/path-operation-advanced-configuration.md`. PR [#10612](https://github.com/tiangolo/fastapi/pull/10612) by [@nilslindemann](https://github.com/nilslindemann). From fdcf67c6aef24c39c850fd2ab0b9c1324b30c968 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:26:19 +0000 Subject: [PATCH 281/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1aa7c1a7a..b323637f1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/handling-errors.md`. PR [#10379](https://github.com/tiangolo/fastapi/pull/10379) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/index.md`. PR [#10283](https://github.com/tiangolo/fastapi/pull/10283) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#10651](https://github.com/tiangolo/fastapi/pull/10651) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/bigger-applications.md`. PR [#10554](https://github.com/tiangolo/fastapi/pull/10554) by [@nilslindemann](https://github.com/nilslindemann). From adae85259cda99ddeeb1fbdc02bef0f1fe94ff88 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:27:14 +0000 Subject: [PATCH 282/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b323637f1..191612cc2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/path-params.md`. PR [#10290](https://github.com/tiangolo/fastapi/pull/10290) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/handling-errors.md`. PR [#10379](https://github.com/tiangolo/fastapi/pull/10379) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/index.md`. PR [#10283](https://github.com/tiangolo/fastapi/pull/10283) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#10651](https://github.com/tiangolo/fastapi/pull/10651) by [@nilslindemann](https://github.com/nilslindemann). From 262e455496801dc2f61b4ebf3446167fd75f2038 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:27:47 +0000 Subject: [PATCH 283/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 191612cc2..512eb6f2d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update German translation for `docs/de/docs/python-types.md`. PR [#10287](https://github.com/tiangolo/fastapi/pull/10287) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/path-params.md`. PR [#10290](https://github.com/tiangolo/fastapi/pull/10290) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/handling-errors.md`. PR [#10379](https://github.com/tiangolo/fastapi/pull/10379) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/index.md`. PR [#10283](https://github.com/tiangolo/fastapi/pull/10283) by [@nilslindemann](https://github.com/nilslindemann). From 1aa2b75667035b5cefddc64300999c70107d6551 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:29:13 +0000 Subject: [PATCH 284/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 512eb6f2d..6afe3ecb0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/help-fastapi.md`. PR [#10455](https://github.com/tiangolo/fastapi/pull/10455) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/python-types.md`. PR [#10287](https://github.com/tiangolo/fastapi/pull/10287) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/path-params.md`. PR [#10290](https://github.com/tiangolo/fastapi/pull/10290) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/handling-errors.md`. PR [#10379](https://github.com/tiangolo/fastapi/pull/10379) by [@nilslindemann](https://github.com/nilslindemann). From 5df31886ade6be204c048ce211534eed13be733c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:29:44 +0000 Subject: [PATCH 285/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6afe3ecb0..0b813fc72 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/behind-a-proxy.md`. PR [#10675](https://github.com/tiangolo/fastapi/pull/10675) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/help-fastapi.md`. PR [#10455](https://github.com/tiangolo/fastapi/pull/10455) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/python-types.md`. PR [#10287](https://github.com/tiangolo/fastapi/pull/10287) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/tutorial/path-params.md`. PR [#10290](https://github.com/tiangolo/fastapi/pull/10290) by [@nilslindemann](https://github.com/nilslindemann). From b1067780d8fc05f934328dd47bcc7256229a013b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:30:30 +0000 Subject: [PATCH 286/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0b813fc72..f998939e8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/deployment/cloud.md`. PR [#10746](https://github.com/tiangolo/fastapi/pull/10746) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/behind-a-proxy.md`. PR [#10675](https://github.com/tiangolo/fastapi/pull/10675) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/help-fastapi.md`. PR [#10455](https://github.com/tiangolo/fastapi/pull/10455) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update German translation for `docs/de/docs/python-types.md`. PR [#10287](https://github.com/tiangolo/fastapi/pull/10287) by [@nilslindemann](https://github.com/nilslindemann). From af6558aa4008e53ac101390582d9c2e0882e195c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 21:31:50 +0000 Subject: [PATCH 287/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f998939e8..4c59aae8f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/advanced/events.md`. PR [#10693](https://github.com/tiangolo/fastapi/pull/10693) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/cloud.md`. PR [#10746](https://github.com/tiangolo/fastapi/pull/10746) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/behind-a-proxy.md`. PR [#10675](https://github.com/tiangolo/fastapi/pull/10675) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/help-fastapi.md`. PR [#10455](https://github.com/tiangolo/fastapi/pull/10455) by [@nilslindemann](https://github.com/nilslindemann). From f2778cf28c5ee5e0824e989fd715741024fe3a00 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 22:19:03 +0000 Subject: [PATCH 288/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4c59aae8f..6d842165c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/security/first-steps.md`. PR [#10432](https://github.com/tiangolo/fastapi/pull/10432) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/events.md`. PR [#10693](https://github.com/tiangolo/fastapi/pull/10693) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/cloud.md`. PR [#10746](https://github.com/tiangolo/fastapi/pull/10746) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/behind-a-proxy.md`. PR [#10675](https://github.com/tiangolo/fastapi/pull/10675) by [@nilslindemann](https://github.com/nilslindemann). From 2774e0fcd84aee6a537d98315d98e8476cc3650d Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:40:18 +0800 Subject: [PATCH 289/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/tutorial/response-status-code.md`=20(#3498?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/response-status-code.md | 88 ++++++++++--------- 1 file changed, 47 insertions(+), 41 deletions(-) diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index 357831942..cc23231b4 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -1,89 +1,95 @@ # 响应状态码 -与指定响应模型的方式相同,你也可以在以下任意的*路径操作*中使用 `status_code` 参数来声明用于响应的 HTTP 状态码: +与指定响应模型的方式相同,在以下任意*路径操作*中,可以使用 `status_code` 参数声明用于响应的 HTTP 状态码: * `@app.get()` * `@app.post()` * `@app.put()` * `@app.delete()` -* 等等。 +* 等…… ```Python hl_lines="6" {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note - 注意,`status_code` 是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 +!!! note "笔记" -`status_code` 参数接收一个表示 HTTP 状态码的数字。 + 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 -!!! info - `status_code` 也能够接收一个 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>。 +`status_code` 参数接收表示 HTTP 状态码的数字。 -它将会: +!!! info "说明" -* 在响应中返回该状态码。 -* 在 OpenAPI 模式中(以及在用户界面中)将其记录为: + `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>。 -<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image01.png"> +它可以: -!!! note - 一些响应状态码(请参阅下一部分)表示响应没有响应体。 +* 在响应中返回状态码 +* 在 OpenAPI 概图(及用户界面)中存档: - FastAPI 知道这一点,并将生成表明没有响应体的 OpenAPI 文档。 +<img src="/img/tutorial/response-status-code/image01.png"> + +!!! note "笔记" + + 某些响应状态码表示响应没有响应体(参阅下一章)。 + + FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 ## 关于 HTTP 状态码 -!!! note - 如果你已经了解什么是 HTTP 状态码,请跳到下一部分。 +!!! note "笔记" -在 HTTP 协议中,你将发送 3 位数的数字状态码作为响应的一部分。 + 如果已经了解 HTTP 状态码,请跳到下一章。 -这些状态码有一个识别它们的关联名称,但是重要的还是数字。 +在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。 -简而言之: +这些状态码都具有便于识别的关联名称,但是重要的还是数字。 -* `100` 及以上状态码用于「消息」响应。你很少直接使用它们。具有这些状态代码的响应不能带有响应体。 -* **`200`** 及以上状态码用于「成功」响应。这些是你最常使用的。 - * `200` 是默认状态代码,它表示一切「正常」。 - * 另一个例子会是 `201`,「已创建」。它通常在数据库中创建了一条新记录后使用。 - * 一个特殊的例子是 `204`,「无内容」。此响应在没有内容返回给客户端时使用,因此该响应不能包含响应体。 -* **`300`** 及以上状态码用于「重定向」。具有这些状态码的响应可能有或者可能没有响应体,但 `304`「未修改」是个例外,该响应不得含有响应体。 -* **`400`** 及以上状态码用于「客户端错误」响应。这些可能是你第二常使用的类型。 - * 一个例子是 `404`,用于「未找到」响应。 - * 对于来自客户端的一般错误,你可以只使用 `400`。 -* `500` 及以上状态码用于服务器端错误。你几乎永远不会直接使用它们。当你的应用程序代码或服务器中的某些部分出现问题时,它将自动返回这些状态代码之一。 +简言之: -!!! tip - 要了解有关每个状态代码以及适用场景的更多信息,请查看 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> 关于 HTTP 状态码的文档</a>。 +* `100` 及以上的状态码用于返回**信息**。这类状态码很少直接使用。具有这些状态码的响应不能包含响应体 +* **`200`** 及以上的状态码用于表示**成功**。这些状态码是最常用的 + * `200` 是默认状态代码,表示一切**正常** + * `201` 表示**已创建**,通常在数据库中创建新记录后使用 + * `204` 是一种特殊的例子,表示**无内容**。该响应在没有为客户端返回内容时使用,因此,该响应不能包含响应体 +* **`300`** 及以上的状态码用于**重定向**。具有这些状态码的响应不一定包含响应体,但 `304`**未修改**是个例外,该响应不得包含响应体 +* **`400`** 及以上的状态码用于表示**客户端错误**。这些可能是第二常用的类型 + * `404`,用于**未找到**响应 + * 对于来自客户端的一般错误,可以只使用 `400` +* `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码 -## 记住名称的捷径 +!!! tip "提示" -让我们再次看看之前的例子: + 状态码及适用场景的详情,请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN 的 HTTP 状态码</abbr>文档</a>。 + +## 状态码名称快捷方式 + +再看下之前的例子: ```Python hl_lines="6" {!../../../docs_src/response_status_code/tutorial001.py!} ``` -`201` 是表示「已创建」的状态码。 +`201` 表示**已创建**的状态码。 -但是你不必去记住每个代码的含义。 +但我们没有必要记住所有代码的含义。 -你可以使用来自 `fastapi.status` 的便捷变量。 +可以使用 `fastapi.status` 中的快捷变量。 ```Python hl_lines="1 6" {!../../../docs_src/response_status_code/tutorial002.py!} ``` -它们只是一种便捷方式,它们具有同样的数字代码,但是这样使用你就可以使用编辑器的自动补全功能来查找它们: +这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能: -<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image02.png"> +<img src="../../../../../../img/tutorial/response-status-code/image02.png"> !!! note "技术细节" - 你也可以使用 `from starlette import status`。 - 为了给你(即开发者)提供方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 + 也可以使用 `from starlette import status`。 + + 为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 ## 更改默认状态码 -稍后,在[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中你将了解如何返回与在此声明的默认状态码不同的状态码。 +[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中,将介绍如何返回与在此声明的默认状态码不同的状态码。 From 3c70d6f23112b317fcb1b17d799ef754eb1431b0 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:42:51 +0800 Subject: [PATCH 290/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/header-params.md`=20(#348?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/header-params.md | 57 ++++++++++++++------------ 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index 2701167b3..25dfeba87 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -1,10 +1,10 @@ # Header 参数 -你可以使用定义 `Query`, `Path` 和 `Cookie` 参数一样的方法定义 Header 参数。 +定义 `Header` 参数的方式与定义 `Query`、`Path`、`Cookie` 参数相同。 ## 导入 `Header` -首先导入 `Header`: +首先,导入 `Header`: === "Python 3.10+" @@ -44,9 +44,9 @@ ## 声明 `Header` 参数 -然后使用和`Path`, `Query` and `Cookie` 一样的结构定义 header 参数 +然后,使用和 `Path`、`Query`、`Cookie` 一样的结构定义 header 参数。 -第一个值是默认值,你可以传递所有的额外验证或注释参数: +第一个值是默认值,还可以传递所有验证参数或注释参数: === "Python 3.10+" @@ -85,28 +85,30 @@ ``` !!! note "技术细节" - `Header` 是 `Path`, `Query` 和 `Cookie` 的兄弟类型。它也继承自通用的 `Param` 类. - 但是请记得,当你从`fastapi`导入 `Query`, `Path`, `Header`, 或其他时,实际上导入的是返回特定类型的函数。 + `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 -!!! info - 为了声明headers, 你需要使用`Header`, 因为否则参数将被解释为查询参数。 + 注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 + +!!! info "说明" + + 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 ## 自动转换 -`Header` 在 `Path`, `Query` 和 `Cookie` 提供的功能之上有一点额外的功能。 +`Header` 比 `Path`、`Query` 和 `Cookie` 提供了更多功能。 -大多数标准的headers用 "连字符" 分隔,也称为 "减号" (`-`)。 +大部分标准请求头用**连字符**分隔,即**减号**(`-`)。 -但是像 `user-agent` 这样的变量在Python中是无效的。 +但是 `user-agent` 这样的变量在 Python 中是无效的。 -因此, 默认情况下, `Header` 将把参数名称的字符从下划线 (`_`) 转换为连字符 (`-`) 来提取并记录 headers. +因此,默认情况下,`Header` 把参数名中的字符由下划线(`_`)改为连字符(`-`)来提取并存档请求头 。 -同时,HTTP headers 是大小写不敏感的,因此,因此可以使用标准Python样式(也称为 "snake_case")声明它们。 +同时,HTTP 的请求头不区分大小写,可以使用 Python 标准样式(即 **snake_case**)进行声明。 -因此,您可以像通常在Python代码中那样使用 `user_agent` ,而不需要将首字母大写为 `User_Agent` 或类似的东西。 +因此,可以像在 Python 代码中一样使用 `user_agent` ,无需把首字母大写为 `User_Agent` 等形式。 -如果出于某些原因,你需要禁用下划线到连字符的自动转换,设置`Header`的参数 `convert_underscores` 为 `False`: +如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`: === "Python 3.10+" @@ -144,19 +146,20 @@ {!> ../../../docs_src/header_params/tutorial002.py!} ``` -!!! warning - 在设置 `convert_underscores` 为 `False` 之前,请记住,一些HTTP代理和服务器不允许使用带有下划线的headers。 +!!! warning "警告" + + 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 -## 重复的 headers +## 重复的请求头 -有可能收到重复的headers。这意味着,相同的header具有多个值。 +有时,可能需要接收重复的请求头。即同一个请求头有多个值。 -您可以在类型声明中使用一个list来定义这些情况。 +类型声明中可以使用 `list` 定义多个请求头。 -你可以通过一个Python `list` 的形式获得重复header的所有值。 +使用 Python `list` 可以接收重复请求头所有的值。 -比如, 为了声明一个 `X-Token` header 可以出现多次,你可以这样写: +例如,声明 `X-Token` 多次出现的请求头,可以写成这样: === "Python 3.10+" @@ -203,14 +206,14 @@ {!> ../../../docs_src/header_params/tutorial003.py!} ``` -如果你与*路径操作*通信时发送两个HTTP headers,就像: +与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头: ``` X-Token: foo X-Token: bar ``` -响应会是: +响应结果是: ```JSON { @@ -221,8 +224,8 @@ X-Token: bar } ``` -## 回顾 +## 小结 -使用 `Header` 来声明 header , 使用和 `Query`, `Path` 与 `Cookie` 相同的模式。 +使用 `Header` 声明请求头的方式与 `Query`、`Path` 、`Cookie` 相同。 -不用担心变量中的下划线,**FastAPI** 会负责转换它们。 +不用担心变量中的下划线,**FastAPI** 可以自动转换。 From 3c7cd6f85f17bf0f02ec599cd00966d9ce815295 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:43:06 +0800 Subject: [PATCH 291/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/cookie-params.md`=20(#348?= =?UTF-8?q?6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/cookie-params.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index f115f9677..8571422dd 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -1,10 +1,10 @@ # Cookie 参数 -你可以像定义 `Query` 参数和 `Path` 参数一样来定义 `Cookie` 参数。 + 定义 `Cookie` 参数与定义 `Query` 和 `Path` 参数一样。 ## 导入 `Cookie` -首先,导入 `Cookie`: +首先,导入 `Cookie`: === "Python 3.10+" @@ -44,9 +44,9 @@ ## 声明 `Cookie` 参数 -声明 `Cookie` 参数的结构与声明 `Query` 参数和 `Path` 参数时相同。 +声明 `Cookie` 参数的方式与声明 `Query` 和 `Path` 参数相同。 -第一个值是参数的默认值,同时也可以传递所有验证参数或注释参数,来校验参数: +第一个值是默认值,还可以传递所有验证参数或注释参数: === "Python 3.10+" @@ -86,13 +86,15 @@ ``` !!! note "技术细节" - `Cookie` 、`Path` 、`Query`是兄弟类,它们都继承自公共的 `Param` 类 - 但请记住,当你从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 或其他参数声明函数,这些实际上是返回特殊类的函数。 + `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 -!!! info - 你需要使用 `Cookie` 来声明 cookie 参数,否则参数将会被解释为查询参数。 + 注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 -## 总结 +!!! info "说明" -使用 `Cookie` 声明 cookie 参数,使用方式与 `Query` 和 `Path` 类似。 + 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 + +## 小结 + +使用 `Cookie` 声明 cookie 参数的方式与 `Query` 和 `Path` 相同。 From 6bee636f90b9ce99f56e5cb0b7b348524571fb7d Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:43:35 +0800 Subject: [PATCH 292/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/security/oauth2-scopes.md`?= =?UTF-8?q?=20(#3800)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../docs/advanced/security/oauth2-scopes.md | 276 ++++++++++++++++++ 1 file changed, 276 insertions(+) create mode 100644 docs/zh/docs/advanced/security/oauth2-scopes.md diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..e5eeffb0a --- /dev/null +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,276 @@ +# OAuth2 作用域 + +**FastAPI** 无缝集成 OAuth2 作用域(`Scopes`),可以直接使用。 + +作用域是更精密的权限系统,遵循 OAuth2 标准,与 OpenAPI 应用(和 API 自动文档)集成。 + +OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证应用使用的机制。这些身份验证应用在用户登录应用时使用 OAuth2 提供指定权限。 + +脸书、谷歌、GitHub、微软、推特就是 OAuth2 作用域登录。 + +本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 + +!!! warning "警告" + + 本章内容较难,刚接触 FastAPI 的新手可以跳过。 + + OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 + + 但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 + + 不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 + + 很多情况下,OAuth2 作用域就像一把牛刀。 + + 但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 + +## OAuth2 作用域与 OpenAPI + +OAuth2 规范的**作用域**是由空格分割的字符串组成的列表。 + +这些字符串支持任何格式,但不能包含空格。 + +作用域表示的是**权限**。 + +OpenAPI 中(例如 API 文档)可以定义**安全方案**。 + +这些安全方案在使用 OAuth2 时,还可以声明和使用作用域。 + +**作用域**只是(不带空格的)字符串。 + +常用于声明特定安全权限,例如: + +* 常见用例为,`users:read` 或 `users:write` +* 脸书和 Instagram 使用 `instagram_basic` +* 谷歌使用 `https://www.googleapis.com/auth/drive` + +!!! info "说明" + + OAuth2 中,**作用域**只是声明特定权限的字符串。 + + 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 + + 这些细节只是特定的实现方式。 + + 对 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!} +``` + +下面,我们逐步说明修改的代码内容。 + +## OAuth2 安全方案 + +第一个修改的地方是,使用两个作用域 `me` 和 `items ` 声明 OAuth2 安全方案。 + +`scopes` 参数接收**字典**,键是作用域、值是作用域的描述: + +```Python hl_lines="62-65" +{!../../../docs_src/security/tutorial005.py!} +``` + +因为声明了作用域,所以登录或授权时会在 API 文档中显示。 + +此处,选择给予访问权限的作用域: `me` 和 `items`。 + +这也是使用脸书、谷歌、GitHub 登录时的授权机制。 + +<img src="/img/tutorial/security/image11.png"> + +## JWT 令牌作用域 + +现在,修改令牌*路径操作*,返回请求的作用域。 + +此处仍然使用 `OAuth2PasswordRequestForm`。它包含类型为**字符串列表**的 `scopes` 属性,且`scopes` 属性中包含要在请求里接收的每个作用域。 + +这样,返回的 JWT 令牌中就包含了作用域。 + +!!! danger "危险" + + 为了简明起见,本例把接收的作用域直接添加到了令牌里。 + + 但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 + +```Python hl_lines="153" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 在*路径操作*与依赖项中声明作用域 + +接下来,为*路径操作* `/users/me/items/` 声明作用域 `items`。 + +为此,要从 `fastapi` 中导入并使用 `Security` 。 + +`Security` 声明依赖项的方式和 `Depends` 一样,但 `Security` 还能接收作用域(字符串)列表类型的参数 `scopes`。 + +此处使用与 `Depends` 相同的方式,把依赖项函数 `get_current_active_user` 传递给 `Security`。 + +同时,还传递了作用域**列表**,本例中只传递了一个作用域:`items`(此处支持传递更多作用域)。 + +依赖项函数 `get_current_active_user` 还能声明子依赖项,不仅可以使用 `Depends`,也可以使用 `Security`。声明子依赖项函数(`get_current_user`)及更多作用域。 + +本例要求使用作用域 `me`(还可以使用更多作用域)。 + +!!! note "笔记" + + 不必在不同位置添加不同的作用域。 + + 本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 + +```Python hl_lines="4 139 166" +{!../../../docs_src/security/tutorial005.py!} +``` + +!!! info "技术细节" + + `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 + + 但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 + + 但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 + +## 使用 `SecurityScopes` + +修改依赖项 `get_current_user`。 + +这是上面的依赖项使用的依赖项。 + +这里使用的也是之前创建的 OAuth2 方案,并把它声明为依赖项:`oauth2_scheme`。 + +该依赖项函数本身不需要作用域,因此,可以使用 `Depends` 和 `oauth2_scheme`。不需要指定安全作用域时,不必使用 `Security`。 + +此处还声明了从 `fastapin.security` 导入的 `SecurityScopes` 类型的特殊参数。 + +`SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 + +```Python hl_lines="8 105" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 使用 `scopes` + +参数 `security_scopes` 的类型是 `SecurityScopes`。 + +它的属性 `scopes` 是作用域列表,所有依赖项都把它作为子依赖项。也就是说所有**依赖**……这听起来有些绕,后文会有解释。 + +(类 `SecurityScopes` 的)`security_scopes` 对象还提供了单字符串类型的属性 `scope_str`,该属性是(要在本例中使用的)用空格分割的作用域。 + +此处还创建了后续代码中要复用(`raise`)的 `HTTPException` 。 + +该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 + +```Python hl_lines="105 107-115" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 校验 `username` 与数据形状 + +我们可以校验是否获取了 `username`,并抽取作用域。 + +然后,使用 Pydantic 模型校验数据(捕获 `ValidationError` 异常),如果读取 JWT 令牌或使用 Pydantic 模型验证数据时出错,就会触发之前创建的 `HTTPException` 异常。 + +对此,要使用新的属性 `scopes` 更新 Pydantic 模型 `TokenData`。 + +使用 Pydantic 验证数据可以确保数据中含有由作用域组成的**字符串列表**,以及 `username` 字符串等内容。 + +反之,如果使用**字典**或其它数据结构,就有可能在后面某些位置破坏应用,形成安全隐患。 + +还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 + +```Python hl_lines="46 116-127" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 校验 `scopes` + +接下来,校验所有依赖项和依赖要素(包括*路径操作*)所需的作用域。这些作用域包含在令牌的 `scopes` 里,如果不在其中就会触发 `HTTPException` 异常。 + +为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 + +```Python hl_lines="128-134" +{!../../../docs_src/security/tutorial005.py!} +``` + +## 依赖项树与作用域 + +再次查看这个依赖项树与作用域。 + +`get_current_active_user` 依赖项包含子依赖项 `get_current_user`,并在 `get_current_active_user`中声明了作用域 `"me"` 包含所需作用域列表 ,在 `security_scopes.scopes` 中传递给 `get_current_user`。 + +*路径操作*自身也声明了作用域,`"items"`,这也是 `security_scopes.scopes` 列表传递给 `get_current_user` 的。 + +依赖项与作用域的层级架构如下: + +* *路径操作* `read_own_items` 包含: + * 依赖项所需的作用域 `["items"]`: + * `get_current_active_user`: + * 依赖项函数 `get_current_active_user` 包含: + * 所需的作用域 `"me"` 包含依赖项: + * `get_current_user`: + * 依赖项函数 `get_current_user` 包含: + * 没有作用域需求其自身 + * 依赖项使用 `oauth2_scheme` + * `security_scopes` 参数的类型是 `SecurityScopes`: + * `security_scopes` 参数的属性 `scopes` 是包含上述声明的所有作用域的**列表**,因此: + * `security_scopes.scopes` 包含用于*路径操作*的 `["me", "items"]` + * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 + * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` + +!!! tip "提示" + + 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 + + 所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 + +## `SecurityScopes` 的更多细节 + +您可以任何位置或多个位置使用 `SecurityScopes`,不一定非得在**根**依赖项中使用。 + +它总是在当前 `Security` 依赖项中和所有依赖因子对于**特定** *路径操作*和**特定**依赖树中安全作用域 + +因为 `SecurityScopes` 包含所有由依赖项声明的作用域,可以在核心依赖函数中用它验证所需作用域的令牌,然后再在不同的*路径操作*中声明不同作用域需求。 + +它们会为每个*路径操作*进行单独检查。 + +## 查看文档 + +打开 API 文档,进行身份验证,并指定要授权的作用域。 + +<img src="/img/tutorial/security/image11.png"> + +没有选择任何作用域,也可以进行**身份验证**,但访问 `/uses/me` 或 `/users/me/items` 时,会显示没有足够的权限。但仍可以访问 `/status/`。 + +如果选择了作用域 `me`,但没有选择作用域 `items`,则可以访问 `/users/me/`,但不能访问 `/users/me/items`。 + +这就是通过用户提供的令牌使用第三方应用访问这些*路径操作*时会发生的情况,具体怎样取决于用户授予第三方应用的权限。 + +## 关于第三方集成 + +本例使用 OAuth2 **密码**流。 + +这种方式适用于登录我们自己的应用,最好使用我们自己的前端。 + +因为我们能控制自己的前端应用,可以信任它接收 `username` 与 `password`。 + +但如果构建的是连接其它应用的 OAuth2 应用,比如具有与脸书、谷歌、GitHub 相同功能的第三方身份验证应用。那您就应该使用其它安全流。 + +最常用的是隐式流。 + +最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 + +!!! note "笔记" + + 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 + + 但归根结底,它们使用的都是 OAuth2 标准。 + +**FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。 + +## 装饰器 `dependencies` 中的 `Security` + +同样,您可以在装饰器的 `dependencies` 参数中定义 `Depends` 列表,(详见[路径操作装饰器依赖项](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank})),也可以把 `scopes` 与 `Security` 一起使用。 From 32b5c3fbbb1d03c9425e67eeee018df7594c667c Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:43:48 +0800 Subject: [PATCH 293/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/security/http-basic-auth.md`?= =?UTF-8?q?=20(#3801)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../docs/advanced/security/http-basic-auth.md | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 docs/zh/docs/advanced/security/http-basic-auth.md diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..1f251ca45 --- /dev/null +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,107 @@ +# HTTP 基础授权 + +最简单的用例是使用 HTTP 基础授权(HTTP Basic Auth)。 + +在 HTTP 基础授权中,应用需要请求头包含用户名与密码。 + +如果没有接收到 HTTP 基础授权,就返回 HTTP 401 `"Unauthorized"` 错误。 + +并返回含 `Basic` 值的请求头 `WWW-Authenticate`以及可选的 `realm` 参数。 + +HTTP 基础授权让浏览器显示内置的用户名与密码提示。 + +输入用户名与密码后,浏览器会把它们自动发送至请求头。 + +## 简单的 HTTP 基础授权 + +* 导入 `HTTPBsic` 与 `HTTPBasicCredentials` +* 使用 `HTTPBsic` 创建**安全概图** +* 在*路径操作*的依赖项中使用 `security` +* 返回类型为 `HTTPBasicCredentials` 的对象: + * 包含发送的 `username` 与 `password` + +```Python hl_lines="2 6 10" +{!../../../docs_src/security/tutorial006.py!} +``` + +第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: + +<img src="/img/tutorial/security/image12.png"> + +## 检查用户名 + +以下是更完整的示例。 + +使用依赖项检查用户名与密码是否正确。 + +为此要使用 Python 标准模块 <a href="https://docs.python.org/3/library/secrets.html" class="external-link" target="_blank">`secrets`</a> 检查用户名与密码: + +```Python hl_lines="1 11-13" +{!../../../docs_src/security/tutorial007.py!} +``` + +这段代码确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。与以下代码类似: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Return some error + ... +``` + +但使用 `secrets.compare_digest()`,可以防御**时差攻击**,更加安全。 + +### 时差攻击 + +什么是**时差攻击**? + +假设攻击者试图猜出用户名与密码。 + +他们发送用户名为 `johndoe`,密码为 `love123` 的请求。 + +然后,Python 代码执行如下操作: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +但就在 Python 比较完 `johndoe` 的第一个字母 `j` 与 `stanleyjobson` 的 `s` 时,Python 就已经知道这两个字符串不相同了,它会这么想,**没必要浪费更多时间执行剩余字母的对比计算了**。应用立刻就会返回**错误的用户或密码**。 + +但接下来,攻击者继续尝试 `stanleyjobsox` 和 密码 `love123`。 + +应用代码会执行类似下面的操作: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +此时,Python 要对比 `stanleyjobsox` 与 `stanleyjobson` 中的 `stanleyjobso`,才能知道这两个字符串不一样。因此会多花费几微秒来返回**错误的用户或密码**。 + +#### 反应时间对攻击者的帮助 + +通过服务器花费了更多微秒才发送**错误的用户或密码**响应,攻击者会知道猜对了一些内容,起码开头字母是正确的。 + +然后,他们就可以放弃 `johndoe`,再用类似 `stanleyjobsox` 的内容进行尝试。 + +#### **专业**攻击 + +当然,攻击者不用手动操作,而是编写每秒能执行成千上万次测试的攻击程序,每次都会找到更多正确字符。 + +但是,在您的应用的**帮助**下,攻击者利用时间差,就能在几分钟或几小时内,以这种方式猜出正确的用户名和密码。 + +#### 使用 `secrets.compare_digest()` 修补 + +在此,代码中使用了 `secrets.compare_digest()`。 + +简单的说,它使用相同的时间对比 `stanleyjobsox` 和 `stanleyjobson`,还有 `johndoe` 和 `stanleyjobson`。对比密码时也一样。 + +在代码中使用 `secrets.compare_digest()` ,就可以安全地防御全面攻击了。 + +### 返回错误 + +检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: + +```Python hl_lines="15-19" +{!../../../docs_src/security/tutorial007.py!} +``` From 23ddb24279b9b54c69df0a14a901166950c05199 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:44:02 +0800 Subject: [PATCH 294/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/using-request-directly.md`?= =?UTF-8?q?=20(#3802)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../docs/advanced/using-request-directly.md | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 docs/zh/docs/advanced/using-request-directly.md diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..1842c2e27 --- /dev/null +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -0,0 +1,54 @@ +# 直接使用请求 + +至此,我们已经使用多种类型声明了请求的各种组件。 + +并从以下对象中提取数据: + +* 路径参数 +* 请求头 +* Cookies +* 等 + +**FastAPI** 使用这种方式验证数据、转换数据,并自动生成 API 文档。 + +但有时,我们也需要直接访问 `Request` 对象。 + +## `Request` 对象的细节 + +实际上,**FastAPI** 的底层是 **Starlette**,**FastAPI** 只不过是在 **Starlette** 顶层提供了一些工具,所以能直接使用 Starlette 的 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request`</a> 对象。 + +但直接从 `Request` 对象提取数据时(例如,读取请求体),**FastAPI** 不会验证、转换和存档数据(为 API 文档使用 OpenAPI)。 + +不过,仍可以验证、转换与注释(使用 Pydantic 模型的请求体等)其它正常声明的参数。 + +但在某些特定情况下,还是需要提取 `Request` 对象。 + +## 直接使用 `Request` 对象 + +假设要在*路径操作函数*中获取客户端 IP 地址和主机。 + +此时,需要直接访问请求。 + +```Python hl_lines="1 7-8" +{!../../../docs_src/using_request_directly/tutorial001.py!} +``` + +把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 + +!!! tip "提示" + + 注意,本例除了声明请求参数之外,还声明了路径参数。 + + 因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 + + 同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 + +## `Request` 文档 + +更多细节详见 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette 官档 - `Request` 对象</a>。 + +!!! note "技术细节" + + 您也可以使用 `from starlette.requests import Request`。 + + **FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 From bc6f4ae5eeb51c23b7b3a4469dfb4723dbf5ab03 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:44:14 +0800 Subject: [PATCH 295/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/dataclasses.md`=20(#3803)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/dataclasses.md | 99 ++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 docs/zh/docs/advanced/dataclasses.md diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md new file mode 100644 index 000000000..5a93877cc --- /dev/null +++ b/docs/zh/docs/advanced/dataclasses.md @@ -0,0 +1,99 @@ +# 使用数据类 + +FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 模型声明请求与响应。 + +但 FastAPI 还可以使用数据类(<a href="https://docs.python.org/3/library/dataclasses.html" class="external-link" target="_blank">`dataclasses`</a>): + +```Python hl_lines="1 7-12 19-20" +{!../../../docs_src/dataclasses/tutorial001.py!} +``` + +这还是借助于 **Pydantic** 及其<a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">内置的 `dataclasses`</a>。 + +因此,即便上述代码没有显式使用 Pydantic,FastAPI 仍会使用 Pydantic 把标准数据类转换为 Pydantic 数据类(`dataclasses`)。 + +并且,它仍然支持以下功能: + +* 数据验证 +* 数据序列化 +* 数据存档等 + +数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 + +!!! info "说明" + + 注意,数据类不支持 Pydantic 模型的所有功能。 + + 因此,开发时仍需要使用 Pydantic 模型。 + + 但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 + +## `response_model` 使用数据类 + +在 `response_model` 参数中使用 `dataclasses`: + +```Python hl_lines="1 7-13 19" +{!../../../docs_src/dataclasses/tutorial002.py!} +``` + +本例把数据类自动转换为 Pydantic 数据类。 + +API 文档中也会显示相关概图: + +<img src="/img/tutorial/dataclasses/image01.png"> + +## 在嵌套数据结构中使用数据类 + +您还可以把 `dataclasses` 与其它类型注解组合在一起,创建嵌套数据结构。 + +还有一些情况也可以使用 Pydantic 的 `dataclasses`。例如,在 API 文档中显示错误。 + +本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`: + +```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } +{!../../../docs_src/dataclasses/tutorial003.py!} +``` + +1. 本例依然要从标准的 `dataclasses` 中导入 `field`; + +2. 使用 `pydantic.dataclasses` 直接替换 `dataclasses`; + +3. `Author` 数据类包含 `Item` 数据类列表; + +4. `Author` 数据类用于 `response_model` 参数; + +5. 其它带有数据类的标准类型注解也可以作为请求体; + + 本例使用的是 `Item` 数据类列表; + +6. 这行代码返回的是包含 `items` 的字典,`items` 是数据类列表; + + FastAPI 仍能把数据<abbr title="把数据转换为可以传输的格式">序列化</abbr>为 JSON; + +7. 这行代码中,`response_model` 的类型注解是 `Author` 数据类列表; + + 再一次,可以把 `dataclasses` 与标准类型注解一起使用; + +8. 注意,*路径操作函数*使用的是普通函数,不是异步函数; + + 与往常一样,在 FastAPI 中,可以按需组合普通函数与异步函数; + + 如果不清楚何时使用异步函数或普通函数,请参阅**急不可待?**一节中对 <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank" class="internal-link">`async` 与 `await`</a> 的说明; + +9. *路径操作函数*返回的不是数据类(虽然它可以返回数据类),而是返回内含数据的字典列表; + + FastAPI 使用(包含数据类的) `response_model` 参数转换响应。 + +把 `dataclasses` 与其它类型注解组合在一起,可以组成不同形式的复杂数据结构。 + +更多内容详见上述代码内的注释。 + +## 深入学习 + +您还可以把 `dataclasses` 与其它 Pydantic 模型组合在一起,继承合并的模型,把它们包含在您自己的模型里。 + +详见 <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/" class="external-link" target="_blank">Pydantic 官档 - 数据类</a>。 + +## 版本 + +本章内容自 FastAPI `0.67.0` 版起生效。🔖 From 3e6c1e455bddff4b253d402486eea52056a0ec4b Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:44:27 +0800 Subject: [PATCH 296/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/middleware.md`=20(#3804)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/middleware.md | 100 ++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 docs/zh/docs/advanced/middleware.md diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md new file mode 100644 index 000000000..06232fe17 --- /dev/null +++ b/docs/zh/docs/advanced/middleware.md @@ -0,0 +1,100 @@ +# 高级中间件 + +用户指南介绍了如何为应用添加[自定义中间件](../tutorial/middleware.md){.internal-link target=_blank} 。 + +以及如何[使用 `CORSMiddleware` 处理 CORS](../tutorial/cors.md){.internal-link target=_blank}。 + +本章学习如何使用其它中间件。 + +## 添加 ASGI 中间件 + +因为 **FastAPI** 基于 Starlette,且执行 <abbr title="Asynchronous Server Gateway Interface,异步服务器网关界面">ASGI</abbr> 规范,所以可以使用任意 ASGI 中间件。 + +中间件不必是专为 FastAPI 或 Starlette 定制的,只要遵循 ASGI 规范即可。 + +总之,ASGI 中间件是类,并把 ASGI 应用作为第一个参数。 + +因此,有些第三方 ASGI 中间件的文档推荐以如下方式使用中间件: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +但 FastAPI(实际上是 Starlette)提供了一种更简单的方式,能让内部中间件在处理服务器错误的同时,还能让自定义异常处理器正常运作。 + +为此,要使用 `app.add_middleware()` (与 CORS 中的示例一样)。 + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` 的第一个参数是中间件的类,其它参数则是要传递给中间件的参数。 + +## 集成中间件 + +**FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 + +!!! note "技术细节" + + 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 + + **FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 + +## `HTTPSRedirectMiddleware` + +强制所有传入请求必须是 `https` 或 `wss`。 + +任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 + +```Python hl_lines="2 6" +{!../../../docs_src/advanced_middleware/tutorial001.py!} +``` + +## `TrustedHostMiddleware` + +强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 + +```Python hl_lines="2 6-8" +{!../../../docs_src/advanced_middleware/tutorial002.py!} +``` + +支持以下参数: + +* `allowed_hosts` - 允许的域名(主机名)列表。`*.example.com` 等通配符域名可以匹配子域名,或使用 `allowed_hosts=["*"]` 允许任意主机名,或省略中间件。 + +如果传入的请求没有通过验证,则发送 `400` 响应。 + +## `GZipMiddleware` + +处理 `Accept-Encoding` 请求头中包含 `gzip` 请求的 GZip 响应。 + +中间件会处理标准响应与流响应。 + +```Python hl_lines="2 6" +{!../../../docs_src/advanced_middleware/tutorial003.py!} +``` + +支持以下参数: + +* `minimum_size` - 小于最小字节的响应不使用 GZip。 默认值是 `500`。 + +## 其它中间件 + +除了上述中间件外,FastAPI 还支持其它ASGI 中间件。 + +例如: + +* <a href="https://docs.sentry.io/platforms/python/asgi/" class="external-link" target="_blank">Sentry</a> +* <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorn 的 `ProxyHeadersMiddleware`</a> +* <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">MessagePack</a> + +其它可用中间件详见 <a href="https://www.starlette.io/middleware/" class="external-link" target="_blank">Starlette 官档 - 中间件</a> 及 <a href="https://github.com/florimondmanca/awesome-asgi" class="external-link" target="_blank">ASGI Awesome 列表</a>。 From 8edc04f84c50e3d7420a9deb9791a980aff64247 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:44:40 +0800 Subject: [PATCH 297/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/async-sql-databases.md`=20(#?= =?UTF-8?q?3805)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/async-sql-databases.md | 167 +++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 docs/zh/docs/advanced/async-sql-databases.md diff --git a/docs/zh/docs/advanced/async-sql-databases.md b/docs/zh/docs/advanced/async-sql-databases.md new file mode 100644 index 000000000..c79877ada --- /dev/null +++ b/docs/zh/docs/advanced/async-sql-databases.md @@ -0,0 +1,167 @@ +# 异步 SQL 关系型数据库 + +**FastAPI** 使用 <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases`</a> 为连接数据库提供异步支持(`async` 与 `await`)。 + +`databases` 兼容以下数据库: + +* PostgreSQL +* MySQL +* SQLite + +本章示例使用 **SQLite**,它使用的是单文件,且 Python 内置集成了 SQLite,因此,可以直接复制并运行本章示例。 + +生产环境下,则要使用 **PostgreSQL** 等数据库服务器。 + +!!! tip "提示" + + 您可以使用 SQLAlchemy ORM([SQL 关系型数据库一章](../tutorial/sql-databases.md){.internal-link target=_blank})中的思路,比如,使用工具函数在数据库中执行操作,独立于 **FastAPI** 代码。 + + 本章不应用这些思路,等效于 <a href="https://www.starlette.io/database/" class="external-link" target="_blank">Starlette</a> 的对应内容。 + +## 导入与设置 `SQLAlchemy` + +* 导入 `SQLAlchemy` +* 创建 `metadata` 对象 +* 使用 `metadata` 对象创建 `notes` 表 + +```Python hl_lines="4 14 16-22" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +!!! tip "提示" + + 注意,上例是都是纯 SQLAlchemy Core 代码。 + + `databases` 还没有进行任何操作。 + +## 导入并设置 `databases` + +* 导入 `databases` +* 创建 `DATABASE_URL` +* 创建 `database` + +```Python hl_lines="3 9 12" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +!!! tip "提示" + + 连接 PostgreSQL 等数据库时,需要修改 `DATABASE_URL`。 + +## 创建表 + +本例中,使用 Python 文件创建表,但在生产环境中,应使用集成迁移等功能的 Alembic 创建表。 + +本例在启动 **FastAPI** 应用前,直接执行这些操作。 + +* 创建 `engine` +* 使用 `metadata` 对象创建所有表 + +```Python hl_lines="25-28" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +## 创建模型 + +创建以下 Pydantic 模型: + +* 创建笔记的模型(`NoteIn`) +* 返回笔记的模型(`Note`) + +```Python hl_lines="31-33 36-39" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +这两个 Pydantic 模型都可以辅助验证、序列化(转换)并注释(存档)输入的数据。 + +因此,API 文档会显示这些数据。 + +## 连接与断开 + +* 创建 `FastAPI` 应用 +* 创建事件处理器,执行数据库连接与断开操作 + +```Python hl_lines="42 45-47 50-52" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +## 读取笔记 + +创建读取笔记的*路径操作函数*: + +```Python hl_lines="55-58" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +!!! Note "笔记" + + 注意,本例与数据库通信时使用 `await`,因此*路径操作函数*要声明为异步函数(`asnyc`)。 + +### 注意 `response_model=List[Note]` + +`response_model=List[Note]` 使用的是 `typing.List`。 + +它以笔记(`Note`)列表的形式存档(及验证、序列化、筛选)输出的数据。 + +## 创建笔记 + +创建新建笔记的*路径操作函数*: + +```Python hl_lines="61-65" +{!../../../docs_src/async_sql_databases/tutorial001.py!} +``` + +!!! Note "笔记" + + 注意,本例与数据库通信时使用 `await`,因此要把*路径操作函数*声明为异步函数(`asnyc`)。 + +### 关于 `{**note.dict(), "id": last_record_id}` + +`note` 是 Pydantic `Note` 对象: + +`note.dict()` 返回包含如下数据的**字典**: + +```Python +{ + "text": "Some note", + "completed": False, +} +``` + +但它不包含 `id` 字段。 + +因此要新建一个包含 `note.dict()` 键值对的**字典**: + +```Python +{**note.dict()} +``` + +`**note.dict()` 直接**解包**键值对, 因此,`{**note.dict()}` 是 `note.dict()` 的副本。 + +然后,扩展`dict` 副本,添加键值对`"id": last_record_id`: + +```Python +{**note.dict(), "id": last_record_id} +``` + +最终返回的结果如下: + +```Python +{ + "id": 1, + "text": "Some note", + "completed": False, +} +``` + +## 查看文档 + +复制这些代码,查看文档 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs。</a> + +API 文档显示如下内容: + +<img src="/img/tutorial/async-sql-databases/image01.png"> + +## 更多说明 + +更多内容详见 <a href="https://github.com/encode/databases" class="external-link" target="_blank">Github 上的`encode/databases` 的说明</a>。 From cca48b39567b48ebc697e5da082ce33b257b1c0b Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:45:04 +0800 Subject: [PATCH 298/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/sub-applications.md`=20(#381?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/sub-applications.md | 73 +++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 docs/zh/docs/advanced/sub-applications.md diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md new file mode 100644 index 000000000..55651def5 --- /dev/null +++ b/docs/zh/docs/advanced/sub-applications.md @@ -0,0 +1,73 @@ +# 子应用 - 挂载 + +如果需要两个独立的 FastAPI 应用,拥有各自独立的 OpenAPI 与文档,则需设置一个主应用,并**挂载**一个(或多个)子应用。 + +## 挂载 **FastAPI** 应用 + +**挂载**是指在特定路径中添加完全**独立**的应用,然后在该路径下使用*路径操作*声明的子应用处理所有事务。 + +### 顶层应用 + +首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: + +```Python hl_lines="3 6-8" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### 子应用 + +接下来,创建子应用及其*路径操作*。 + +子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: + +```Python hl_lines="11 14-16" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### 挂载子应用 + +在顶层应用 `app` 中,挂载子应用 `subapi`。 + +本例的子应用挂载在 `/subapi` 路径下: + +```Python hl_lines="11 19" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### 查看文档 + +如果主文件是 `main.py`,则用以下 `uvicorn` 命令运行主应用: + +<div class="termy"> + +```console +$ uvicorn main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +查看文档 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs。</a> + +下图显示的是主应用 API 文档,只包括其自有的*路径操作*。 + +<img src="/img/tutorial/sub-applications/image01.png"> + +然后查看子应用文档 <a href="http://127.0.0.1:8000/subapi/docs" class="external-link" target="_blank">http://127.0.0.1:8000/subapi/docs。</a> + +下图显示的是子应用的 API 文档,也是只包括其自有的*路径操作*,所有这些路径操作都在 `/subapi` 子路径前缀下。 + +<img src="/img/tutorial/sub-applications/image02.png"> + +两个用户界面都可以正常运行,因为浏览器能够与每个指定的应用或子应用会话。 + +### 技术细节:`root_path` + +以上述方式挂载子应用时,FastAPI 使用 ASGI 规范中的 `root_path` 机制处理挂载子应用路径之间的通信。 + +这样,子应用就可以为自动文档使用路径前缀。 + +并且子应用还可以再挂载子应用,一切都会正常运行,FastAPI 可以自动处理所有 `root_path`。 + +关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](./behind-a-proxy.md){.internal-link target=_blank}一章。 From 807cb3e2ee233f9fc38353132f16c966631105f5 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:45:16 +0800 Subject: [PATCH 299/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/templates.md`=20(#3812)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/templates.md | 94 ++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 docs/zh/docs/advanced/templates.md diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md new file mode 100644 index 000000000..d735f1697 --- /dev/null +++ b/docs/zh/docs/advanced/templates.md @@ -0,0 +1,94 @@ +# 模板 + +**FastAPI** 支持多种模板引擎。 + +Flask 等工具使用的 Jinja2 是最用的模板引擎。 + +在 Starlette 的支持下,**FastAPI** 应用可以直接使用工具轻易地配置 Jinja2。 + +## 安装依赖项 + +安装 `jinja2`: + +<div class="termy"> + +```console +$ pip install jinja2 + +---> 100% +``` + +</div> + +如需使用静态文件,还要安装 `aiofiles`: + +<div class="termy"> + +```console +$ pip install aiofiles + +---> 100% +``` + +</div> + +## 使用 `Jinja2Templates` + +* 导入 `Jinja2Templates` +* 创建可复用的 `templates` 对象 +* 在返回模板的*路径操作*中声明 `Request` 参数 +* 使用 `templates` 渲染并返回 `TemplateResponse`, 以键值对方式在 Jinja2 的 **context** 中传递 `request` + +```Python hl_lines="4 11 15-16" +{!../../../docs_src/templates/tutorial001.py!} +``` + +!!! note "笔记" + + 注意,必须为 Jinja2 以键值对方式在上下文中传递 `request`。因此,还要在*路径操作*中声明。 + +!!! tip "提示" + + 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 + +!!! note "技术细节" + + 您还可以使用 `from starlette.templating import Jinja2Templates`。 + + **FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 + +## 编写模板 + +编写模板 `templates/item.html`,代码如下: + +```jinja hl_lines="7" +{!../../../docs_src/templates/templates/item.html!} +``` + +它会显示从 **context** 字典中提取的 `id`: + +```Python +{"request": request, "id": id} +``` + +## 模板与静态文件 + +在模板内部使用 `url_for()`,例如,与挂载的 `StaticFiles` 一起使用。 + +```jinja hl_lines="4" +{!../../../docs_src/templates/templates/item.html!} +``` + +本例中,使用 `url_for()` 为模板添加 CSS 文件 `static/styles.css` 链接: + +```CSS hl_lines="4" +{!../../../docs_src/templates/static/styles.css!} +``` + +因为使用了 `StaticFiles`, **FastAPI** 应用自动提供位于 URL `/static/styles.css` + +的 CSS 文件。 + +## 更多说明 + +包括测试模板等更多详情,请参阅 <a href="https://www.starlette.io/templates/" class="external-link" target="_blank">Starlette 官档 - 模板</a>。 From ca4da93cf285a7ef7b1081d97574d73d116b4c32 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:45:29 +0800 Subject: [PATCH 300/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/external-links.md`=20(#3833)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/zh/docs/external-links.md | 83 ++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 docs/zh/docs/external-links.md diff --git a/docs/zh/docs/external-links.md b/docs/zh/docs/external-links.md new file mode 100644 index 000000000..8c919fa38 --- /dev/null +++ b/docs/zh/docs/external-links.md @@ -0,0 +1,83 @@ +# 外部链接与文章 + +**FastAPI** 社区正在不断壮大。 + +有关 **FastAPI** 的帖子、文章、工具和项目越来越多。 + +以下是 **FastAPI** 各种资源的不完整列表。 + +!!! tip "提示" + + 如果您的文章、项目、工具或其它任何与 **FastAPI** 相关的内容尚未收入此表,请在此创建 <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">PR</a>。 + +## 文章 + +### 英文 + +{% if external_links %} +{% for article in external_links.articles.english %} + +* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. +{% endfor %} +{% endif %} + +### 日文 + +{% if external_links %} +{% for article in external_links.articles.japanese %} + +* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. +{% endfor %} +{% endif %} + +### 越南语 + +{% if external_links %} +{% for article in external_links.articles.vietnamese %} + +* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. +{% endfor %} +{% endif %} + +### 俄语 + +{% if external_links %} +{% for article in external_links.articles.russian %} + +* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. +{% endfor %} +{% endif %} + +### 德语 + +{% if external_links %} +{% for article in external_links.articles.german %} + +* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. +{% endfor %} +{% endif %} + +## 播客 + +{% if external_links %} +{% for article in external_links.podcasts.english %} + +* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. +{% endfor %} +{% endif %} + +## 访谈 + +{% if external_links %} +{% for article in external_links.talks.english %} + +* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. +{% endfor %} +{% endif %} + +## 项目 + +GitHub 上最新的 `fastapi` 主题项目: + +<div class="github-topic-projects"> +</div> From 1faf30d1d5feb705771c024180c7d8739b356361 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:45:40 +0800 Subject: [PATCH 301/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/custom-request-and-route.md`?= =?UTF-8?q?=20(#3816)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../docs/advanced/custom-request-and-route.md | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 docs/zh/docs/advanced/custom-request-and-route.md diff --git a/docs/zh/docs/advanced/custom-request-and-route.md b/docs/zh/docs/advanced/custom-request-and-route.md new file mode 100644 index 000000000..0a0257d08 --- /dev/null +++ b/docs/zh/docs/advanced/custom-request-and-route.md @@ -0,0 +1,113 @@ +# 自定义请求与 APIRoute 类 + +有时,我们要覆盖 `Request` 与 `APIRoute` 类使用的逻辑。 + +尤其是中间件里的逻辑。 + +例如,在应用处理请求体前,预先读取或操控请求体。 + +!!! danger "危险" + + 本章内容**较难**。 + + **FastAPI** 新手可跳过本章。 + +## 用例 + +常见用例如下: + +* 把 <a href="https://msgpack.org/index.html" class="external-link" target="_blank">`msgpack`</a> 等非 JSON 请求体转换为 JSON +* 解压 gzip 压缩的请求体 +* 自动记录所有请求体的日志 + +## 处理自定义请求体编码 + +下面学习如何使用自定义 `Request` 子类压缩 gizp 请求。 + +并在自定义请求的类中使用 `APIRoute` 子类。 + +### 创建自定义 `GzipRequest` 类 + +!!! tip "提示" + + 本例只是为了说明 `GzipRequest` 类如何运作。如需 Gzip 支持,请使用 [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}。 + +首先,创建 `GzipRequest` 类,覆盖解压请求头中请求体的 `Request.body()` 方法。 + +请求头中没有 `gzip` 时,`GzipRequest` 不会解压请求体。 + +这样就可以让同一个路由类处理 gzip 压缩的请求或未压缩的请求。 + +```Python hl_lines="8-15" +{!../../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +### 创建自定义 `GzipRoute` 类 + +接下来,创建使用 `GzipRequest` 的 `fastapi.routing.APIRoute ` 的自定义子类。 + +此时,这个自定义子类会覆盖 `APIRoute.get_route_handler()`。 + +`APIRoute.get_route_handler()` 方法返回的是函数,并且返回的函数接收请求并返回响应。 + +本例用它根据原始请求创建 `GzipRequest`。 + +```Python hl_lines="18-26" +{!../../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +!!! note "技术细节" + + `Request` 的 `request.scope` 属性是包含关联请求元数据的字典。 + + `Request` 的 `request.receive` 方法是**接收**请求体的函数。 + + `scope` 字典与 `receive` 函数都是 ASGI 规范的内容。 + + `scope` 与 `receive` 也是创建新的 `Request` 实例所需的。 + + `Request` 的更多内容详见 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette 官档 - 请求</a>。 + +`GzipRequest.get_route_handler` 返回函数的唯一区别是把 `Request` 转换成了 `GzipRequest`。 + +如此一来,`GzipRequest` 把数据传递给*路径操作*前,就会解压数据(如需)。 + +之后,所有处理逻辑都一样。 + +但因为改变了 `GzipRequest.body`,**FastAPI** 加载请求体时会自动解压。 + +## 在异常处理器中访问请求体 + +!!! tip "提示" + + 为了解决同样的问题,在 `RequestValidationError` 的自定义处理器使用 `body` ([处理错误](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank})可能会更容易。 + + 但本例仍然可行,而且本例展示了如何与内部组件进行交互。 + +同样也可以在异常处理器中访问请求体。 + +此时要做的只是处理 `try`/`except` 中的请求: + +```Python hl_lines="13 15" +{!../../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +发生异常时,`Request` 实例仍在作用域内,因此处理错误时可以读取和使用请求体: + +```Python hl_lines="16-18" +{!../../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +## 在路由中自定义 `APIRoute` 类 + +您还可以设置 `APIRoute` 的 `route_class` 参数: + +```Python hl_lines="26" +{!../../../docs_src/custom_request_and_route/tutorial003.py!} +``` + +本例中,*路径操作*下的 `router` 使用自定义的 `TimedRoute` 类,并在响应中包含输出生成响应时间的 `X-Response-Time` 响应头: + +```Python hl_lines="13-20" +{!../../../docs_src/custom_request_and_route/tutorial003.py!} +``` From 3cf500da06271b40f1db915233ca25ef472b93c0 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:45:53 +0800 Subject: [PATCH 302/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/testing-dependencies.md`=20(?= =?UTF-8?q?#3819)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/testing-dependencies.md | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 docs/zh/docs/advanced/testing-dependencies.md diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..dc0f88b33 --- /dev/null +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -0,0 +1,51 @@ +# 测试依赖项 + +## 测试时覆盖依赖项 + +有些场景下,您可能需要在测试时覆盖依赖项。 + +即不希望运行原有依赖项(及其子依赖项)。 + +反之,要在测试期间(或只是为某些特定测试)提供只用于测试的依赖项,并使用此依赖项的值替换原有依赖项的值。 + +### 用例:外部服务 + +常见实例是调用外部第三方身份验证应用。 + +向第三方应用发送令牌,然后返回经验证的用户。 + +但第三方服务商处理每次请求都可能会收费,并且耗时通常也比调用写死的模拟测试用户更长。 + +一般只要测试一次外部验证应用就够了,不必每次测试都去调用。 + +此时,最好覆盖调用外部验证应用的依赖项,使用返回模拟测试用户的自定义依赖项就可以了。 + +### 使用 `app.dependency_overrides` 属性 + +对于这些用例,**FastAPI** 应用支持 `app.dependcy_overrides` 属性,该属性就是**字典**。 + +要在测试时覆盖原有依赖项,这个字典的键应当是原依赖项(函数),值是覆盖依赖项(另一个函数)。 + +这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 + +```Python hl_lines="26-27 30" +{!../../../docs_src/dependency_testing/tutorial001.py!} +``` + +!!! tip "提示" + + **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 + + 原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 + + FastAPI 可以覆盖这些位置的依赖项。 + +然后,使用 `app.dependency_overrides` 把覆盖依赖项重置为空**字典**: + +```Python +app.dependency_overrides = {} +``` + +!!! tip "提示" + + 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 From 0e0bae46b5f0b03b082b9dd30ace2233922d772c Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:46:12 +0800 Subject: [PATCH 303/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/extending-openapi.md`=20(#38?= =?UTF-8?q?23)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/extending-openapi.md | 252 +++++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 docs/zh/docs/advanced/extending-openapi.md diff --git a/docs/zh/docs/advanced/extending-openapi.md b/docs/zh/docs/advanced/extending-openapi.md new file mode 100644 index 000000000..466961462 --- /dev/null +++ b/docs/zh/docs/advanced/extending-openapi.md @@ -0,0 +1,252 @@ +# 扩展 OpenAPI + +!!! warning "警告" + + 本章介绍的功能较难,您可以跳过阅读。 + + 如果您刚开始学习**用户指南**,最好跳过本章。 + + 如果您确定要修改 OpenAPI 概图,请继续阅读。 + +某些情况下,我们需要修改 OpenAPI 概图。 + +本章介绍如何修改 OpenAPI 概图。 + +## 常规流程 + +常规(默认)流程如下。 + +`FastAPI` 应用(实例)提供了返回 OpenAPI 概图的 `.openapi()` 方法。 + +作为应用对象创建的组成部分,要注册 `/openapi.json` (或其它为 `openapi_url` 设置的任意内容)*路径操作*。 + +它只返回包含应用的 `.openapi()` 方法操作结果的 JSON 响应。 + +但默认情况下,`.openapi()` 只是检查 `.openapi_schema` 属性是否包含内容,并返回其中的内容。 + +如果 `.openapi_schema` 属性没有内容,该方法就使用 `fastapi.openapi.utils.get_openapi` 工具函数生成内容。 + +`get_openapi()` 函数接收如下参数: + +* `title`:文档中显示的 OpenAPI 标题 +* `version`:API 的版本号,例如 `2.5.0` +* `openapi_version`: OpenAPI 规范的版本号,默认为最新版: `3.0.2` +* `description`:API 的描述说明 +* `routes`:路由列表,每个路由都是注册的*路径操作*。这些路由是从 `app.routes` 中提取的。 + +## 覆盖默认值 + +`get_openapi()` 工具函数还可以用于生成 OpenAPI 概图,并利用上述信息参数覆盖指定的内容。 + +例如,使用 <a href="https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo" class="external-link" target="_blank">ReDoc 的 OpenAPI 扩展添加自定义 Logo</a>。 + +### 常规 **FastAPI** + +首先,编写常规 **FastAPI** 应用: + +```Python hl_lines="1 4 7-9" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 生成 OpenAPI 概图 + +然后,在 `custom_openapi()` 函数里使用 `get_openapi()` 工具函数生成 OpenAPI 概图: + +```Python hl_lines="2 15-20" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 修改 OpenAPI 概图 + +添加 ReDoc 扩展信息,为 OpenAPI 概图里的 `info` **对象**添加自定义 `x-logo`: + +```Python hl_lines="21-23" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 缓存 OpenAPI 概图 + +把 `.openapi_schema` 属性当作**缓存**,存储生成的概图。 + +通过这种方式,**FastAPI** 应用不必在用户每次打开 API 文档时反复生成概图。 + +只需生成一次,下次请求时就可以使用缓存的概图。 + +```Python hl_lines="13-14 24-25" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 覆盖方法 + +用新函数替换 `.openapi()` 方法。 + +```Python hl_lines="28" +{!../../../docs_src/extending_openapi/tutorial001.py!} +``` + +### 查看文档 + +打开 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc,查看</a>自定义 Logo(本例中是 **FastAPI** 的 Logo): + +<img src="/img/tutorial/extending-openapi/image01.png"> + +## 文档 JavaScript 与 CSS 自托管 + +FastAPI 支持 **Swagger UI** 和 **ReDoc** 两种 API 文档,这两种文档都需要调用 JavaScript 与 CSS 文件。 + +这些文件默认由 <abbr title="Content Delivery Network(内容分发网络): 由多台服务器为 JavaScript 和 CSS 等静态文件支持的服务。一般来说,从靠近客户端的服务器提供静态文件服务可以提高性能。">CDN</abbr> 提供支持服务。 + +但也可以自定义设置指定的 CDN 或自行提供文件服务。 + +这种做法很常用,例如,在没有联网或本地局域网时也能让应用在离线状态下正常运行。 + +本文介绍如何为 FastAPI 应用提供文件自托管服务,并设置文档使用这些文件。 + +### 项目文件架构 + +假设项目文件架构如下: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +接下来,创建存储静态文件的文件夹。 + +新的文件架构如下: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +└── static/ +``` + +### 下载文件 + +下载文档所需的静态文件,把文件放到 `static/` 文件夹里。 + +右键点击链接,选择**另存为...**。 + +**Swagger UI** 使用如下文件: + +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a> +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a> + +**ReDoc** 使用如下文件: + +* <a href="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js" class="external-link" target="_blank">`redoc.standalone.js`</a> + +保存好后,文件架构所示如下: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### 安装 `aiofiles` + +现在,安装 `aiofiles`: + + +<div class="termy"> + +```console +$ pip install aiofiles + +---> 100% +``` + +</div> + +### 静态文件服务 + +* 导入 `StaticFiles` +* 在指定路径下**挂载** `StaticFiles()` 实例 + +```Python hl_lines="7 11" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +### 测试静态文件 + +启动应用,打开 <a href="http://127.0.0.1:8000/static/redoc.standalone.js" class="external-link" target="_blank">http://127.0.0.1:8000/static/redoc.standalone.js。</a> + +就能看到 **ReDoc** 的 JavaScript 文件。 + +该文件开头如下: + +```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 + +... +``` + +能打开这个文件就表示 FastAPI 应用能提供静态文件服务,并且文档要调用的静态文件放到了正确的位置。 + +接下来,使用静态文件配置文档。 + +### 禁用 API 文档 + +第一步是禁用 API 文档,就是使用 CDN 的默认文档。 + +创建 `FastAPI` 应用时把文档的 URL 设置为 `None` 即可禁用默认文档: + +```Python hl_lines="9" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +### 添加自定义文档 + +现在,创建自定义文档的*路径操作*。 + +导入 FastAPI 内部函数为文档创建 HTML 页面,并把所需参数传递给这些函数: + +* `openapi_url`: API 文档获取 OpenAPI 概图的 HTML 页面,此处可使用 `app.openapi_url` +* `title`:API 的标题 +* `oauth2_redirect_url`:此处使用 `app.swagger_ui_oauth2_redirect_url` 作为默认值 +* `swagger_js_url`:Swagger UI 文档所需 **JavaScript** 文件的 URL,即为应用提供服务的文件 +* `swagger_css_url`:Swagger UI 文档所需 **CSS** 文件的 URL,即为应用提供服务的文件 + +添加 ReDoc 文档的方式与此类似…… + +```Python hl_lines="2-6 14-22 25-27 30-36" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +!!! tip "提示" + + `swagger_ui_redirect` 的*路径操作*是 OAuth2 的辅助函数。 + + 集成 API 与 OAuth2 第三方应用时,您能进行身份验证,使用请求凭证返回 API 文档,并使用真正的 OAuth2 身份验证与 API 文档进行交互操作。 + + Swagger UI 在后台进行处理,但它需要这个**重定向**辅助函数。 + +### 创建测试*路径操作* + +现在,测试各项功能是否能顺利运行。创建*路径操作*: + +```Python hl_lines="39-41" +{!../../../docs_src/extending_openapi/tutorial002.py!} +``` + +### 测试文档 + +断开 WiFi 连接,打开 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs,刷新页面。</a> + +现在,就算没有联网也能查看并操作 API 文档。 From ae315b7f1a7bdf5196ece0b3dbcc3f95d308391d Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:46:28 +0800 Subject: [PATCH 304/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/openapi-callbacks.md`=20(#38?= =?UTF-8?q?25)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/openapi-callbacks.md | 184 +++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 docs/zh/docs/advanced/openapi-callbacks.md diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..e2dadbfb0 --- /dev/null +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -0,0 +1,184 @@ +# OpenAPI 回调 + +您可以创建触发外部 API 请求的*路径操作* API,这个外部 API 可以是别人创建的,也可以是由您自己创建的。 + +API 应用调用外部 API 时的流程叫做**回调**。因为外部开发者编写的软件发送请求至您的 API,然后您的 API 要进行回调,并把请求发送至外部 API。 + +此时,我们需要存档外部 API 的*信息*,比如应该有哪些*路径操作*,返回什么样的请求体,应该返回哪种响应等。 + +## 使用回调的应用 + +示例如下。 + +假设要开发一个创建发票的应用。 + +发票包括 `id`、`title`(可选)、`customer`、`total` 等属性。 + +API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建一条发票记录。 + +(假设)您的 API 将: + +* 把发票发送至外部开发者的消费者 +* 归集现金 +* 把通知发送至 API 的用户(外部开发者) + * 通过(从您的 API)发送 POST 请求至外部 API (即**回调**)来完成 + +## 常规 **FastAPI** 应用 + +添加回调前,首先看下常规 API 应用是什么样子。 + +常规 API 应用包含接收 `Invoice` 请求体的*路径操作*,还有包含回调 URL 的查询参数 `callback_url`。 + +这部分代码很常规,您对绝大多数代码应该都比较熟悉了: + +```Python hl_lines="10-14 37-54" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +!!! tip "提示" + + `callback_url` 查询参数使用 Pydantic 的 <a href="https://pydantic-docs.helpmanual.io/usage/types/#urls" class="external-link" target="_blank">URL</a> 类型。 + +此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。 + +## 存档回调 + +实际的回调代码高度依赖于您自己的 API 应用。 + +并且可能每个应用都各不相同。 + +回调代码可能只有一两行,比如: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +但回调最重要的部分可能是,根据 API 要发送给回调请求体的数据等内容,确保您的 API 用户(外部开发者)正确地实现*外部 API*。 + +因此,我们下一步要做的就是添加代码,为从 API 接收回调的*外部 API*存档。 + +这部分文档在 `/docs` 下的 Swagger API 文档中显示,并且会告诉外部开发者如何构建*外部 API*。 + +本例没有实现回调本身(只是一行代码),只有文档部分。 + +!!! tip "提示" + + 实际的回调只是 HTTP 请求。 + + 实现回调时,要使用 <a href="https://www.encode.io/httpx/" class="external-link" target="_blank">HTTPX</a> 或 <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>。 + +## 编写回调文档代码 + +应用不执行这部分代码,只是用它来*记录 外部 API* 。 + +但,您已经知道用 **FastAPI** 创建自动 API 文档有多简单了。 + +我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 + +!!! tip "提示" + + 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 + + 临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 + +### 创建回调的 `APIRouter` + +首先,新建包含一些用于回调的 `APIRouter`。 + +```Python hl_lines="5 26" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +### 创建回调*路径操作* + +创建回调*路径操作*也使用之前创建的 `APIRouter`。 + +它看起来和常规 FastAPI *路径操作*差不多: + +* 声明要接收的请求体,例如,`body: InvoiceEvent` +* 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` + +```Python hl_lines="17-19 22-23 29-33" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +回调*路径操作*与常规*路径操作*有两点主要区别: + +* 它不需要任何实际的代码,因为应用不会调用这段代码。它只是用于存档*外部 API*。因此,函数的内容只需要 `pass` 就可以了 +* *路径*可以包含 <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#key-expression" class="external-link" target="_blank">OpenAPI 3 表达式</a>(详见下文),可以使用带参数的变量,以及发送至您的 API 的原始请求的部分 + +### 回调路径表达式 + +回调*路径*支持包含发送给您的 API 的原始请求的部分的 <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#key-expression" class="external-link" target="_blank">OpenAPI 3 表达式</a>。 + +本例中是**字符串**: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +因此,如果您的 API 用户(外部开发者)发送请求到您的 API: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +使用如下 JSON 请求体: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +然后,您的 API 就会处理发票,并在某个点之后,发送回调请求至 `callback_url`(外部 API): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +JSON 请求体包含如下内容: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +它会预期*外部 API* 的响应包含如下 JSON 请求体: + +```JSON +{ + "ok": true +} +``` + +!!! tip "提示" + + 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 + +### 添加回调路由 + +至此,在上文创建的回调路由里就包含了*回调路径操作*(外部开发者要在外部 API 中实现)。 + +现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): + +```Python hl_lines="36" +{!../../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +!!! tip "提示" + + 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 + +### 查看文档 + +现在,使用 Uvicorn 启动应用,打开 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs。</a> + +就能看到文档的*路径操作*已经包含了**回调**的内容以及*外部 API*: + +<img src="/img/tutorial/openapi-callbacks/image01.png"> From e99a15db7637885506ac878d093dc6b905c17e68 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Sun, 31 Mar 2024 06:46:46 +0800 Subject: [PATCH 305/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/security/get-current-user?= =?UTF-8?q?.md`=20(#3842)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../tutorial/security/get-current-user.md | 86 ++++++++++--------- 1 file changed, 44 insertions(+), 42 deletions(-) diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md index 477baec3a..1f17f5bd9 100644 --- a/docs/zh/docs/tutorial/security/get-current-user.md +++ b/docs/zh/docs/tutorial/security/get-current-user.md @@ -1,35 +1,35 @@ # 获取当前用户 -在上一章节中,(基于依赖项注入系统的)安全系统向*路径操作函数*提供了一个 `str` 类型的 `token`: +上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`: ```Python hl_lines="10" {!../../../docs_src/security/tutorial001.py!} ``` -但这还不是很实用。 +但这并不实用。 -让我们来使它返回当前用户给我们。 +接下来,我们学习如何返回当前用户。 -## 创建一个用户模型 +## 创建用户模型 -首先,让我们来创建一个用户 Pydantic 模型。 +首先,创建 Pydantic 用户模型。 -与使用 Pydantic 声明请求体的方式相同,我们可以在其他任何地方使用它: +与使用 Pydantic 声明请求体相同,并且可在任何位置使用: ```Python hl_lines="5 12-16" {!../../../docs_src/security/tutorial002.py!} ``` -## 创建一个 `get_current_user` 依赖项 +## 创建 `get_current_user` 依赖项 -让我们来创建一个 `get_current_user` 依赖项。 +创建 `get_current_user` 依赖项。 -还记得依赖项可以有子依赖项吗? +还记得依赖项支持子依赖项吗? -`get_current_user` 将具有一个我们之前所创建的同一个 `oauth2_scheme` 作为依赖项。 +`get_current_user` 使用 `oauth2_scheme` 作为依赖项。 -与我们之前直接在路径操作中所做的相同,我们新的依赖项 `get_current_user` 将从子依赖项 `oauth2_scheme` 中接收一个 `str` 类型的 `token`: +与之前直接在路径操作中的做法相同,新的 `get_current_user` 依赖项从子依赖项 `oauth2_scheme` 中接收 `str` 类型的 `token`: ```Python hl_lines="25" {!../../../docs_src/security/tutorial002.py!} @@ -37,7 +37,7 @@ ## 获取用户 -`get_current_user` 将使用我们创建的(伪)工具函数,该函数接收 `str` 类型的令牌并返回我们的 Pydantic `User` 模型: +`get_current_user` 使用创建的(伪)工具函数,该函数接收 `str` 类型的令牌,并返回 Pydantic 的 `User` 模型: ```Python hl_lines="19-22 26-27" {!../../../docs_src/security/tutorial002.py!} @@ -45,70 +45,72 @@ ## 注入当前用户 -因此现在我们可以在*路径操作*中使用 `get_current_user` 作为 `Depends` 了: +在*路径操作* 的 `Depends` 中使用 `get_current_user`: ```Python hl_lines="31" {!../../../docs_src/security/tutorial002.py!} ``` -注意我们将 `current_user` 的类型声明为 Pydantic 模型 `User`。 +注意,此处把 `current_user` 的类型声明为 Pydantic 的 `User` 模型。 -这将帮助我们在函数内部使用所有的代码补全和类型检查。 +这有助于在函数内部使用代码补全和类型检查。 -!!! tip - 你可能还记得请求体也是使用 Pydantic 模型来声明的。 +!!! tip "提示" - 在这里 **FastAPI** 不会搞混,因为你正在使用的是 `Depends`。 + 还记得请求体也是使用 Pydantic 模型声明的吧。 -!!! check - 这种依赖系统的设计方式使我们可以拥有不同的依赖项(不同的「可依赖类型」),并且它们都返回一个 `User` 模型。 + 放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 - 我们并未被局限于只能有一个返回该类型数据的依赖项。 +!!! check "检查" + 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 -## 其他模型 + 而不是局限于只能有一个返回该类型数据的依赖项。 -现在你可以直接在*路径操作函数*中获取当前用户,并使用 `Depends` 在**依赖注入**级别处理安全性机制。 -你可以使用任何模型或数据来满足安全性要求(在这个示例中,使用的是 Pydantic 模型 `User`)。 +## 其它模型 -但是你并未被限制只能使用某些特定的数据模型,类或类型。 +接下来,直接在*路径操作函数*中获取当前用户,并用 `Depends` 在**依赖注入**系统中处理安全机制。 -你想要在模型中使用 `id` 和 `email` 而不使用任何的 `username`?当然可以。你可以同样地使用这些工具。 +开发者可以使用任何模型或数据满足安全需求(本例中是 Pydantic 的 `User` 模型)。 -你只想要一个 `str`?或者仅仅一个 `dict`?还是直接一个数据库模型类的实例?它们的工作方式都是一样的。 +而且,不局限于只能使用特定的数据模型、类或类型。 -实际上你没有用户登录到你的应用程序,而是只拥有访问令牌的机器人,程序或其他系统?再一次,它们的工作方式也是一样的。 +不想在模型中使用 `username`,而是使用 `id` 和 `email`?当然可以。这些工具也支持。 -尽管去使用你的应用程序所需要的任何模型,任何类,任何数据库。**FastAPI** 通过依赖项注入系统都帮你搞定。 +只想使用字符串?或字典?甚至是数据库类模型的实例?工作方式都一样。 +实际上,就算登录应用的不是用户,而是只拥有访问令牌的机器人、程序或其它系统?工作方式也一样。 -## 代码体积 +尽管使用应用所需的任何模型、类、数据库。**FastAPI** 通过依赖注入系统都能帮您搞定。 -这个示例似乎看起来很冗长。考虑到我们在同一文件中混合了安全性,数据模型工具函数和路径操作等代码。 -但关键的是。 +## 代码大小 -安全性和依赖项注入内容只需要编写一次。 +这个示例看起来有些冗长。毕竟这个文件同时包含了安全、数据模型的工具函数,以及路径操作等代码。 -你可以根据需要使其变得很复杂。而且只需要在一个地方写一次。但仍然具备所有的灵活性。 +但,关键是: -但是,你可以有无数个使用同一安全系统的端点(*路径操作*)。 +**安全和依赖注入的代码只需要写一次。** -所有(或所需的任何部分)的端点,都可以利用对这些或你创建的其他依赖项进行复用所带来的优势。 +就算写得再复杂,也只是在一个位置写一次就够了。所以,要多复杂就可以写多复杂。 -所有的这无数个*路径操作*甚至可以小到只需 3 行代码: +但是,就算有数千个端点(*路径操作*),它们都可以使用同一个安全系统。 + +而且,所有端点(或它们的任何部件)都可以利用这些依赖项或任何其它依赖项。 + +所有*路径操作*只需 3 行代码就可以了: ```Python hl_lines="30-32" {!../../../docs_src/security/tutorial002.py!} ``` -## 总结 +## 小结 -现在你可以直接在*路径操作函数*中获取当前用户。 +现在,我们可以直接在*路径操作函数*中获取当前用户。 -我们已经进行到一半了。 +至此,安全的内容已经讲了一半。 -我们只需要再为用户/客户端添加一个真正发送 `username` 和 `password` 的*路径操作*。 +只要再为用户或客户端的*路径操作*添加真正发送 `username` 和 `password` 的功能就可以了。 -这些内容在下一章节。 +下一章见。 From 08c03765824928dc34ba2b72e7c35422f9c7bf69 Mon Sep 17 00:00:00 2001 From: Takayoshi Urushio <uru@craft-works.jp> Date: Sun, 31 Mar 2024 08:22:21 +0900 Subject: [PATCH 306/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Japanese=20tran?= =?UTF-8?q?slation=20of=20`docs/ja/docs/tutorial/query-params.md`=20(#1080?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/ja/docs/tutorial/query-params.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 5202009ef..957726b9f 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -73,11 +73,6 @@ http://127.0.0.1:8000/items/?skip=20 !!! check "確認" パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 -!!! note "備考" - FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 - - `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 - ## クエリパラメータの型変換 `bool` 型も宣言できます。これは以下の様に変換されます: From d75cfa1e0cc16bbc05434208de47d9b01cc1fba5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:36:09 +0000 Subject: [PATCH 307/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6d842165c..dd2f09cc0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/tutorial/response-status-code.md`. PR [#3498](https://github.com/tiangolo/fastapi/pull/3498) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add German translation for `docs/de/docs/tutorial/security/first-steps.md`. PR [#10432](https://github.com/tiangolo/fastapi/pull/10432) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/events.md`. PR [#10693](https://github.com/tiangolo/fastapi/pull/10693) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/deployment/cloud.md`. PR [#10746](https://github.com/tiangolo/fastapi/pull/10746) by [@nilslindemann](https://github.com/nilslindemann). From 376726d0254b4e9bf684af2b1b809ed538b48bbe Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:39:09 +0000 Subject: [PATCH 308/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index dd2f09cc0..13cfe355e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/header-params.md`. PR [#3487](https://github.com/tiangolo/fastapi/pull/3487) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/response-status-code.md`. PR [#3498](https://github.com/tiangolo/fastapi/pull/3498) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add German translation for `docs/de/docs/tutorial/security/first-steps.md`. PR [#10432](https://github.com/tiangolo/fastapi/pull/10432) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Add German translation for `docs/de/docs/advanced/events.md`. PR [#10693](https://github.com/tiangolo/fastapi/pull/10693) by [@nilslindemann](https://github.com/nilslindemann). From 51e98121d04ab4b4e1d257e72b823d816a9828cd Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:39:41 +0000 Subject: [PATCH 309/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 13cfe355e..2a25d3339 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/cookie-params.md`. PR [#3486](https://github.com/tiangolo/fastapi/pull/3486) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/header-params.md`. PR [#3487](https://github.com/tiangolo/fastapi/pull/3487) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/response-status-code.md`. PR [#3498](https://github.com/tiangolo/fastapi/pull/3498) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add German translation for `docs/de/docs/tutorial/security/first-steps.md`. PR [#10432](https://github.com/tiangolo/fastapi/pull/10432) by [@nilslindemann](https://github.com/nilslindemann). From 2e355c47f995a68d260b0cf520d7fc9d374c549f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:40:22 +0000 Subject: [PATCH 310/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2a25d3339..4158ec40c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#3800](https://github.com/tiangolo/fastapi/pull/3800) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/cookie-params.md`. PR [#3486](https://github.com/tiangolo/fastapi/pull/3486) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/header-params.md`. PR [#3487](https://github.com/tiangolo/fastapi/pull/3487) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/response-status-code.md`. PR [#3498](https://github.com/tiangolo/fastapi/pull/3498) by [@jaystone776](https://github.com/jaystone776). From 802f8bc9b6d0635e1e7cfe5c4e60ae9527778898 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:40:53 +0000 Subject: [PATCH 311/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4158ec40c..a46fbef11 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/http-basic-auth.md`. PR [#3801](https://github.com/tiangolo/fastapi/pull/3801) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#3800](https://github.com/tiangolo/fastapi/pull/3800) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/cookie-params.md`. PR [#3486](https://github.com/tiangolo/fastapi/pull/3486) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/header-params.md`. PR [#3487](https://github.com/tiangolo/fastapi/pull/3487) by [@jaystone776](https://github.com/jaystone776). From 8f2be5e005891a01f128890d9bd75140f29afcc8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:41:42 +0000 Subject: [PATCH 312/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a46fbef11..357f71b96 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/using-request-directly.md`. PR [#3802](https://github.com/tiangolo/fastapi/pull/3802) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/http-basic-auth.md`. PR [#3801](https://github.com/tiangolo/fastapi/pull/3801) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#3800](https://github.com/tiangolo/fastapi/pull/3800) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/cookie-params.md`. PR [#3486](https://github.com/tiangolo/fastapi/pull/3486) by [@jaystone776](https://github.com/jaystone776). From f61eeb6b185c498c54c21964d6d325eba7f4cb44 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:43:27 +0000 Subject: [PATCH 313/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 357f71b96..3ffe119a4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/dataclasses.md`. PR [#3803](https://github.com/tiangolo/fastapi/pull/3803) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/using-request-directly.md`. PR [#3802](https://github.com/tiangolo/fastapi/pull/3802) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/http-basic-auth.md`. PR [#3801](https://github.com/tiangolo/fastapi/pull/3801) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#3800](https://github.com/tiangolo/fastapi/pull/3800) by [@jaystone776](https://github.com/jaystone776). From 9c99c43a944c305c168226d26e3e33476cff1fb0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:44:05 +0000 Subject: [PATCH 314/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3ffe119a4..e8af475a0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/middleware.md`. PR [#3804](https://github.com/tiangolo/fastapi/pull/3804) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/dataclasses.md`. PR [#3803](https://github.com/tiangolo/fastapi/pull/3803) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/using-request-directly.md`. PR [#3802](https://github.com/tiangolo/fastapi/pull/3802) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/http-basic-auth.md`. PR [#3801](https://github.com/tiangolo/fastapi/pull/3801) by [@jaystone776](https://github.com/jaystone776). From 34caf8e42ba3701ab2e6981699f1c5b55465a430 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:44:43 +0000 Subject: [PATCH 315/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e8af475a0..94a12aeb5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-sql-databases.md`. PR [#3805](https://github.com/tiangolo/fastapi/pull/3805) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/middleware.md`. PR [#3804](https://github.com/tiangolo/fastapi/pull/3804) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/dataclasses.md`. PR [#3803](https://github.com/tiangolo/fastapi/pull/3803) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/using-request-directly.md`. PR [#3802](https://github.com/tiangolo/fastapi/pull/3802) by [@jaystone776](https://github.com/jaystone776). From 8c3aa5e012f6027b0adbc38b98c4f8d18aa10e12 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:45:27 +0000 Subject: [PATCH 316/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 94a12aeb5..2196aa0c2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/sub-applications.md`. PR [#3811](https://github.com/tiangolo/fastapi/pull/3811) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-sql-databases.md`. PR [#3805](https://github.com/tiangolo/fastapi/pull/3805) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/middleware.md`. PR [#3804](https://github.com/tiangolo/fastapi/pull/3804) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/dataclasses.md`. PR [#3803](https://github.com/tiangolo/fastapi/pull/3803) by [@jaystone776](https://github.com/jaystone776). From 42d62eb0285b887ac805cfb998be67052da7c4ea Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:46:03 +0000 Subject: [PATCH 317/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2196aa0c2..f1969fff1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#3812](https://github.com/tiangolo/fastapi/pull/3812) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/sub-applications.md`. PR [#3811](https://github.com/tiangolo/fastapi/pull/3811) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-sql-databases.md`. PR [#3805](https://github.com/tiangolo/fastapi/pull/3805) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/middleware.md`. PR [#3804](https://github.com/tiangolo/fastapi/pull/3804) by [@jaystone776](https://github.com/jaystone776). From 602445f305e8c590ec961a533a9c1d2bfe2cccf5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:47:46 +0000 Subject: [PATCH 318/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f1969fff1..3ae0ce391 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/external-links.md`. PR [#3833](https://github.com/tiangolo/fastapi/pull/3833) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#3812](https://github.com/tiangolo/fastapi/pull/3812) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/sub-applications.md`. PR [#3811](https://github.com/tiangolo/fastapi/pull/3811) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-sql-databases.md`. PR [#3805](https://github.com/tiangolo/fastapi/pull/3805) by [@jaystone776](https://github.com/jaystone776). From aa73071b5e51cf309c6445110fa7882e82701314 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:48:20 +0000 Subject: [PATCH 319/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3ae0ce391..af77f2db5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/custom-request-and-route.md`. PR [#3816](https://github.com/tiangolo/fastapi/pull/3816) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/external-links.md`. PR [#3833](https://github.com/tiangolo/fastapi/pull/3833) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#3812](https://github.com/tiangolo/fastapi/pull/3812) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/sub-applications.md`. PR [#3811](https://github.com/tiangolo/fastapi/pull/3811) by [@jaystone776](https://github.com/jaystone776). From 9a5a429aa0f05a6324920bba26faca02ce11a362 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:49:10 +0000 Subject: [PATCH 320/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index af77f2db5..6420e8a7b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#3819](https://github.com/tiangolo/fastapi/pull/3819) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/custom-request-and-route.md`. PR [#3816](https://github.com/tiangolo/fastapi/pull/3816) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/external-links.md`. PR [#3833](https://github.com/tiangolo/fastapi/pull/3833) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#3812](https://github.com/tiangolo/fastapi/pull/3812) by [@jaystone776](https://github.com/jaystone776). From 05b88371bb65fde0f910a5a8af5ec45c526655af Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:49:41 +0000 Subject: [PATCH 321/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6420e8a7b..ae7ee9b4a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/extending-openapi.md`. PR [#3823](https://github.com/tiangolo/fastapi/pull/3823) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#3819](https://github.com/tiangolo/fastapi/pull/3819) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/custom-request-and-route.md`. PR [#3816](https://github.com/tiangolo/fastapi/pull/3816) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/external-links.md`. PR [#3833](https://github.com/tiangolo/fastapi/pull/3833) by [@jaystone776](https://github.com/jaystone776). From bc1ec514ada84fa157f21ceb719b90c3fd770c9a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:50:22 +0000 Subject: [PATCH 322/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ae7ee9b4a..b3734a331 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-callbacks.md`. PR [#3825](https://github.com/tiangolo/fastapi/pull/3825) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/extending-openapi.md`. PR [#3823](https://github.com/tiangolo/fastapi/pull/3823) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#3819](https://github.com/tiangolo/fastapi/pull/3819) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/custom-request-and-route.md`. PR [#3816](https://github.com/tiangolo/fastapi/pull/3816) by [@jaystone776](https://github.com/jaystone776). From 447527be5dbebc5cab92d0ecce7b495c479c2b94 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 30 Mar 2024 23:51:04 +0000 Subject: [PATCH 323/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b3734a331..43f559e2b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/security/get-current-user.md`. PR [#3842](https://github.com/tiangolo/fastapi/pull/3842) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-callbacks.md`. PR [#3825](https://github.com/tiangolo/fastapi/pull/3825) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/extending-openapi.md`. PR [#3823](https://github.com/tiangolo/fastapi/pull/3823) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#3819](https://github.com/tiangolo/fastapi/pull/3819) by [@jaystone776](https://github.com/jaystone776). From cdfa3226516436f64ab16ea0a195da10895917ed Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Sun, 31 Mar 2024 00:55:23 +0100 Subject: [PATCH 324/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/contributing.md`=20(#10487)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/contributing.md | 447 +++++++++++++++++++++++++++++++++++ 1 file changed, 447 insertions(+) create mode 100644 docs/de/docs/contributing.md diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md new file mode 100644 index 000000000..07a3c9a78 --- /dev/null +++ b/docs/de/docs/contributing.md @@ -0,0 +1,447 @@ +# 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 <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">fastapi Repository</a> 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): + +<div class="termy"> + +```console +$ python -m venv env +``` + +</div> + +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: + +=== "Linux, macOS" + + <div class="termy"> + + ```console + $ source ./env/bin/activate + ``` + + </div> + +=== "Windows PowerShell" + + <div class="termy"> + + ```console + $ .\env\Scripts\Activate.ps1 + ``` + + </div> + +=== "Windows Bash" + + Oder, wenn Sie Bash für Windows verwenden (z. B. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): + + <div class="termy"> + + ```console + $ source ./env/Scripts/activate + ``` + + </div> + +Um zu überprüfen, ob es funktioniert hat, geben Sie ein: + +=== "Linux, macOS, Windows Bash" + + <div class="termy"> + + ```console + $ which pip + + some/directory/fastapi/env/bin/pip + ``` + + </div> + +=== "Windows PowerShell" + + <div class="termy"> + + ```console + $ Get-Command pip + + some/directory/fastapi/env/bin/pip + ``` + + </div> + +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: + +<div class="termy"> + +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +</div> + +!!! 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: + +<div class="termy"> + +```console +$ pip install -r requirements.txt + +---> 100% +``` + +</div> + +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: + +<div class="termy"> + +```console +$ bash scripts/format.sh +``` + +</div> + +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): + +<div class="termy"> + +```console +$ python ./scripts/docs.py live + +<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008 +<span style="color: green;">[INFO]</span> Start watching changes +<span style="color: green;">[INFO]</span> Start detecting changes +``` + +</div> + +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 <a href="https://typer.tiangolo.com/typer-cli/" class="external-link" target="_blank">Typer CLI</a> 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: + +<div class="termy"> + +```console +$ typer --install-completion + +zsh completion installed in /home/user/.bashrc. +Completion will take effect once you restart the terminal. +``` + +</div> + +### Dokumentationsstruktur + +Die Dokumentation verwendet <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>. + +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.: + +<div class="termy"> + +```console +$ uvicorn tutorial001:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +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 <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">aktuellen Pull Requests</a> 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 <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3Aawaiting-review" class="external-link" target="_blank">`lang-es`</a>. + +* 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 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">Kommentare mit Änderungsvorschlägen</a> zu vorhandenen Pull Requests hinzufügen. + + Schauen Sie sich die Dokumentation an, <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">wie man ein Review zu einem Pull Request hinzufügt</a>, welches den PR absegnet oder Änderungen vorschlägt. + +* Überprüfen Sie, ob es eine <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub-Diskussion</a> 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 <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" class="external-link" target= verwenden "_blank">List of ISO 639-1 codes</a> 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: + +<div class="termy"> + +```console +// Verwenden Sie das Kommando „live“ und fügen Sie den Sprach-Code als Argument hinten an +$ python ./scripts/docs.py live es + +<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008 +<span style="color: green;">[INFO]</span> Start watching changes +<span style="color: green;">[INFO]</span> Start detecting changes +``` + +</div> + +!!! 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 <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> 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: + +<div class="termy"> + +```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 +``` + +</div> + +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: + +<div class="termy"> + +```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 +``` + +</div> + +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: + +<div class="termy"> + +```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 +``` + +</div> + +#### Ü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: + +<div class="termy"> + +```console +$ bash scripts/test-cov-html.sh +``` + +</div> + +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. From 90f4b93c3eea7ad89c0b3c7336fb124e7e01de84 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 31 Mar 2024 00:00:20 +0000 Subject: [PATCH 325/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 43f559e2b..f3262a73e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Update Japanese translation of `docs/ja/docs/tutorial/query-params.md`. PR [#10808](https://github.com/tiangolo/fastapi/pull/10808) by [@urushio](https://github.com/urushio). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/security/get-current-user.md`. PR [#3842](https://github.com/tiangolo/fastapi/pull/3842) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-callbacks.md`. PR [#3825](https://github.com/tiangolo/fastapi/pull/3825) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/extending-openapi.md`. PR [#3823](https://github.com/tiangolo/fastapi/pull/3823) by [@jaystone776](https://github.com/jaystone776). From 78a883d2c3696a59782eb2688146a74d75b8a5ce Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 31 Mar 2024 00:16:43 +0000 Subject: [PATCH 326/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f3262a73e..759fbf3d3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/contributing.md`. PR [#10487](https://github.com/tiangolo/fastapi/pull/10487) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Japanese translation of `docs/ja/docs/tutorial/query-params.md`. PR [#10808](https://github.com/tiangolo/fastapi/pull/10808) by [@urushio](https://github.com/urushio). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/security/get-current-user.md`. PR [#3842](https://github.com/tiangolo/fastapi/pull/3842) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-callbacks.md`. PR [#3825](https://github.com/tiangolo/fastapi/pull/3825) by [@jaystone776](https://github.com/jaystone776). From 267af4756691c1107f12bd3fe1197f49a3ea9702 Mon Sep 17 00:00:00 2001 From: tokusumi <41147016+tokusumi@users.noreply.github.com> Date: Sun, 31 Mar 2024 11:46:56 +0900 Subject: [PATCH 327/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/metadata.md`=20(#2667)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/ja/docs/tutorial/metadata.md | 105 ++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 docs/ja/docs/tutorial/metadata.md diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md new file mode 100644 index 000000000..9c6d48e11 --- /dev/null +++ b/docs/ja/docs/tutorial/metadata.md @@ -0,0 +1,105 @@ +# メタデータとドキュメントのURL + +**FastAPI** アプリケーションのいくつかのメタデータの設定をカスタマイズできます。 + +## タイトル、説明文、バージョン + +以下を設定できます: + +* **タイトル**: OpenAPIおよび自動APIドキュメントUIでAPIのタイトル/名前として使用される。 +* **説明文**: OpenAPIおよび自動APIドキュメントUIでのAPIの説明文。 +* **バージョン**: APIのバージョン。例: `v2` または `2.5.0`。 + *たとえば、以前のバージョンのアプリケーションがあり、OpenAPIも使用している場合に便利です。 + +これらを設定するには、パラメータ `title`、`description`、`version` を使用します: + +```Python hl_lines="4-6" +{!../../../docs_src/metadata/tutorial001.py!} +``` + +この設定では、自動APIドキュメントは以下の様になります: + +<img src="/img/tutorial/metadata/image01.png"> + +## タグのためのメタデータ + +さらに、パラメータ `openapi_tags` を使うと、path operations をグループ分けするための複数のタグに関するメタデータを追加できます。 + +それぞれのタグ毎にひとつの辞書を含むリストをとります。 + +それぞれの辞書は以下をもつことができます: + +* `name` (**必須**): *path operations* および `APIRouter` の `tags` パラメーターで使用するのと同じタグ名である `str`。 +* `description`: タグの簡単な説明文である `str`。 Markdownで記述でき、ドキュメントUIに表示されます。 +* `externalDocs`: 外部ドキュメントを説明するための `dict`: + * `description`: 外部ドキュメントの簡単な説明文である `str`。 + * `url` (**必須**): 外部ドキュメントのURLである `str`。 + +### タグのためのメタデータの作成 + +`users` と `items` のタグを使った例でメタデータの追加を試してみましょう。 + +タグのためのメタデータを作成し、それを `openapi_tags` パラメータに渡します。 + +```Python hl_lines="3-16 18" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 + +!!! tip "豆知識" + 使用するすべてのタグにメタデータを追加する必要はありません。 + +### 自作タグの使用 + +`tags` パラメーターを使用して、それぞれの *path operations* (および `APIRouter`) を異なるタグに割り当てます: + +```Python hl_lines="21 26" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +!!! info "情報" + タグのより詳しい説明を知りたい場合は [Path Operation Configuration](../path-operation-configuration/#tags){.internal-link target=_blank} を参照して下さい。 + +### ドキュメントの確認 + +ここで、ドキュメントを確認すると、追加したメタデータがすべて表示されます: + +<img src="/img/tutorial/metadata/image02.png"> + +### タグの順番 + +タグのメタデータ辞書の順序は、ドキュメントUIに表示される順序の定義にもなります。 + +たとえば、`users` はアルファベット順では `items` の後に続きます。しかし、リストの最初に `users` のメタデータ辞書を追加したため、ドキュメントUIでは `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` を設定できます。これにより、それを使用するドキュメントUIも無効になります。 + +## ドキュメントのURL + +以下の2つのドキュメントUIを構築できます: + +* **Swagger UI**: `/docs` で提供されます。 + * URL はパラメータ `docs_url` で設定できます。 + * `docs_url=None` を設定することで無効にできます。 +* ReDoc: `/redoc` で提供されます。 + * URL はパラメータ `redoc_url` で設定できます。 + * `redoc_url=None` を設定することで無効にできます。 + +たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial003.py!} +``` From 4c2de5e2c3cdeb16825782cd84ca6ef2b6c0cd72 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 31 Mar 2024 02:47:18 +0000 Subject: [PATCH 328/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 759fbf3d3..97a31a9c5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/metadata.md`. PR [#2667](https://github.com/tiangolo/fastapi/pull/2667) by [@tokusumi](https://github.com/tokusumi). * 🌐 Add German translation for `docs/de/docs/contributing.md`. PR [#10487](https://github.com/tiangolo/fastapi/pull/10487) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Japanese translation of `docs/ja/docs/tutorial/query-params.md`. PR [#10808](https://github.com/tiangolo/fastapi/pull/10808) by [@urushio](https://github.com/urushio). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/security/get-current-user.md`. PR [#3842](https://github.com/tiangolo/fastapi/pull/3842) by [@jaystone776](https://github.com/jaystone776). From ee6403212b97a81190b49ada21c8c438315d049d Mon Sep 17 00:00:00 2001 From: igeni <kublin@it8.ru> Date: Sun, 31 Mar 2024 19:37:21 +0300 Subject: [PATCH 329/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Simplify=20string?= =?UTF-8?q?=20format=20with=20f-strings=20in=20`fastapi/applications.py`?= =?UTF-8?q?=20(#11335)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/applications.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index ffe9da358..d3edcc880 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -1019,7 +1019,7 @@ class FastAPI(Starlette): oauth2_redirect_url = root_path + oauth2_redirect_url return get_swagger_ui_html( openapi_url=openapi_url, - title=self.title + " - Swagger UI", + title=f"{self.title} - Swagger UI", oauth2_redirect_url=oauth2_redirect_url, init_oauth=self.swagger_ui_init_oauth, swagger_ui_parameters=self.swagger_ui_parameters, @@ -1043,7 +1043,7 @@ class FastAPI(Starlette): root_path = req.scope.get("root_path", "").rstrip("/") openapi_url = root_path + self.openapi_url return get_redoc_html( - openapi_url=openapi_url, title=self.title + " - ReDoc" + openapi_url=openapi_url, title=f"{self.title} - ReDoc" ) self.add_route(self.redoc_url, redoc_html, include_in_schema=False) From d8449b2fff1d64497d38b9ef2b4673ad92bf2696 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 31 Mar 2024 16:37:43 +0000 Subject: [PATCH 330/846] =?UTF-8?q?=F0=9F=93=9D=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 97a31a9c5..7ca581abe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Simplify string format with f-strings in `fastapi/applications.py`. PR [#11335](https://github.com/tiangolo/fastapi/pull/11335) by [@igeni](https://github.com/igeni). + ### Docs * ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#11368](https://github.com/tiangolo/fastapi/pull/11368) by [@shandongbinzhou](https://github.com/shandongbinzhou). From c1796275f918af83d9433515b9b3ab925b574468 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 31 Mar 2024 18:52:53 -0500 Subject: [PATCH 331/846] =?UTF-8?q?=F0=9F=93=9D=20Tweak=20docs=20and=20tra?= =?UTF-8?q?nslations=20links=20and=20remove=20old=20docs=20translations=20?= =?UTF-8?q?(#11381)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/advanced/async-sql-databases.md | 162 ----------- docs/em/docs/advanced/index.md | 4 +- docs/em/docs/advanced/nosql-databases.md | 156 ----------- docs/em/docs/advanced/security/index.md | 4 +- docs/em/docs/async.md | 2 +- docs/em/docs/help-fastapi.md | 2 +- docs/em/docs/tutorial/metadata.md | 2 +- docs/en/docs/advanced/index.md | 6 +- docs/en/docs/advanced/security/index.md | 4 +- docs/en/docs/async.md | 2 +- docs/en/docs/help-fastapi.md | 2 +- .../docs/how-to/custom-request-and-route.md | 2 +- docs/en/docs/release-notes.md | 2 +- docs/en/docs/tutorial/metadata.md | 2 +- docs/es/docs/advanced/index.md | 4 +- docs/es/docs/advanced/security/index.md | 4 +- docs/es/docs/async.md | 2 +- docs/fr/docs/advanced/index.md | 4 +- docs/fr/docs/async.md | 2 +- docs/ja/docs/advanced/index.md | 4 +- docs/ja/docs/advanced/nosql-databases.md | 156 ----------- docs/ja/docs/async.md | 2 +- docs/ja/docs/tutorial/metadata.md | 2 +- docs/ko/docs/advanced/index.md | 4 +- docs/ko/docs/async.md | 2 +- docs/pl/docs/help-fastapi.md | 2 +- docs/pt/docs/advanced/index.md | 4 +- docs/pt/docs/async.md | 2 +- docs/pt/docs/help-fastapi.md | 2 +- docs/ru/docs/async.md | 2 +- docs/ru/docs/help-fastapi.md | 2 +- docs/ru/docs/tutorial/metadata.md | 2 +- docs/tr/docs/async.md | 2 +- docs/zh/docs/advanced/async-sql-databases.md | 167 ------------ .../docs/advanced/custom-request-and-route.md | 113 -------- docs/zh/docs/advanced/extending-openapi.md | 252 ------------------ docs/zh/docs/advanced/index.md | 6 +- docs/zh/docs/advanced/security/index.md | 4 +- docs/zh/docs/async.md | 2 +- docs/zh/docs/deployment/deta.md | 244 ----------------- docs/zh/docs/external-links.md | 83 ------ docs/zh/docs/help-fastapi.md | 2 +- docs/zh/docs/tutorial/metadata.md | 3 +- 43 files changed, 50 insertions(+), 1382 deletions(-) delete mode 100644 docs/em/docs/advanced/async-sql-databases.md delete mode 100644 docs/em/docs/advanced/nosql-databases.md delete mode 100644 docs/ja/docs/advanced/nosql-databases.md delete mode 100644 docs/zh/docs/advanced/async-sql-databases.md delete mode 100644 docs/zh/docs/advanced/custom-request-and-route.md delete mode 100644 docs/zh/docs/advanced/extending-openapi.md delete mode 100644 docs/zh/docs/deployment/deta.md delete mode 100644 docs/zh/docs/external-links.md diff --git a/docs/em/docs/advanced/async-sql-databases.md b/docs/em/docs/advanced/async-sql-databases.md deleted file mode 100644 index 848936de1..000000000 --- a/docs/em/docs/advanced/async-sql-databases.md +++ /dev/null @@ -1,162 +0,0 @@ -# 🔁 🗄 (🔗) 💽 - -👆 💪 ⚙️ <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases`</a> ⏮️ **FastAPI** 🔗 💽 ⚙️ `async` & `await`. - -⚫️ 🔗 ⏮️: - -* ✳ -* ✳ -* 🗄 - -👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️. - -⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. - -!!! tip - 👆 💪 🛠️ 💭 ⚪️➡️ 📄 🔃 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), 💖 ⚙️ 🚙 🔢 🎭 🛠️ 💽, 🔬 👆 **FastAPI** 📟. - - 👉 📄 🚫 ✔ 📚 💭, 🌓 😑 <a href="https://www.starlette.io/database/" class="external-link" target="_blank">💃</a>. - -## 🗄 & ⚒ 🆙 `SQLAlchemy` - -* 🗄 `SQLAlchemy`. -* ✍ `metadata` 🎚. -* ✍ 🏓 `notes` ⚙️ `metadata` 🎚. - -```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - 👀 👈 🌐 👉 📟 😁 🇸🇲 🐚. - - `databases` 🚫 🔨 🕳 📥. - -## 🗄 & ⚒ 🆙 `databases` - -* 🗄 `databases`. -* ✍ `DATABASE_URL`. -* ✍ `database` 🎚. - -```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - 🚥 👆 🔗 🎏 💽 (✅ ✳), 👆 🔜 💪 🔀 `DATABASE_URL`. - -## ✍ 🏓 - -👉 💼, 👥 🏗 🏓 🎏 🐍 📁, ✋️ 🏭, 👆 🔜 🎲 💚 ✍ 👫 ⏮️ ⚗, 🛠️ ⏮️ 🛠️, ♒️. - -📥, 👉 📄 🔜 🏃 🔗, ▶️️ ⏭ ▶️ 👆 **FastAPI** 🈸. - -* ✍ `engine`. -* ✍ 🌐 🏓 ⚪️➡️ `metadata` 🎚. - -```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## ✍ 🏷 - -✍ Pydantic 🏷: - -* 🗒 ✍ (`NoteIn`). -* 🗒 📨 (`Note`). - -```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -🏗 👫 Pydantic 🏷, 🔢 💽 🔜 ✔, 🎻 (🗜), & ✍ (📄). - -, 👆 🔜 💪 👀 ⚫️ 🌐 🎓 🛠️ 🩺. - -## 🔗 & 🔌 - -* ✍ 👆 `FastAPI` 🈸. -* ✍ 🎉 🐕🦺 🔗 & 🔌 ⚪️➡️ 💽. - -```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## ✍ 🗒 - -✍ *➡ 🛠️ 🔢* ✍ 🗒: - -```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`. - -### 👀 `response_model=List[Note]` - -⚫️ ⚙️ `typing.List`. - -👈 📄 (& ✔, 🎻, ⛽) 🔢 💽, `list` `Note`Ⓜ. - -## ✍ 🗒 - -✍ *➡ 🛠️ 🔢* ✍ 🗒: - -```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`. - -### 🔃 `{**note.dict(), "id": last_record_id}` - -`note` Pydantic `Note` 🎚. - -`note.dict()` 📨 `dict` ⏮️ 🚮 💽, 🕳 💖: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -✋️ ⚫️ 🚫 ✔️ `id` 🏑. - -👥 ✍ 🆕 `dict`, 👈 🔌 🔑-💲 👫 ⚪️➡️ `note.dict()` ⏮️: - -```Python -{**note.dict()} -``` - -`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`. - -& ⤴️, 👥 ↔ 👈 📁 `dict`, ❎ ➕1️⃣ 🔑-💲 👫: `"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -, 🏁 🏁 📨 🔜 🕳 💖: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## ✅ ⚫️ - -👆 💪 📁 👉 📟, & 👀 🩺 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. - -📤 👆 💪 👀 🌐 👆 🛠️ 📄 & 🔗 ⏮️ ⚫️: - -<img src="/img/tutorial/async-sql-databases/image01.png"> - -## 🌅 ℹ - -👆 💪 ✍ 🌅 🔃 <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases` 🚮 📂 📃</a>. diff --git a/docs/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md index abe8d357c..43bada6b4 100644 --- a/docs/em/docs/advanced/index.md +++ b/docs/em/docs/advanced/index.md @@ -2,7 +2,7 @@ ## 🌖 ⚒ -👑 [🔰 - 👩💻 🦮](../tutorial/){.internal-link target=_blank} 🔜 🥃 🤝 👆 🎫 🔘 🌐 👑 ⚒ **FastAPI**. +👑 [🔰 - 👩💻 🦮](../tutorial/index.md){.internal-link target=_blank} 🔜 🥃 🤝 👆 🎫 🔘 🌐 👑 ⚒ **FastAPI**. ⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒. @@ -13,7 +13,7 @@ ## ✍ 🔰 🥇 -👆 💪 ⚙️ 🏆 ⚒ **FastAPI** ⏮️ 💡 ⚪️➡️ 👑 [🔰 - 👩💻 🦮](../tutorial/){.internal-link target=_blank}. +👆 💪 ⚙️ 🏆 ⚒ **FastAPI** ⏮️ 💡 ⚪️➡️ 👑 [🔰 - 👩💻 🦮](../tutorial/index.md){.internal-link target=_blank}. & ⏭ 📄 🤔 👆 ⏪ ✍ ⚫️, & 🤔 👈 👆 💭 👈 👑 💭. diff --git a/docs/em/docs/advanced/nosql-databases.md b/docs/em/docs/advanced/nosql-databases.md deleted file mode 100644 index 9c828a909..000000000 --- a/docs/em/docs/advanced/nosql-databases.md +++ /dev/null @@ -1,156 +0,0 @@ -# ☁ (📎 / 🦏 💽) 💽 - -**FastAPI** 💪 🛠️ ⏮️ 🙆 <abbr title="Distributed database (Big Data), also 'Not Only SQL'">☁</abbr>. - -📥 👥 🔜 👀 🖼 ⚙️ **<a href="https://www.couchbase.com/" class="external-link" target="_blank">🗄</a>**, <abbr title="Document here refers to a JSON object (a dict), with keys and values, and those values can also be other JSON objects, arrays (lists), numbers, strings, booleans, etc.">📄</abbr> 🧢 ☁ 💽. - -👆 💪 🛠️ ⚫️ 🙆 🎏 ☁ 💽 💖: - -* **✳** -* **👸** -* **✳** -* **🇸🇲** -* **✳**, ♒️. - -!!! tip - 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **🗄**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a> - -## 🗄 🗄 🦲 - -🔜, 🚫 💸 🙋 🎂, 🕴 🗄: - -```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## 🔬 📉 ⚙️ "📄 🆎" - -👥 🔜 ⚙️ ⚫️ ⏪ 🔧 🏑 `type` 👆 📄. - -👉 🚫 ✔ 🗄, ✋️ 👍 💡 👈 🔜 ℹ 👆 ⏮️. - -```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## 🚮 🔢 🤚 `Bucket` - -**🗄**, 🥡 ⚒ 📄, 👈 💪 🎏 🆎. - -👫 🛎 🌐 🔗 🎏 🈸. - -🔑 🔗 💽 🌏 🔜 "💽" (🎯 💽, 🚫 💽 💽). - -🔑 **✳** 🔜 "🗃". - -📟, `Bucket` 🎨 👑 🇨🇻 📻 ⏮️ 💽. - -👉 🚙 🔢 🔜: - -* 🔗 **🗄** 🌑 (👈 💪 👁 🎰). - * ⚒ 🔢 ⏲. -* 🔓 🌑. -* 🤚 `Bucket` 👐. - * ⚒ 🔢 ⏲. -* 📨 ⚫️. - -```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## ✍ Pydantic 🏷 - -**🗄** "📄" 🤙 "🎻 🎚", 👥 💪 🏷 👫 ⏮️ Pydantic. - -### `User` 🏷 - -🥇, ➡️ ✍ `User` 🏷: - -```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -👥 🔜 ⚙️ 👉 🏷 👆 *➡ 🛠️ 🔢*,, 👥 🚫 🔌 ⚫️ `hashed_password`. - -### `UserInDB` 🏷 - -🔜, ➡️ ✍ `UserInDB` 🏷. - -👉 🔜 ✔️ 💽 👈 🤙 🏪 💽. - -👥 🚫 ✍ ⚫️ 🏿 Pydantic `BaseModel` ✋️ 🏿 👆 👍 `User`, ↩️ ⚫️ 🔜 ✔️ 🌐 🔢 `User` ➕ 👩❤👨 🌅: - -```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -!!! note - 👀 👈 👥 ✔️ `hashed_password` & `type` 🏑 👈 🔜 🏪 💽. - - ✋️ ⚫️ 🚫 🍕 🏢 `User` 🏷 (1️⃣ 👥 🔜 📨 *➡ 🛠️*). - -## 🤚 👩💻 - -🔜 ✍ 🔢 👈 🔜: - -* ✊ 🆔. -* 🏗 📄 🆔 ⚪️➡️ ⚫️. -* 🤚 📄 ⏮️ 👈 🆔. -* 🚮 🎚 📄 `UserInDB` 🏷. - -🏗 🔢 👈 🕴 💡 🤚 👆 👩💻 ⚪️➡️ `username` (⚖️ 🙆 🎏 🔢) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 🏤-⚙️ ⚫️ 💗 🍕 & 🚮 <abbr title="Automated test, written in code, that checks if another piece of code is working correctly.">⚒ 💯</abbr> ⚫️: - -```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### Ⓜ-🎻 - -🚥 👆 🚫 😰 ⏮️ `f"userprofile::{username}"`, ⚫️ 🐍 "<a href="https://docs.python.org/3/glossary.html#term-f-string" class="external-link" target="_blank">Ⓜ-🎻</a>". - -🙆 🔢 👈 🚮 🔘 `{}` Ⓜ-🎻 🔜 ↔ / 💉 🎻. - -### `dict` 🏗 - -🚥 👆 🚫 😰 ⏮️ `UserInDB(**result.value)`, <a href="https://docs.python.org/3/glossary.html#term-argument" class="external-link" target="_blank">⚫️ ⚙️ `dict` "🏗"</a>. - -⚫️ 🔜 ✊ `dict` `result.value`, & ✊ 🔠 🚮 🔑 & 💲 & 🚶♀️ 👫 🔑-💲 `UserInDB` 🇨🇻 ❌. - -, 🚥 `dict` 🔌: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -⚫️ 🔜 🚶♀️ `UserInDB` : - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## ✍ 👆 **FastAPI** 📟 - -### ✍ `FastAPI` 📱 - -```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### ✍ *➡ 🛠️ 🔢* - -👆 📟 🤙 🗄 & 👥 🚫 ⚙️ <a href="https://docs.couchbase.com/python-sdk/2.5/async-programming.html#asyncio-python-3-5" class="external-link" target="_blank">🥼 🐍 <code>await</code> 🐕🦺</a>, 👥 🔜 📣 👆 🔢 ⏮️ 😐 `def` ↩️ `async def`. - -, 🗄 👍 🚫 ⚙️ 👁 `Bucket` 🎚 💗 "<abbr title="A sequence of code being executed by the program, while at the same time, or at intervals, there can be others being executed too.">🧵</abbr>Ⓜ",, 👥 💪 🤚 🥡 🔗 & 🚶♀️ ⚫️ 👆 🚙 🔢: - -```Python hl_lines="49-53" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## 🌃 - -👆 💪 🛠️ 🙆 🥉 🥳 ☁ 💽, ⚙️ 👫 🐩 📦. - -🎏 ✔ 🙆 🎏 🔢 🧰, ⚙️ ⚖️ 🛠️. diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md index f2bb66df4..10291338e 100644 --- a/docs/em/docs/advanced/security/index.md +++ b/docs/em/docs/advanced/security/index.md @@ -2,7 +2,7 @@ ## 🌖 ⚒ -📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}. +📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}. !!! tip ⏭ 📄 **🚫 🎯 "🏧"**. @@ -11,6 +11,6 @@ ## ✍ 🔰 🥇 -⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}. +⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}. 👫 🌐 ⚓️ 🔛 🎏 🔧, ✋️ ✔ ➕ 🛠️. diff --git a/docs/em/docs/async.md b/docs/em/docs/async.md index ddcae1573..bed31c3e7 100644 --- a/docs/em/docs/async.md +++ b/docs/em/docs/async.md @@ -405,7 +405,7 @@ async def read_burgers(): 🚥 👆 👟 ⚪️➡️ ➕1️⃣ 🔁 🛠️ 👈 🔨 🚫 👷 🌌 🔬 🔛 & 👆 ⚙️ ⚖ 🙃 📊-🕴 *➡ 🛠️ 🔢* ⏮️ ✅ `def` 🤪 🎭 📈 (🔃 1️⃣0️⃣0️⃣ 💓), 🙏 🗒 👈 **FastAPI** ⭐ 🔜 🔄. 👫 💼, ⚫️ 👻 ⚙️ `async def` 🚥 👆 *➡ 🛠️ 🔢* ⚙️ 📟 👈 🎭 🚧 <abbr title="Input/Output: disk reading or writing, network communications.">👤/🅾</abbr>. -, 👯♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](/#performance){.internal-link target=_blank} 🌘 (⚖️ 🌘 ⭐) 👆 ⏮️ 🛠️. +, 👯♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](index.md#performance){.internal-link target=_blank} 🌘 (⚖️ 🌘 ⭐) 👆 ⏮️ 🛠️. ### 🔗 diff --git a/docs/em/docs/help-fastapi.md b/docs/em/docs/help-fastapi.md index b998ade42..da452abf4 100644 --- a/docs/em/docs/help-fastapi.md +++ b/docs/em/docs/help-fastapi.md @@ -12,7 +12,7 @@ ## 👱📔 📰 -👆 💪 👱📔 (🐌) [**FastAPI & 👨👧👦** 📰](/newsletter/){.internal-link target=_blank} 🚧 ℹ 🔃: +👆 💪 👱📔 (🐌) [**FastAPI & 👨👧👦** 📰](newsletter.md){.internal-link target=_blank} 🚧 ℹ 🔃: * 📰 🔃 FastAPI & 👨👧👦 👶 * 🦮 👶 diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 00098cdf5..75508af4d 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -66,7 +66,7 @@ ``` !!! info - ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](../path-operation-configuration/#tags){.internal-link target=_blank}. + ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#tags){.internal-link target=_blank}. ### ✅ 🩺 diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index d8dcd4ca6..86e42fba0 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -2,7 +2,7 @@ ## Additional Features -The main [Tutorial - User Guide](../tutorial/){.internal-link target=_blank} should be enough to give you a tour through all the main features of **FastAPI**. +The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} should be enough to give you a tour through all the main features of **FastAPI**. In the next sections you will see other options, configurations, and additional features. @@ -13,13 +13,13 @@ In the next sections you will see other options, configurations, and additional ## Read the Tutorial first -You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/){.internal-link target=_blank}. +You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank}. And the next sections assume you already read it, and assume that you know those main ideas. ## External Courses -Although the [Tutorial - User Guide](../tutorial/){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses. +Although the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses. Or it might be the case that you just prefer to take other courses because they adapt better to your learning style. diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md index c18baf64b..c9ede4231 100644 --- a/docs/en/docs/advanced/security/index.md +++ b/docs/en/docs/advanced/security/index.md @@ -2,7 +2,7 @@ ## Additional Features -There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/){.internal-link target=_blank}. +There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}. !!! tip The next sections are **not necessarily "advanced"**. @@ -11,6 +11,6 @@ There are some extra features to handle security apart from the ones covered in ## Read the Tutorial first -The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/){.internal-link target=_blank}. +The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}. They are all based on the same concepts, but allow some extra functionalities. diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 2ead1f2db..ff322635a 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -405,7 +405,7 @@ When you declare a *path operation function* with normal `def` instead of `async If you are coming from another async framework that does not work in the way described above and you are used to defining trivial compute-only *path operation functions* with plain `def` for a tiny performance gain (about 100 nanoseconds), please note that in **FastAPI** the effect would be quite opposite. In these cases, it's better to use `async def` unless your *path operation functions* use code that performs blocking <abbr title="Input/Output: disk reading or writing, network communications.">I/O</abbr>. -Still, in both situations, chances are that **FastAPI** will [still be faster](/#performance){.internal-link target=_blank} than (or at least comparable to) your previous framework. +Still, in both situations, chances are that **FastAPI** will [still be faster](index.md#performance){.internal-link target=_blank} than (or at least comparable to) your previous framework. ### Dependencies diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 095fc8c58..1d76aca5e 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -12,7 +12,7 @@ And there are several ways to get help too. ## Subscribe to the newsletter -You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](/newsletter/){.internal-link target=_blank} to stay updated about: +You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](newsletter.md){.internal-link target=_blank} to stay updated about: * News about FastAPI and friends 🚀 * Guides 📝 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 bca0c7603..3b9435004 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -28,7 +28,7 @@ And an `APIRoute` subclass to use that custom request class. ### Create a custom `GzipRequest` class !!! tip - This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}. + This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header. diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7ca581abe..52f51d19d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -3555,7 +3555,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * Add support and tests for Pydantic dataclasses in `response_model`. PR [#454](https://github.com/tiangolo/fastapi/pull/454) by [@dconathan](https://github.com/dconathan). * Fix typo in OAuth2 JWT tutorial. PR [#447](https://github.com/tiangolo/fastapi/pull/447) by [@pablogamboa](https://github.com/pablogamboa). * Use the `media_type` parameter in `Body()` params to set the media type in OpenAPI for `requestBody`. PR [#439](https://github.com/tiangolo/fastapi/pull/439) by [@divums](https://github.com/divums). -* Add article [Deploying a scikit-learn model with ONNX and FastAPI](https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915) by [https://www.linkedin.com/in/nico-axtmann](Nico Axtmann). PR [#438](https://github.com/tiangolo/fastapi/pull/438) by [@naxty](https://github.com/naxty). +* Add article [Deploying a scikit-learn model with ONNX and FastAPI](https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915) by [Nico Axtmann](https://www.linkedin.com/in/nico-axtmann). PR [#438](https://github.com/tiangolo/fastapi/pull/438) by [@naxty](https://github.com/naxty). * Allow setting custom `422` (validation error) response/schema in OpenAPI. * And use media type from response class instead of fixed `application/json` (the default). * PR [#437](https://github.com/tiangolo/fastapi/pull/437) by [@divums](https://github.com/divums). diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index 504204e98..4dce9af13 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -77,7 +77,7 @@ Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assig ``` !!! info - Read more about tags in [Path Operation Configuration](../path-operation-configuration/#tags){.internal-link target=_blank}. + Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}. ### Check the docs diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md index ba1d20b0d..eb8fe5c1b 100644 --- a/docs/es/docs/advanced/index.md +++ b/docs/es/docs/advanced/index.md @@ -2,7 +2,7 @@ ## Características Adicionales -El [Tutorial - Guía de Usuario](../tutorial/){.internal-link target=_blank} principal debe ser suficiente para darte un paseo por todas las características principales de **FastAPI** +El [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_blank} principal debe ser suficiente para darte un paseo por todas las características principales de **FastAPI** En las secciones siguientes verás otras opciones, configuraciones, y características adicionales. @@ -13,6 +13,6 @@ En las secciones siguientes verás otras opciones, configuraciones, y caracterí ## Lee primero el Tutorial -Puedes continuar usando la mayoría de las características de **FastAPI** con el conocimiento del [Tutorial - Guía de Usuario](../tutorial/){.internal-link target=_blank} principal. +Puedes continuar usando la mayoría de las características de **FastAPI** con el conocimiento del [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_blank} principal. En las siguientes secciones se asume que lo has leído y conoces esas ideas principales. diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md index e393fde4e..139e8f9bd 100644 --- a/docs/es/docs/advanced/security/index.md +++ b/docs/es/docs/advanced/security/index.md @@ -2,7 +2,7 @@ ## Características Adicionales -Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/){.internal-link target=_blank}. +Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. !!! tip Las siguientes secciones **no necesariamente son "avanzadas"**. @@ -11,6 +11,6 @@ Hay algunas características adicionales para manejar la seguridad además de la ## Leer primero el Tutorial -En las siguientes secciones asumimos que ya has leído el principal [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/){.internal-link target=_blank}. +En las siguientes secciones asumimos que ya has leído el principal [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. Están basadas en los mismos conceptos, pero permiten algunas funcionalidades adicionales. diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 83dd532ee..0fdc30739 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -400,7 +400,7 @@ Cuando declaras una *path operation function* con `def` normal en lugar de `asyn Si vienes de otro framework asíncrono que no funciona de la manera descrita anteriormente y estás acostumbrado a definir *path operation functions* del tipo sólo cálculo con `def` simple para una pequeña ganancia de rendimiento (aproximadamente 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen un código que realice el bloqueo <abbr title="Input/Output: disk reading or writing, network communications.">I/O</abbr>. -Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](/#rendimiento){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior. +Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](index.md#performance){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior. ### Dependencias diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md index f4fa5ecf6..aa37f1806 100644 --- a/docs/fr/docs/advanced/index.md +++ b/docs/fr/docs/advanced/index.md @@ -2,7 +2,7 @@ ## Caractéristiques supplémentaires -Le [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**. +Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**. Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires. @@ -13,7 +13,7 @@ Dans les sections suivantes, vous verrez des options, configurations et fonction ## Lisez d'abord le didacticiel -Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank}. +Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank}. Et les sections suivantes supposent que vous l'avez lu et que vous en connaissez les idées principales. diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index af4d6ca06..3f65032fe 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -365,7 +365,7 @@ Quand vous déclarez une *fonction de chemin* avec un `def` normal et non `async Si vous venez d'un autre framework asynchrone qui ne fonctionne pas comme de la façon décrite ci-dessus et que vous êtes habitués à définir des *fonctions de chemin* basiques avec un simple `def` pour un faible gain de performance (environ 100 nanosecondes), veuillez noter que dans **FastAPI**, l'effet serait plutôt contraire. Dans ces cas-là, il vaut mieux utiliser `async def` à moins que votre *fonction de chemin* utilise du code qui effectue des opérations <abbr title="Input/Output ou Entrées et Sorties ">I/O</abbr> bloquantes. -Au final, dans les deux situations, il est fort probable que **FastAPI** soit tout de même [plus rapide](/#performance){.internal-link target=_blank} que (ou au moins de vitesse égale à) votre framework précédent. +Au final, dans les deux situations, il est fort probable que **FastAPI** soit tout de même [plus rapide](index.md#performance){.internal-link target=_blank} que (ou au moins de vitesse égale à) votre framework précédent. ### Dépendances diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md index 0732fc405..2d60e7489 100644 --- a/docs/ja/docs/advanced/index.md +++ b/docs/ja/docs/advanced/index.md @@ -2,7 +2,7 @@ ## さらなる機能 -[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。 +[チュートリアル - ユーザーガイド](../tutorial/index.md){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。 以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。 @@ -13,7 +13,7 @@ ## 先にチュートリアルを読む -[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}の知識があれば、**FastAPI**の主要な機能を利用することができます。 +[チュートリアル - ユーザーガイド](../tutorial/index.md){.internal-link target=_blank}の知識があれば、**FastAPI**の主要な機能を利用することができます。 以降のセクションは、すでにチュートリアルを読んで、その主要なアイデアを理解できていることを前提としています。 diff --git a/docs/ja/docs/advanced/nosql-databases.md b/docs/ja/docs/advanced/nosql-databases.md deleted file mode 100644 index fbd76e96b..000000000 --- a/docs/ja/docs/advanced/nosql-databases.md +++ /dev/null @@ -1,156 +0,0 @@ -# NoSQL (分散 / ビッグデータ) Databases - -**FastAPI** はあらゆる <abbr title="分散データベース (Big Data)や 'Not Only SQL'">NoSQL</abbr>と統合することもできます。 - -ここでは<abbr title="ここでのドキュメントとは、キーと値を持つJSONオブジェクト(ディクショナリー)をあらわし、これらの値は他のJSONオブジェクトや配列(リスト)、数値、文字列、真偽値などにすることができます。">ドキュメント</abbr>ベースのNoSQLデータベースである**<a href="https://www.couchbase.com/" class="external-link" target="_blank">Couchbase</a>**を使用した例を見てみましょう。 - -他にもこれらのNoSQLデータベースを利用することが出来ます: - -* **MongoDB** -* **Cassandra** -* **CouchDB** -* **ArangoDB** -* **ElasticSearch** など。 - -!!! tip "豆知識" - **FastAPI**と**Couchbase**を使った公式プロジェクト・ジェネレータがあります。すべて**Docker**ベースで、フロントエンドやその他のツールも含まれています: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a> - -## Couchbase コンポーネントの Import - -まずはImportしましょう。今はその他のソースコードに注意を払う必要はありません。 - -```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## "document type" として利用する定数の定義 - -documentで利用する固定の`type`フィールドを用意しておきます。 - -これはCouchbaseで必須ではありませんが、後々の助けになるベストプラクティスです。 - -```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## `Bucket` を取得する関数の追加 - -**Couchbase**では、bucketはdocumentのセットで、様々な種類のものがあります。 - -Bucketは通常、同一のアプリケーション内で互いに関係を持っています。 - -リレーショナルデータベースの世界でいう"database"(データベースサーバではなく特定のdatabase)と類似しています。 - -**MongoDB** で例えると"collection"と似た概念です。 - -次のコードでは主に `Bucket` を利用してCouchbaseを操作します。 - -この関数では以下の処理を行います: - -* **Couchbase** クラスタ(1台の場合もあるでしょう)に接続 - * タイムアウトのデフォルト値を設定 -* クラスタで認証を取得 -* `Bucket` インスタンスを取得 - * タイムアウトのデフォルト値を設定 -* 作成した`Bucket`インスタンスを返却 - -```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Pydantic モデルの作成 - -**Couchbase**のdocumentは実際には単にJSONオブジェクトなのでPydanticを利用してモデルに出来ます。 - -### `User` モデル - -まずは`User`モデルを作成してみましょう: - -```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -このモデルは*path operation*に使用するので`hashed_password`は含めません。 - -### `UserInDB` モデル - -それでは`UserInDB`モデルを作成しましょう。 - -こちらは実際にデータベースに保存されるデータを保持します。 - -`User`モデルの持つ全ての属性に加えていくつかの属性を追加するのでPydanticの`BaseModel`を継承せずに`User`のサブクラスとして定義します: - -```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -!!! note "備考" - データベースに保存される`hashed_password`と`type`フィールドを`UserInDB`モデルに保持させていることに注意してください。 - - しかしこれらは(*path operation*で返却する)一般的な`User`モデルには含まれません - -## user の取得 - -それでは次の関数を作成しましょう: - -* username を取得する -* username を利用してdocumentのIDを生成する -* 作成したIDでdocumentを取得する -* documentの内容を`UserInDB`モデルに設定する - -*path operation関数*とは別に、`username`(またはその他のパラメータ)からuserを取得することだけに特化した関数を作成することで、より簡単に複数の部分で再利用したり<abbr title="コードで書かれた自動テストで、他のコードが正しく動作しているかどうかをチェックするもの。">ユニットテスト</abbr>を追加することができます。 - -```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### f-strings - -`f"userprofile::{username}"` という記載に馴染みがありませんか?これは Python の"<a href="https://docs.python.org/3/glossary.html#term-f-string" class="external-link" target="_blank">f-string</a>"と呼ばれるものです。 - -f-stringの`{}`の中に入れられた変数は、文字列の中に展開/注入されます。 - -### `dict` アンパック - -`UserInDB(**result.value)`という記載に馴染みがありませんか?<a href="https://docs.python.org/3/glossary.html#term-argument" class="external-link" target="_blank">これは`dict`の"アンパック"</a>と呼ばれるものです。 - -これは`result.value`の`dict`からそのキーと値をそれぞれ取りキーワード引数として`UserInDB`に渡します。 - -例えば`dict`が下記のようになっていた場合: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -`UserInDB`には次のように渡されます: - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## **FastAPI** コードの実装 - -### `FastAPI` app の作成 - -```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### *path operation関数*の作成 - -私たちのコードはCouchbaseを呼び出しており、<a href="https://docs.couchbase.com/python-sdk/2.5/async-programming.html#asyncio-python-3-5" class="external-link" target="_blank">実験的なPython <code>await</code></a>を使用していないので、私たちは`async def`ではなく通常の`def`で関数を宣言する必要があります。 - -また、Couchbaseは単一の`Bucket`オブジェクトを複数の<abbr title="プログラムによって実行される一連のコードのことで、同時に、または間隔をおいて他のコードも実行されることがあります。">スレッド</abbr>で使用しないことを推奨していますので、単に直接Bucketを取得して関数に渡すことが出来ます。 - -```Python hl_lines="49-53" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## まとめ - -他のサードパーティ製のNoSQLデータベースを利用する場合でも、そのデータベースの標準ライブラリを利用するだけで利用できます。 - -他の外部ツール、システム、APIについても同じことが言えます。 diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index 8fac2cb38..934cea0ef 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -368,7 +368,7 @@ async def read_burgers(): 上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキング<abbr title="入力/出力: ディスクの読み取りまたは書き込み、ネットワーク通信。">I/O</abbr>を実行しないのであれば、`async def` の使用をお勧めします。 -それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](/#performance){.internal-link target=_blank}可能性があります。 +それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#performance){.internal-link target=_blank}可能性があります。 ### 依存関係 diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index 9c6d48e11..73d7f02b2 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -59,7 +59,7 @@ ``` !!! info "情報" - タグのより詳しい説明を知りたい場合は [Path Operation Configuration](../path-operation-configuration/#tags){.internal-link target=_blank} を参照して下さい。 + タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 ### ドキュメントの確認 diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md index 5e23e2809..5fd1711a1 100644 --- a/docs/ko/docs/advanced/index.md +++ b/docs/ko/docs/advanced/index.md @@ -2,7 +2,7 @@ ## 추가 기능 -메인 [자습서 - 사용자 안내서](../tutorial/){.internal-link target=_blank}는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다. +메인 [자습서 - 사용자 안내서](../tutorial/index.md){.internal-link target=_blank}는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다. 이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. @@ -13,7 +13,7 @@ ## 자습서를 먼저 읽으십시오 -여러분은 메인 [자습서 - 사용자 안내서](../tutorial/){.internal-link target=_blank}의 지식으로 **FastAPI**의 대부분의 기능을 사용하실 수 있습니다. +여러분은 메인 [자습서 - 사용자 안내서](../tutorial/index.md){.internal-link target=_blank}의 지식으로 **FastAPI**의 대부분의 기능을 사용하실 수 있습니다. 이어지는 장들은 여러분이 메인 자습서 - 사용자 안내서를 이미 읽으셨으며 주요 아이디어를 알고 계신다고 가정합니다. diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index 47dbaa1b0..9bcebd367 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -379,7 +379,7 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 <a href="https://anyi 만약 상기에 묘사된대로 동작하지 않는 비동기 프로그램을 사용해왔고 약간의 성능 향상 (약 100 나노초)을 위해 `def`를 사용해서 계산만을 위한 사소한 *경로 작동 함수*를 정의해왔다면, **FastAPI**는 이와는 반대라는 것에 주의하십시오. 이러한 경우에, *경로 작동 함수*가 블로킹 <abbr title="Input/Output: 디스크 읽기 또는 쓰기, 네트워크 통신.">I/O</abbr>를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다. -하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](/#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. +하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. ### 의존성 diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index 3d02a8741..54c172664 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -12,7 +12,7 @@ Istnieje również kilka sposobów uzyskania pomocy. ## Zapisz się do newslettera -Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołach**](/newsletter/){.internal-link target=_blank}, aby być na bieżąco z: +Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołach**](newsletter.md){.internal-link target=_blank}, aby być na bieżąco z: * Aktualnościami o FastAPI i przyjaciołach 🚀 * Przewodnikami 📝 diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md index 7e276f732..413d8815f 100644 --- a/docs/pt/docs/advanced/index.md +++ b/docs/pt/docs/advanced/index.md @@ -2,7 +2,7 @@ ## Recursos Adicionais -O [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank} deve ser o suficiente para dar a você um tour por todos os principais recursos do **FastAPI**. +O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} deve ser o suficiente para dar a você um tour por todos os principais recursos do **FastAPI**. Na próxima seção você verá outras opções, configurações, e recursos adicionais. @@ -13,7 +13,7 @@ Na próxima seção você verá outras opções, configurações, e recursos adi ## Leia o Tutorial primeiro -Você ainda pode usar a maior parte dos recursos no **FastAPI** com o conhecimento do [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank}. +Você ainda pode usar a maior parte dos recursos no **FastAPI** com o conhecimento do [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank}. E as próximas seções assumem que você já leu ele, e que você conhece suas ideias principais. diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md index be1278a1b..fe2363386 100644 --- a/docs/pt/docs/async.md +++ b/docs/pt/docs/async.md @@ -369,7 +369,7 @@ Quando você declara uma *função de operação de rota* com `def` normal ao in Se você está chegando de outro framework assíncrono que não faz o trabalho descrito acima e você está acostumado a definir triviais *funções de operação de rota* com simples `def` para ter um mínimo ganho de performance (cerca de 100 nanosegundos), por favor observe que no **FastAPI** o efeito pode ser bem o oposto. Nesses casos, é melhor usar `async def` a menos que suas *funções de operação de rota* utilizem código que performem bloqueamento <abbr title="Input/Output: disco lendo ou escrevendo, comunicações de rede.">IO</abbr>. -Ainda, em ambas as situações, as chances são que o **FastAPI** será [ainda mais rápido](/#performance){.internal-link target=_blank} do que (ou ao menos comparável a) seus frameworks antecessores. +Ainda, em ambas as situações, as chances são que o **FastAPI** será [ainda mais rápido](index.md#performance){.internal-link target=_blank} do que (ou ao menos comparável a) seus frameworks antecessores. ### Dependências diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index d04905197..06a4db1e0 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -12,7 +12,7 @@ E também existem vários modos de se conseguir ajuda. ## Inscreva-se na newsletter -Você pode se inscrever (pouco frequente) [**FastAPI e amigos** newsletter](/newsletter/){.internal-link target=_blank} para receber atualizações: +Você pode se inscrever (pouco frequente) [**FastAPI e amigos** newsletter](newsletter.md){.internal-link target=_blank} para receber atualizações: * Notícias sobre FastAPI e amigos 🚀 * Tutoriais 📝 diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md index 4c44fc22d..4d3ce2adf 100644 --- a/docs/ru/docs/async.md +++ b/docs/ru/docs/async.md @@ -468,7 +468,7 @@ Starlette (и **FastAPI**) основаны на <a href="https://anyio.readthed <!--Уточнить: Не использовать async def, если код приводит к блокировке IO?--> <!--http://new.gramota.ru/spravka/punctum?layout=item&id=58_285--> -Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](/#performance){.internal-link target=_blank} +Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](index.md#performance){.internal-link target=_blank} другого фреймворка (или хотя бы на уровне с ним). ### Зависимости diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index 65ff768d1..3ad3e6fd4 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -12,7 +12,7 @@ ## Подписаться на новостную рассылку -Вы можете подписаться на редкую [новостную рассылку **FastAPI и его друзья**](/newsletter/){.internal-link target=_blank} и быть в курсе о: +Вы можете подписаться на редкую [новостную рассылку **FastAPI и его друзья**](newsletter.md){.internal-link target=_blank} и быть в курсе о: * Новостях о FastAPI и его друзьях 🚀 * Руководствах 📝 diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 331c96734..468e08917 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -65,7 +65,7 @@ ``` !!! info "Дополнительная информация" - Узнайте больше о тегах в [Конфигурации операции пути](../path-operation-configuration/#tags){.internal-link target=_blank}. + Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#tags){.internal-link target=_blank}. ### Проверьте документацию diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md index 2be594343..aab939189 100644 --- a/docs/tr/docs/async.md +++ b/docs/tr/docs/async.md @@ -376,7 +376,7 @@ FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir p Yukarıda açıklanan şekilde çalışmayan başka bir asenkron framework'den geliyorsanız ve küçük bir performans kazancı (yaklaşık 100 nanosaniye) için "def" ile *path fonksiyonu* tanımlamaya alışkınsanız, **FastAPI**'de tam tersi olacağını unutmayın. Bu durumlarda, *path fonksiyonu* <abbr title="Input/Output: disk okuma veya yazma, ağ iletişimleri.">G/Ç</abbr> engelleyen durum oluşturmadıkça "async def" kullanmak daha iyidir. -Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](/#performance){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. +Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](index.md#performance){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. ### Bagımlılıklar diff --git a/docs/zh/docs/advanced/async-sql-databases.md b/docs/zh/docs/advanced/async-sql-databases.md deleted file mode 100644 index c79877ada..000000000 --- a/docs/zh/docs/advanced/async-sql-databases.md +++ /dev/null @@ -1,167 +0,0 @@ -# 异步 SQL 关系型数据库 - -**FastAPI** 使用 <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases`</a> 为连接数据库提供异步支持(`async` 与 `await`)。 - -`databases` 兼容以下数据库: - -* PostgreSQL -* MySQL -* SQLite - -本章示例使用 **SQLite**,它使用的是单文件,且 Python 内置集成了 SQLite,因此,可以直接复制并运行本章示例。 - -生产环境下,则要使用 **PostgreSQL** 等数据库服务器。 - -!!! tip "提示" - - 您可以使用 SQLAlchemy ORM([SQL 关系型数据库一章](../tutorial/sql-databases.md){.internal-link target=_blank})中的思路,比如,使用工具函数在数据库中执行操作,独立于 **FastAPI** 代码。 - - 本章不应用这些思路,等效于 <a href="https://www.starlette.io/database/" class="external-link" target="_blank">Starlette</a> 的对应内容。 - -## 导入与设置 `SQLAlchemy` - -* 导入 `SQLAlchemy` -* 创建 `metadata` 对象 -* 使用 `metadata` 对象创建 `notes` 表 - -```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip "提示" - - 注意,上例是都是纯 SQLAlchemy Core 代码。 - - `databases` 还没有进行任何操作。 - -## 导入并设置 `databases` - -* 导入 `databases` -* 创建 `DATABASE_URL` -* 创建 `database` - -```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip "提示" - - 连接 PostgreSQL 等数据库时,需要修改 `DATABASE_URL`。 - -## 创建表 - -本例中,使用 Python 文件创建表,但在生产环境中,应使用集成迁移等功能的 Alembic 创建表。 - -本例在启动 **FastAPI** 应用前,直接执行这些操作。 - -* 创建 `engine` -* 使用 `metadata` 对象创建所有表 - -```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## 创建模型 - -创建以下 Pydantic 模型: - -* 创建笔记的模型(`NoteIn`) -* 返回笔记的模型(`Note`) - -```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -这两个 Pydantic 模型都可以辅助验证、序列化(转换)并注释(存档)输入的数据。 - -因此,API 文档会显示这些数据。 - -## 连接与断开 - -* 创建 `FastAPI` 应用 -* 创建事件处理器,执行数据库连接与断开操作 - -```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## 读取笔记 - -创建读取笔记的*路径操作函数*: - -```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note "笔记" - - 注意,本例与数据库通信时使用 `await`,因此*路径操作函数*要声明为异步函数(`asnyc`)。 - -### 注意 `response_model=List[Note]` - -`response_model=List[Note]` 使用的是 `typing.List`。 - -它以笔记(`Note`)列表的形式存档(及验证、序列化、筛选)输出的数据。 - -## 创建笔记 - -创建新建笔记的*路径操作函数*: - -```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note "笔记" - - 注意,本例与数据库通信时使用 `await`,因此要把*路径操作函数*声明为异步函数(`asnyc`)。 - -### 关于 `{**note.dict(), "id": last_record_id}` - -`note` 是 Pydantic `Note` 对象: - -`note.dict()` 返回包含如下数据的**字典**: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -但它不包含 `id` 字段。 - -因此要新建一个包含 `note.dict()` 键值对的**字典**: - -```Python -{**note.dict()} -``` - -`**note.dict()` 直接**解包**键值对, 因此,`{**note.dict()}` 是 `note.dict()` 的副本。 - -然后,扩展`dict` 副本,添加键值对`"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -最终返回的结果如下: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## 查看文档 - -复制这些代码,查看文档 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs。</a> - -API 文档显示如下内容: - -<img src="/img/tutorial/async-sql-databases/image01.png"> - -## 更多说明 - -更多内容详见 <a href="https://github.com/encode/databases" class="external-link" target="_blank">Github 上的`encode/databases` 的说明</a>。 diff --git a/docs/zh/docs/advanced/custom-request-and-route.md b/docs/zh/docs/advanced/custom-request-and-route.md deleted file mode 100644 index 0a0257d08..000000000 --- a/docs/zh/docs/advanced/custom-request-and-route.md +++ /dev/null @@ -1,113 +0,0 @@ -# 自定义请求与 APIRoute 类 - -有时,我们要覆盖 `Request` 与 `APIRoute` 类使用的逻辑。 - -尤其是中间件里的逻辑。 - -例如,在应用处理请求体前,预先读取或操控请求体。 - -!!! danger "危险" - - 本章内容**较难**。 - - **FastAPI** 新手可跳过本章。 - -## 用例 - -常见用例如下: - -* 把 <a href="https://msgpack.org/index.html" class="external-link" target="_blank">`msgpack`</a> 等非 JSON 请求体转换为 JSON -* 解压 gzip 压缩的请求体 -* 自动记录所有请求体的日志 - -## 处理自定义请求体编码 - -下面学习如何使用自定义 `Request` 子类压缩 gizp 请求。 - -并在自定义请求的类中使用 `APIRoute` 子类。 - -### 创建自定义 `GzipRequest` 类 - -!!! tip "提示" - - 本例只是为了说明 `GzipRequest` 类如何运作。如需 Gzip 支持,请使用 [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}。 - -首先,创建 `GzipRequest` 类,覆盖解压请求头中请求体的 `Request.body()` 方法。 - -请求头中没有 `gzip` 时,`GzipRequest` 不会解压请求体。 - -这样就可以让同一个路由类处理 gzip 压缩的请求或未压缩的请求。 - -```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` - -### 创建自定义 `GzipRoute` 类 - -接下来,创建使用 `GzipRequest` 的 `fastapi.routing.APIRoute ` 的自定义子类。 - -此时,这个自定义子类会覆盖 `APIRoute.get_route_handler()`。 - -`APIRoute.get_route_handler()` 方法返回的是函数,并且返回的函数接收请求并返回响应。 - -本例用它根据原始请求创建 `GzipRequest`。 - -```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` - -!!! note "技术细节" - - `Request` 的 `request.scope` 属性是包含关联请求元数据的字典。 - - `Request` 的 `request.receive` 方法是**接收**请求体的函数。 - - `scope` 字典与 `receive` 函数都是 ASGI 规范的内容。 - - `scope` 与 `receive` 也是创建新的 `Request` 实例所需的。 - - `Request` 的更多内容详见 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette 官档 - 请求</a>。 - -`GzipRequest.get_route_handler` 返回函数的唯一区别是把 `Request` 转换成了 `GzipRequest`。 - -如此一来,`GzipRequest` 把数据传递给*路径操作*前,就会解压数据(如需)。 - -之后,所有处理逻辑都一样。 - -但因为改变了 `GzipRequest.body`,**FastAPI** 加载请求体时会自动解压。 - -## 在异常处理器中访问请求体 - -!!! tip "提示" - - 为了解决同样的问题,在 `RequestValidationError` 的自定义处理器使用 `body` ([处理错误](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank})可能会更容易。 - - 但本例仍然可行,而且本例展示了如何与内部组件进行交互。 - -同样也可以在异常处理器中访问请求体。 - -此时要做的只是处理 `try`/`except` 中的请求: - -```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` - -发生异常时,`Request` 实例仍在作用域内,因此处理错误时可以读取和使用请求体: - -```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` - -## 在路由中自定义 `APIRoute` 类 - -您还可以设置 `APIRoute` 的 `route_class` 参数: - -```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` - -本例中,*路径操作*下的 `router` 使用自定义的 `TimedRoute` 类,并在响应中包含输出生成响应时间的 `X-Response-Time` 响应头: - -```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` diff --git a/docs/zh/docs/advanced/extending-openapi.md b/docs/zh/docs/advanced/extending-openapi.md deleted file mode 100644 index 466961462..000000000 --- a/docs/zh/docs/advanced/extending-openapi.md +++ /dev/null @@ -1,252 +0,0 @@ -# 扩展 OpenAPI - -!!! warning "警告" - - 本章介绍的功能较难,您可以跳过阅读。 - - 如果您刚开始学习**用户指南**,最好跳过本章。 - - 如果您确定要修改 OpenAPI 概图,请继续阅读。 - -某些情况下,我们需要修改 OpenAPI 概图。 - -本章介绍如何修改 OpenAPI 概图。 - -## 常规流程 - -常规(默认)流程如下。 - -`FastAPI` 应用(实例)提供了返回 OpenAPI 概图的 `.openapi()` 方法。 - -作为应用对象创建的组成部分,要注册 `/openapi.json` (或其它为 `openapi_url` 设置的任意内容)*路径操作*。 - -它只返回包含应用的 `.openapi()` 方法操作结果的 JSON 响应。 - -但默认情况下,`.openapi()` 只是检查 `.openapi_schema` 属性是否包含内容,并返回其中的内容。 - -如果 `.openapi_schema` 属性没有内容,该方法就使用 `fastapi.openapi.utils.get_openapi` 工具函数生成内容。 - -`get_openapi()` 函数接收如下参数: - -* `title`:文档中显示的 OpenAPI 标题 -* `version`:API 的版本号,例如 `2.5.0` -* `openapi_version`: OpenAPI 规范的版本号,默认为最新版: `3.0.2` -* `description`:API 的描述说明 -* `routes`:路由列表,每个路由都是注册的*路径操作*。这些路由是从 `app.routes` 中提取的。 - -## 覆盖默认值 - -`get_openapi()` 工具函数还可以用于生成 OpenAPI 概图,并利用上述信息参数覆盖指定的内容。 - -例如,使用 <a href="https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo" class="external-link" target="_blank">ReDoc 的 OpenAPI 扩展添加自定义 Logo</a>。 - -### 常规 **FastAPI** - -首先,编写常规 **FastAPI** 应用: - -```Python hl_lines="1 4 7-9" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 生成 OpenAPI 概图 - -然后,在 `custom_openapi()` 函数里使用 `get_openapi()` 工具函数生成 OpenAPI 概图: - -```Python hl_lines="2 15-20" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 修改 OpenAPI 概图 - -添加 ReDoc 扩展信息,为 OpenAPI 概图里的 `info` **对象**添加自定义 `x-logo`: - -```Python hl_lines="21-23" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 缓存 OpenAPI 概图 - -把 `.openapi_schema` 属性当作**缓存**,存储生成的概图。 - -通过这种方式,**FastAPI** 应用不必在用户每次打开 API 文档时反复生成概图。 - -只需生成一次,下次请求时就可以使用缓存的概图。 - -```Python hl_lines="13-14 24-25" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 覆盖方法 - -用新函数替换 `.openapi()` 方法。 - -```Python hl_lines="28" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` - -### 查看文档 - -打开 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc,查看</a>自定义 Logo(本例中是 **FastAPI** 的 Logo): - -<img src="/img/tutorial/extending-openapi/image01.png"> - -## 文档 JavaScript 与 CSS 自托管 - -FastAPI 支持 **Swagger UI** 和 **ReDoc** 两种 API 文档,这两种文档都需要调用 JavaScript 与 CSS 文件。 - -这些文件默认由 <abbr title="Content Delivery Network(内容分发网络): 由多台服务器为 JavaScript 和 CSS 等静态文件支持的服务。一般来说,从靠近客户端的服务器提供静态文件服务可以提高性能。">CDN</abbr> 提供支持服务。 - -但也可以自定义设置指定的 CDN 或自行提供文件服务。 - -这种做法很常用,例如,在没有联网或本地局域网时也能让应用在离线状态下正常运行。 - -本文介绍如何为 FastAPI 应用提供文件自托管服务,并设置文档使用这些文件。 - -### 项目文件架构 - -假设项目文件架构如下: - -``` -. -├── app -│ ├── __init__.py -│ ├── main.py -``` - -接下来,创建存储静态文件的文件夹。 - -新的文件架构如下: - -``` -. -├── app -│ ├── __init__.py -│ ├── main.py -└── static/ -``` - -### 下载文件 - -下载文档所需的静态文件,把文件放到 `static/` 文件夹里。 - -右键点击链接,选择**另存为...**。 - -**Swagger UI** 使用如下文件: - -* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a> -* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a> - -**ReDoc** 使用如下文件: - -* <a href="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js" class="external-link" target="_blank">`redoc.standalone.js`</a> - -保存好后,文件架构所示如下: - -``` -. -├── app -│ ├── __init__.py -│ ├── main.py -└── static - ├── redoc.standalone.js - ├── swagger-ui-bundle.js - └── swagger-ui.css -``` - -### 安装 `aiofiles` - -现在,安装 `aiofiles`: - - -<div class="termy"> - -```console -$ pip install aiofiles - ----> 100% -``` - -</div> - -### 静态文件服务 - -* 导入 `StaticFiles` -* 在指定路径下**挂载** `StaticFiles()` 实例 - -```Python hl_lines="7 11" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### 测试静态文件 - -启动应用,打开 <a href="http://127.0.0.1:8000/static/redoc.standalone.js" class="external-link" target="_blank">http://127.0.0.1:8000/static/redoc.standalone.js。</a> - -就能看到 **ReDoc** 的 JavaScript 文件。 - -该文件开头如下: - -```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 - -... -``` - -能打开这个文件就表示 FastAPI 应用能提供静态文件服务,并且文档要调用的静态文件放到了正确的位置。 - -接下来,使用静态文件配置文档。 - -### 禁用 API 文档 - -第一步是禁用 API 文档,就是使用 CDN 的默认文档。 - -创建 `FastAPI` 应用时把文档的 URL 设置为 `None` 即可禁用默认文档: - -```Python hl_lines="9" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### 添加自定义文档 - -现在,创建自定义文档的*路径操作*。 - -导入 FastAPI 内部函数为文档创建 HTML 页面,并把所需参数传递给这些函数: - -* `openapi_url`: API 文档获取 OpenAPI 概图的 HTML 页面,此处可使用 `app.openapi_url` -* `title`:API 的标题 -* `oauth2_redirect_url`:此处使用 `app.swagger_ui_oauth2_redirect_url` 作为默认值 -* `swagger_js_url`:Swagger UI 文档所需 **JavaScript** 文件的 URL,即为应用提供服务的文件 -* `swagger_css_url`:Swagger UI 文档所需 **CSS** 文件的 URL,即为应用提供服务的文件 - -添加 ReDoc 文档的方式与此类似…… - -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -!!! tip "提示" - - `swagger_ui_redirect` 的*路径操作*是 OAuth2 的辅助函数。 - - 集成 API 与 OAuth2 第三方应用时,您能进行身份验证,使用请求凭证返回 API 文档,并使用真正的 OAuth2 身份验证与 API 文档进行交互操作。 - - Swagger UI 在后台进行处理,但它需要这个**重定向**辅助函数。 - -### 创建测试*路径操作* - -现在,测试各项功能是否能顺利运行。创建*路径操作*: - -```Python hl_lines="39-41" -{!../../../docs_src/extending_openapi/tutorial002.py!} -``` - -### 测试文档 - -断开 WiFi 连接,打开 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs,刷新页面。</a> - -现在,就算没有联网也能查看并操作 API 文档。 diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md index 824f91f47..e39eed805 100644 --- a/docs/zh/docs/advanced/index.md +++ b/docs/zh/docs/advanced/index.md @@ -2,7 +2,7 @@ ## 额外特性 -主要的教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。 +主要的教程 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。 你会在接下来的章节中了解到其他的选项、配置以及额外的特性。 @@ -13,6 +13,6 @@ ## 先阅读教程 -你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 中的大多数特性。 +你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 中的大多数特性。 -接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/){.internal-link target=_blank},并且假设你已经知晓其中主要思想。 +接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank},并且假设你已经知晓其中主要思想。 diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md index fdc8075c7..e2bef4765 100644 --- a/docs/zh/docs/advanced/security/index.md +++ b/docs/zh/docs/advanced/security/index.md @@ -2,7 +2,7 @@ ## 附加特性 -除 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. +除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. !!! tip "小贴士" 接下来的章节 **并不一定是 "高级的"**. @@ -11,6 +11,6 @@ ## 先阅读教程 -接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank}. +接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank}. 它们都基于相同的概念,但支持一些额外的功能. diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index 59eebd049..ed0e6e497 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -405,7 +405,7 @@ Starlette (和 **FastAPI**) 是基于 <a href="https://anyio.readthedocs.io/ 如果您使用过另一个不以上述方式工作的异步框架,并且您习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 <abbr title="输入/输出:磁盘读写,网络通讯.">I/O</abbr> 的代码。 -在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](/#performance){.internal-link target=_blank}。 +在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](index.md#performance){.internal-link target=_blank}。 ### 依赖 diff --git a/docs/zh/docs/deployment/deta.md b/docs/zh/docs/deployment/deta.md deleted file mode 100644 index a7390f786..000000000 --- a/docs/zh/docs/deployment/deta.md +++ /dev/null @@ -1,244 +0,0 @@ -# 在 Deta 上部署 FastAPI - -本节介绍如何使用 <a href="https://www.deta.sh/?ref=fastapi" class="external-link" target="_blank">Deta</a> 免费方案部署 **FastAPI** 应用。🎁 - -部署操作需要大约 10 分钟。 - -!!! info "说明" - - <a href="https://www.deta.sh/?ref=fastapi" class="external-link" target="_blank">Deta</a> 是 **FastAPI** 的赞助商。 🎉 - -## 基础 **FastAPI** 应用 - -* 创建应用文件夹,例如 `./fastapideta/`,进入文件夹 - -### FastAPI 代码 - -* 创建包含如下代码的 `main.py`: - -```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): - return {"item_id": item_id} -``` - -### 需求项 - -在文件夹里新建包含如下内容的 `requirements.txt` 文件: - -```text -fastapi -``` - -!!! tip "提示" - - 在 Deta 上部署时无需安装 Uvicorn,虽然在本地测试应用时需要安装。 - -### 文件夹架构 - -`./fastapideta/` 文件夹中现在有两个文件: - -``` -. -└── main.py -└── requirements.txt -``` - -## 创建免费 Deta 账号 - -创建<a href="https://www.deta.sh/?ref=fastapi" class="external-link" target="_blank">免费的 Deta 账号</a>,只需要电子邮件和密码。 - -甚至不需要信用卡。 - -## 安装 CLI - -创建账号后,安装 Deta <abbr title="Command Line Interface application">CLI</abbr>: - -=== "Linux, macOS" - - <div class="termy"> - - ```console - $ curl -fsSL https://get.deta.dev/cli.sh | sh - ``` - - </div> - -=== "Windows PowerShell" - - <div class="termy"> - - ```console - $ iwr https://get.deta.dev/cli.ps1 -useb | iex - ``` - - </div> - -安装完 CLI 后,打开新的 Terminal,就能检测到刚安装的 CLI。 - -在新的 Terminal 里,用以下命令确认 CLI 是否正确安装: - -<div class="termy"> - -```console -$ deta --help - -Deta command line interface for managing deta micros. -Complete documentation available at https://docs.deta.sh - -Usage: - deta [flags] - deta [command] - -Available Commands: - auth Change auth settings for a deta micro - -... -``` - -</div> - -!!! tip "提示" - - 安装 CLI 遇到问题时,请参阅 <a href="https://docs.deta.sh/docs/micros/getting_started?ref=fastapi" class="external-link" target="_blank">Deta 官档</a>。 - -## 使用 CLI 登录 - -现在,使用 CLI 登录 Deta: - -<div class="termy"> - -```console -$ deta login - -Please, log in from the web page. Waiting.. -Logged in successfully. -``` - -</div> - -这个命令会打开浏览器并自动验证身份。 - -## 使用 Deta 部署 - -接下来,使用 Deta CLI 部署应用: - -<div class="termy"> - -```console -$ deta new - -Successfully created a new micro - -// Notice the "endpoint" 🔍 - -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} - -Adding dependencies... - - ----> 100% - - -Successfully installed fastapi-0.61.1 pydantic-1.7.2 starlette-0.13.6 -``` - -</div> - -您会看到如下 JSON 信息: - -```JSON hl_lines="4" -{ - "name": "fastapideta", - "runtime": "python3.7", - "endpoint": "https://qltnci.deta.dev", - "visor": "enabled", - "http_auth": "enabled" -} -``` - -!!! tip "提示" - - 您部署时的 `"endpoint"` URL 可能会有所不同。 - -## 查看效果 - -打开浏览器,跳转到 `endpoint` URL。本例中是 `https://qltnci.deta.dev`,但您的链接可能与此不同。 - -FastAPI 应用会返回如下 JSON 响应: - -```JSON -{ - "Hello": "World" -} -``` - -接下来,跳转到 API 文档 `/docs`,本例中是 `https://qltnci.deta.dev/docs`。 - -文档显示如下: - -<img src="/img/deployment/deta/image01.png"> - -## 启用公开访问 - -默认情况下,Deta 使用您的账号 Cookies 处理身份验证。 - -应用一切就绪之后,使用如下命令让公众也能看到您的应用: - -<div class="termy"> - -```console -$ deta auth disable - -Successfully disabled http auth -``` - -</div> - -现在,就可以把 URL 分享给大家,他们就能访问您的 API 了。🚀 - -## HTTPS - -恭喜!您已经在 Deta 上部署了 FastAPI 应用!🎉 🍰 - -还要注意,Deta 能够正确处理 HTTPS,因此您不必操心 HTTPS,您的客户端肯定能有安全加密的连接。 ✅ 🔒 - -## 查看 Visor - -从 API 文档(URL 是 `https://gltnci.deta.dev/docs`)发送请求至*路径操作* `/items/{item_id}`。 - -例如,ID `5`。 - -现在跳转至 <a href="https://web.deta.sh/" class="external-link" target="_blank">https://web.deta.sh。</a> - -左边栏有个 <abbr title="it comes from Micro(server)">"Micros"</abbr> 标签,里面是所有的应用。 - -还有一个 **Details** 和 **Visor** 标签,跳转到 **Visor** 标签。 - -在这里查看最近发送给应用的请求。 - -您可以编辑或重新使用这些请求。 - -<img src="/img/deployment/deta/image02.png"> - -## 更多内容 - -如果要持久化保存应用数据,可以使用提供了**免费方案**的 <a href="https://docs.deta.sh/docs/base/py_tutorial?ref=fastapi" class="external-link" target="_blank">Deta Base</a>。 - -详见 <a href="https://docs.deta.sh?ref=fastapi" class="external-link" target="_blank">Deta 官档</a>。 diff --git a/docs/zh/docs/external-links.md b/docs/zh/docs/external-links.md deleted file mode 100644 index 8c919fa38..000000000 --- a/docs/zh/docs/external-links.md +++ /dev/null @@ -1,83 +0,0 @@ -# 外部链接与文章 - -**FastAPI** 社区正在不断壮大。 - -有关 **FastAPI** 的帖子、文章、工具和项目越来越多。 - -以下是 **FastAPI** 各种资源的不完整列表。 - -!!! tip "提示" - - 如果您的文章、项目、工具或其它任何与 **FastAPI** 相关的内容尚未收入此表,请在此创建 <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">PR</a>。 - -## 文章 - -### 英文 - -{% if external_links %} -{% for article in external_links.articles.english %} - -* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. -{% endfor %} -{% endif %} - -### 日文 - -{% if external_links %} -{% for article in external_links.articles.japanese %} - -* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. -{% endfor %} -{% endif %} - -### 越南语 - -{% if external_links %} -{% for article in external_links.articles.vietnamese %} - -* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. -{% endfor %} -{% endif %} - -### 俄语 - -{% if external_links %} -{% for article in external_links.articles.russian %} - -* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. -{% endfor %} -{% endif %} - -### 德语 - -{% if external_links %} -{% for article in external_links.articles.german %} - -* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. -{% endfor %} -{% endif %} - -## 播客 - -{% if external_links %} -{% for article in external_links.podcasts.english %} - -* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. -{% endfor %} -{% endif %} - -## 访谈 - -{% if external_links %} -{% for article in external_links.talks.english %} - -* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>. -{% endfor %} -{% endif %} - -## 项目 - -GitHub 上最新的 `fastapi` 主题项目: - -<div class="github-topic-projects"> -</div> diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index 9b70d115a..1a9aa57d0 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -12,7 +12,7 @@ ## 订阅新闻邮件 -您可以订阅 [**FastAPI 和它的小伙伴** 新闻邮件](/newsletter/){.internal-link target=_blank}(不会经常收到) +您可以订阅 [**FastAPI 和它的小伙伴** 新闻邮件](newsletter.md){.internal-link target=_blank}(不会经常收到) * FastAPI 及其小伙伴的新闻 🚀 * 指南 📝 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 09b106273..8170e6ecc 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -1,4 +1,5 @@ # 元数据和文档 URL + 你可以在 FastAPI 应用程序中自定义多个元数据配置。 ## API 元数据 @@ -54,7 +55,7 @@ ``` !!! 信息 - 阅读更多关于标签的信息[路径操作配置](../path-operation-configuration/#tags){.internal-link target=_blank}。 + 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 ### 查看文档 From 242ed3bf95df679cdccd4880e539aa2ab2f40a8f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 31 Mar 2024 23:53:11 +0000 Subject: [PATCH 332/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 52f51d19d..702aee32b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Tweak docs and translations links and remove old docs translations. PR [#11381](https://github.com/tiangolo/fastapi/pull/11381) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#11368](https://github.com/tiangolo/fastapi/pull/11368) by [@shandongbinzhou](https://github.com/shandongbinzhou). * 📝 Update links to Pydantic docs to point to new website. PR [#11328](https://github.com/tiangolo/fastapi/pull/11328) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo in `docs/en/docs/tutorial/extra-models.md`. PR [#11329](https://github.com/tiangolo/fastapi/pull/11329) by [@alejsdev](https://github.com/alejsdev). From 8108cdb737783f82a2fd4c4369f391e971ef5301 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Mon, 1 Apr 2024 09:15:53 +0800 Subject: [PATCH 333/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/tutorial/extra-models.md`=20(#3497)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/extra-models.md | 106 +++++++++++++------------- 1 file changed, 55 insertions(+), 51 deletions(-) diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index f89d58dd1..94d82c524 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -1,21 +1,22 @@ -# 额外的模型 +# 更多模型 -我们从前面的示例继续,拥有多个相关的模型是很常见的。 +书接上文,多个关联模型这种情况很常见。 -对用户模型来说尤其如此,因为: +特别是用户模型,因为: -* **输入模型**需要拥有密码属性。 -* **输出模型**不应该包含密码。 -* **数据库模型**很可能需要保存密码的哈希值。 +* **输入模型**应该含密码 +* **输出模型**不应含密码 +* **数据库模型**需要加密的密码 -!!! danger - 永远不要存储用户的明文密码。始终存储一个可以用于验证的「安全哈希值」。 +!!! danger "危险" - 如果你尚未了解该知识,你可以在[安全章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}中学习何为「密码哈希值」。 + 千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 + + 如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 ## 多个模型 -下面是应该如何根据它们的密码字段以及使用位置去定义模型的大概思路: +下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路: === "Python 3.10+" @@ -29,35 +30,35 @@ {!> ../../../docs_src/extra_models/tutorial001.py!} ``` -### 关于 `**user_in.dict()` +### `**user_in.dict()` 简介 #### Pydantic 的 `.dict()` -`user_in` 是一个 `UserIn` 类的 Pydantic 模型. +`user_in` 是类 `UserIn` 的 Pydantic 模型。 -Pydantic 模型具有 `.dict()` 方法,该方法返回一个拥有模型数据的 `dict`。 +Pydantic 模型支持 `.dict()` 方法,能返回包含模型数据的**字典**。 -因此,如果我们像下面这样创建一个 Pydantic 对象 `user_in`: +因此,如果使用如下方式创建 Pydantic 对象 `user_in`: ```Python user_in = UserIn(username="john", password="secret", email="john.doe@example.com") ``` -然后我们调用: +就能以如下方式调用: ```Python user_dict = user_in.dict() ``` -现在我们有了一个数据位于变量 `user_dict` 中的 `dict`(它是一个 `dict` 而不是 Pydantic 模型对象)。 +现在,变量 `user_dict`中的就是包含数据的**字典**(变量 `user_dict` 是字典,不是 Pydantic 模型对象)。 -如果我们调用: +以如下方式调用: ```Python print(user_dict) ``` -我们将获得一个这样的 Python `dict`: +输出的就是 Python **字典**: ```Python { @@ -70,15 +71,15 @@ print(user_dict) #### 解包 `dict` -如果我们将 `user_dict` 这样的 `dict` 以 `**user_dict` 形式传递给一个函数(或类),Python将对其进行「解包」。它会将 `user_dict` 的键和值作为关键字参数直接传递。 +把**字典** `user_dict` 以 `**user_dict` 形式传递给函数(或类),Python 会执行**解包**操作。它会把 `user_dict` 的键和值作为关键字参数直接传递。 -因此,从上面的 `user_dict` 继续,编写: +因此,接着上面的 `user_dict` 继续编写如下代码: ```Python UserInDB(**user_dict) ``` -会产生类似于以下的结果: +就会生成如下结果: ```Python UserInDB( @@ -89,7 +90,7 @@ UserInDB( ) ``` -或者更确切地,直接使用 `user_dict` 来表示将来可能包含的任何内容: +或更精准,直接把可能会用到的内容与 `user_dict` 一起使用: ```Python UserInDB( @@ -100,34 +101,34 @@ UserInDB( ) ``` -#### 来自于其他模型内容的 Pydantic 模型 +#### 用其它模型中的内容生成 Pydantic 模型 -如上例所示,我们从 `user_in.dict()` 中获得了 `user_dict`,此代码: +上例中 ,从 `user_in.dict()` 中得到了 `user_dict`,下面的代码: ```Python user_dict = user_in.dict() UserInDB(**user_dict) ``` -等同于: +等效于: ```Python UserInDB(**user_in.dict()) ``` -...因为 `user_in.dict()` 是一个 `dict`,然后我们通过以`**`开头传递给 `UserInDB` 来使 Python「解包」它。 +……因为 `user_in.dict()` 是字典,在传递给 `UserInDB` 时,把 `**` 加在 `user_in.dict()` 前,可以让 Python 进行**解包**。 -这样,我们获得了一个来自于其他 Pydantic 模型中的数据的 Pydantic 模型。 +这样,就可以用其它 Pydantic 模型中的数据生成 Pydantic 模型。 -#### 解包 `dict` 和额外关键字 +#### 解包 `dict` 和更多关键字 -然后添加额外的关键字参数 `hashed_password=hashed_password`,例如: +接下来,继续添加关键字参数 `hashed_password=hashed_password`,例如: ```Python UserInDB(**user_in.dict(), hashed_password=hashed_password) ``` -...最终的结果如下: +……输出结果如下: ```Python UserInDB( @@ -139,24 +140,27 @@ UserInDB( ) ``` -!!! warning - 辅助性的额外函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全性。 +!!! warning "警告" + + 辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 ## 减少重复 -减少代码重复是 **FastAPI** 的核心思想之一。 +**FastAPI** 的核心思想就是减少代码重复。 + +代码重复会导致 bug、安全问题、代码失步等问题(更新了某个位置的代码,但没有同步更新其它位置的代码)。 -因为代码重复会增加出现 bug、安全性问题、代码失步问题(当你在一个位置更新了代码但没有在其他位置更新)等的可能性。 +上面的这些模型共享了大量数据,拥有重复的属性名和类型。 -上面的这些模型都共享了大量数据,并拥有重复的属性名称和类型。 +FastAPI 可以做得更好。 -我们可以做得更好。 +声明 `UserBase` 模型作为其它模型的基类。然后,用该类衍生出继承其属性(类型声明、验证等)的子类。 -我们可以声明一个 `UserBase` 模型作为其他模型的基类。然后我们可以创建继承该模型属性(类型声明,校验等)的子类。 +所有数据转换、校验、文档等功能仍将正常运行。 -所有的数据转换、校验、文档生成等仍将正常运行。 +这样,就可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。 -这样,我们可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。 +通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。 === "Python 3.10+" @@ -172,15 +176,15 @@ UserInDB( ## `Union` 或者 `anyOf` -你可以将一个响应声明为两种类型的 `Union`,这意味着该响应将是两种类型中的任何一种。 +响应可以声明为两种类型的 `Union` 类型,即该响应可以是两种类型中的任意类型。 -这将在 OpenAPI 中使用 `anyOf` 进行定义。 +在 OpenAPI 中可以使用 `anyOf` 定义。 -为此,请使用标准的 Python 类型提示 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: +为此,请使用 Python 标准类型提示 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: +!!! note "笔记" -!!! note - 定义一个 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 + 定义 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 === "Python 3.10+" @@ -196,7 +200,7 @@ UserInDB( ## 模型列表 -你可以用同样的方式声明由对象列表构成的响应。 +使用同样的方式也可以声明由对象列表构成的响应。 为此,请使用标准的 Python `typing.List`: @@ -214,11 +218,11 @@ UserInDB( ## 任意 `dict` 构成的响应 -你还可以使用一个任意的普通 `dict` 声明响应,仅声明键和值的类型,而不使用 Pydantic 模型。 +任意的 `dict` 都能用于声明响应,只要声明键和值的类型,无需使用 Pydantic 模型。 -如果你事先不知道有效的字段/属性名称(对于 Pydantic 模型是必需的),这将很有用。 +事先不知道可用的字段 / 属性名时(Pydantic 模型必须知道字段是什么),这种方式特别有用。 -在这种情况下,你可以使用 `typing.Dict`: +此时,可以使用 `typing.Dict`: === "Python 3.9+" @@ -232,8 +236,8 @@ UserInDB( {!> ../../../docs_src/extra_models/tutorial005.py!} ``` -## 总结 +## 小结 -使用多个 Pydantic 模型,并针对不同场景自由地继承。 +针对不同场景,可以随意使用不同的 Pydantic 模型继承定义的基类。 -如果一个实体必须能够具有不同的「状态」,你无需为每个状态的实体定义单独的数据模型。以用户「实体」为例,其状态有包含 `password`、包含 `password_hash` 以及不含密码。 +实体必须具有不同的**状态**时,不必为不同状态的实体单独定义数据模型。例如,用户**实体**就有包含 `password`、包含 `password_hash` 以及不含密码等多种状态。 From 620cdb5567f709c07a3a641ac2134501415b811d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Apr 2024 01:16:17 +0000 Subject: [PATCH 334/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 702aee32b..e5b9a5a9d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/tutorial/extra-models.md`. PR [#3497](https://github.com/tiangolo/fastapi/pull/3497) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/metadata.md`. PR [#2667](https://github.com/tiangolo/fastapi/pull/2667) by [@tokusumi](https://github.com/tokusumi). * 🌐 Add German translation for `docs/de/docs/contributing.md`. PR [#10487](https://github.com/tiangolo/fastapi/pull/10487) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Japanese translation of `docs/ja/docs/tutorial/query-params.md`. PR [#10808](https://github.com/tiangolo/fastapi/pull/10808) by [@urushio](https://github.com/urushio). From cc8d20e6545cc2a046aedb4a3a1b3b6906e61981 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Mon, 1 Apr 2024 13:35:27 +0800 Subject: [PATCH 335/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/tutorial/body-fields.md`=20(#3496)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/body-fields.md | 39 +++++++++++++++------------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index fb6c6d9b6..6c68f1008 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -1,10 +1,10 @@ # 请求体 - 字段 -与使用 `Query`、`Path` 和 `Body` 在*路径操作函数*中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。 +与在*路径操作函数*中使用 `Query`、`Path` 、`Body` 声明校验与元数据的方式一样,可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。 ## 导入 `Field` -首先,你必须导入它: +首先,从 Pydantic 中导入 `Field`: === "Python 3.10+" @@ -42,12 +42,13 @@ {!> ../../../docs_src/body_fields/tutorial001.py!} ``` -!!! warning - 注意,`Field` 是直接从 `pydantic` 导入的,而不是像其他的(`Query`,`Path`,`Body` 等)都从 `fastapi` 导入。 +!!! warning "警告" + + 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 ## 声明模型属性 -然后,你可以对模型属性使用 `Field`: +然后,使用 `Field` 定义模型的属性: === "Python 3.10+" @@ -85,28 +86,30 @@ {!> ../../../docs_src/body_fields/tutorial001.py!} ``` -`Field` 的工作方式和 `Query`、`Path` 和 `Body` 相同,包括它们的参数等等也完全相同。 +`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 !!! note "技术细节" - 实际上,`Query`、`Path` 和其他你将在之后看到的类,创建的是由一个共同的 `Params` 类派生的子类的对象,该共同类本身又是 Pydantic 的 `FieldInfo` 类的子类。 - Pydantic 的 `Field` 也会返回一个 `FieldInfo` 的实例。 + 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 + + Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 + + `Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。 - `Body` 也直接返回 `FieldInfo` 的一个子类的对象。还有其他一些你之后会看到的类是 `Body` 类的子类。 + 注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。 - 请记住当你从 `fastapi` 导入 `Query`、`Path` 等对象时,他们实际上是返回特殊类的函数。 +!!! tip "提示" -!!! tip - 注意每个模型属性如何使用类型、默认值和 `Field` 在代码结构上和*路径操作函数*的参数是相同的,区别是用 `Field` 替换`Path`、`Query` 和 `Body`。 + 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 -## 添加额外信息 +## 添加更多信息 -你可以在 `Field`、`Query`、`Body` 中声明额外的信息。这些信息将包含在生成的 JSON Schema 中。 +`Field`、`Query`、`Body` 等对象里可以声明更多信息,并且 JSON Schema 中也会集成这些信息。 -你将在文档的后面部分学习声明示例时,了解到更多有关添加额外信息的知识。 +*声明示例*一章中将详细介绍添加更多信息的知识。 -## 总结 +## 小结 -你可以使用 Pydantic 的 `Field` 为模型属性声明额外的校验和元数据。 +Pydantic 的 `Field` 可以为模型属性声明更多校验和元数据。 -你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。 +传递 JSON Schema 元数据还可以使用更多关键字参数。 From 1e06b177ccffffe8f85f4499b9d3babce39f8d9c Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Mon, 1 Apr 2024 13:35:40 +0800 Subject: [PATCH 336/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/path-params.md`=20(#3479)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/path-params.md | 184 +++++++++++++++------------ 1 file changed, 101 insertions(+), 83 deletions(-) diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 5bb4eba80..12a08b4a3 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -1,48 +1,50 @@ # 路径参数 -你可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量": +FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**): ```Python hl_lines="6-7" {!../../../docs_src/path_params/tutorial001.py!} ``` -路径参数 `item_id` 的值将作为参数 `item_id` 传递给你的函数。 +这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。 -所以,如果你运行示例并访问 <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a>,将会看到如下响应: +运行示例并访问 <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a>,可获得如下响应: ```JSON {"item_id":"foo"} ``` -## 有类型的路径参数 +## 声明路径参数的类型 -你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。 +使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。 ```Python hl_lines="7" {!../../../docs_src/path_params/tutorial002.py!} ``` -在这个例子中,`item_id` 被声明为 `int` 类型。 +本例把 `item_id` 的类型声明为 `int`。 -!!! check - 这将为你的函数提供编辑器支持,包括错误检查、代码补全等等。 +!!! check "检查" -## 数据<abbr title="也被称为:序列化、解析">转换</abbr> + 类型声明将为函数提供错误检查、代码补全等编辑器支持。 -如果你运行示例并打开浏览器访问 <a href="http://127.0.0.1:8000/items/3" class="external-link" target="_blank">http://127.0.0.1:8000/items/3</a>,将得到如下响应: +## 数据<abbr title="也称为:序列化、解析">转换</abbr> + +运行示例并访问 <a href="http://127.0.0.1:8000/items/3" class="external-link" target="_blank">http://127.0.0.1:8000/items/3</a>,返回的响应如下: ```JSON {"item_id":3} ``` -!!! check - 注意函数接收(并返回)的值为 3,是一个 Python `int` 值,而不是字符串 `"3"`。 +!!! check "检查" + + 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 - 所以,**FastAPI** 通过上面的类型声明提供了对请求的自动<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">"解析"</abbr>。 + **FastAPI** 通过类型声明自动<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">**解析**请求中的数据</abbr>。 ## 数据校验 -但如果你通过浏览器访问 <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a>,你会看到一个清晰可读的 HTTP 错误: +通过浏览器访问 <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a>,接收如下 HTTP 错误信息: ```JSON { @@ -59,86 +61,91 @@ } ``` -因为路径参数 `item_id` 传入的值为 `"foo"`,它不是一个 `int`。 +这是因为路径参数 `item_id` 的值 (`"foo"`)的类型不是 `int`。 + +值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2。</a> + +!!! check "检查" -如果你提供的是 `float` 而非整数也会出现同样的错误,比如: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> + **FastAPI** 使用 Python 类型声明实现了数据校验。 -!!! check - 所以,通过同样的 Python 类型声明,**FastAPI** 提供了数据校验功能。 + 注意,上面的错误清晰地指出了未通过校验的具体原因。 - 注意上面的错误同样清楚地指出了校验未通过的具体原因。 + 这在开发调试与 API 交互的代码时非常有用。 - 在开发和调试与你的 API 进行交互的代码时,这非常有用。 +## 查看文档 -## 文档 +访问 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>,查看自动生成的 API 文档: -当你打开浏览器访问 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>,你将看到自动生成的交互式 API 文档: +<img src="/img/tutorial/path-params/image01.png"> -<img src="https://fastapi.tiangolo.com/img/tutorial/path-params/image01.png"> +!!! check "检查" -!!! check - 再一次,还是通过相同的 Python 类型声明,**FastAPI** 为你提供了自动生成的交互式文档(集成 Swagger UI)。 + 还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 - 注意这里的路径参数被声明为一个整数。 + 注意,路径参数的类型是整数。 -## 基于标准的好处:可选文档 +## 基于标准的好处,备选文档 -由于生成的 API 模式来自于 <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md" class="external-link" target="_blank">OpenAPI</a> 标准,所以有很多工具与其兼容。 +**FastAPI** 使用 <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md" class="external-link" target="_blank">OpenAPI</a> 生成概图,所以能兼容很多工具。 -正因如此,**FastAPI** 内置了一个可选的 API 文档(使用 Redoc): +因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>: -<img src="https://fastapi.tiangolo.com/img/tutorial/path-params/image02.png"> +<img src="/img/tutorial/path-params/image02.png"> -同样的,还有很多其他兼容的工具,包括适用于多种语言的代码生成工具。 +同样,还有很多兼容工具,包括多种语言的代码生成工具。 ## Pydantic -所有的数据校验都由 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。 +FastAPI 充分地利用了 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。 -你可以使用同样的类型声明来声明 `str`、`float`、`bool` 以及许多其他的复合数据类型。 +同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。 -本教程的下一章节将探讨其中的一些内容。 +下一章介绍详细内容。 ## 顺序很重要 -在创建*路径操作*时,你会发现有些情况下路径是固定的。 +有时,*路径操作*中的路径是写死的。 -比如 `/users/me`,我们假设它用来获取关于当前用户的数据. +比如要使用 `/users/me` 获取当前用户的数据。 -然后,你还可以使用路径 `/users/{user_id}` 来通过用户 ID 获取关于特定用户的数据。 +然后还要使用 `/users/{user_id}`,通过用户 ID 获取指定用户的数据。 + +由于*路径操作*是按顺序依次运行的,因此,一定要在 `/users/{user_id}` 之前声明 `/users/me` : -由于*路径操作*是按顺序依次运行的,你需要确保路径 `/users/me` 声明在路径 `/users/{user_id}`之前: ```Python hl_lines="6 11" {!../../../docs_src/path_params/tutorial003.py!} ``` -否则,`/users/{user_id}` 的路径还将与 `/users/me` 相匹配,"认为"自己正在接收一个值为 `"me"` 的 `user_id` 参数。 +否则,`/users/{user_id}` 将匹配 `/users/me`,FastAPI 会**认为**正在接收值为 `"me"` 的 `user_id` 参数。 ## 预设值 -如果你有一个接收路径参数的路径操作,但你希望预先设定可能的有效参数值,则可以使用标准的 Python <abbr title="Enumeration">`Enum`</abbr> 类型。 +路径操作使用 Python 的 <abbr title="Enumeration">`Enum`</abbr> 类型接收预设的*路径参数*。 -### 创建一个 `Enum` 类 +### 创建 `Enum` 类 -导入 `Enum` 并创建一个继承自 `str` 和 `Enum` 的子类。 +导入 `Enum` 并创建继承自 `str` 和 `Enum` 的子类。 -通过从 `str` 继承,API 文档将能够知道这些值必须为 `string` 类型并且能够正确地展示出来。 +通过从 `str` 继承,API 文档就能把值的类型定义为**字符串**,并且能正确渲染。 -然后创建具有固定值的类属性,这些固定值将是可用的有效值: +然后,创建包含固定值的类属性,这些固定值是可用的有效值: ```Python hl_lines="1 6-9" {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">枚举(或 enums)</a>从 3.4 版本起在 Python 中可用。 +!!! info "说明" + + Python 3.4 及之后版本支持<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">枚举(即 enums)</a>。 -!!! tip - 如果你想知道,"AlexNet"、"ResNet" 和 "LeNet" 只是机器学习中的<abbr title="技术上来说是深度学习模型架构">模型</abbr>名称。 +!!! tip "提示" + + **AlexNet**、**ResNet**、**LeNet** 是机器学习<abbr title="技术上来说是深度学习模型架构">模型</abbr>。 ### 声明*路径参数* -然后使用你定义的枚举类(`ModelName`)创建一个带有类型标注的*路径参数*: +使用 Enum 类(`ModelName`)创建使用类型注解的*路径参数*: ```Python hl_lines="16" {!../../../docs_src/path_params/tutorial005.py!} @@ -146,17 +153,17 @@ ### 查看文档 -因为已经指定了*路径参数*的可用值,所以交互式文档可以恰当地展示它们: + API 文档会显示预定义*路径参数*的可用值: -<img src="https://fastapi.tiangolo.com/img/tutorial/path-params/image03.png"> +<img src="/img/tutorial/path-params/image03.png"> -### 使用 Python *枚举类型* +### 使用 Python _枚举类型_ -*路径参数*的值将是一个*枚举成员*。 +*路径参数*的值是枚举的元素。 -#### 比较*枚举成员* +#### 比较*枚举元素* -你可以将它与你创建的枚举类 `ModelName` 中的*枚举成员*进行比较: +枚举类 `ModelName` 中的*枚举元素*支持比较操作: ```Python hl_lines="17" {!../../../docs_src/path_params/tutorial005.py!} @@ -164,71 +171,82 @@ #### 获取*枚举值* -你可以使用 `model_name.value` 或通常来说 `your_enum_member.value` 来获取实际的值(在这个例子中为 `str`): +使用 `model_name.value` 或 `your_enum_member.value` 获取实际的值(本例中为**字符串**): -```Python hl_lines="19" +```Python hl_lines="20" {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip - 你也可以通过 `ModelName.lenet.value` 来获取值 `"lenet"`。 +!!! tip "提示" + + 使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。 -#### 返回*枚举成员* +#### 返回*枚举元素* -你可以从*路径操作*中返回*枚举成员*,即使嵌套在 JSON 结构中(例如一个 `dict` 中)。 +即使嵌套在 JSON 请求体里(例如, `dict`),也可以从*路径操作*返回*枚举元素*。 -在返回给客户端之前,它们将被转换为对应的值: +返回给客户端之前,要把枚举元素转换为对应的值(本例中为字符串): -```Python hl_lines="18-21" +```Python hl_lines="18 21 23" {!../../../docs_src/path_params/tutorial005.py!} ``` +客户端中的 JSON 响应如下: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + ## 包含路径的路径参数 -假设你有一个*路径操作*,它的路径为 `/files/{file_path}`。 +假设*路径操作*的路径为 `/files/{file_path}`。 -但是你需要 `file_path` 自身也包含*路径*,比如 `home/johndoe/myfile.txt`。 +但需要 `file_path` 中也包含*路径*,比如,`home/johndoe/myfile.txt`。 -因此,该文件的URL将类似于这样:`/files/home/johndoe/myfile.txt`。 +此时,该文件的 URL 是这样的:`/files/home/johndoe/myfile.txt`。 ### OpenAPI 支持 -OpenAPI 不支持任何方式去声明*路径参数*以在其内部包含*路径*,因为这可能会导致难以测试和定义的情况出现。 +OpenAPI 不支持声明包含路径的*路径参数*,因为这会导致测试和定义更加困难。 -不过,你仍然可以通过 Starlette 的一个内部工具在 **FastAPI** 中实现它。 +不过,仍可使用 Starlette 内置工具在 **FastAPI** 中实现这一功能。 -而且文档依旧可以使用,但是不会添加任何该参数应包含路径的说明。 +而且不影响文档正常运行,但是不会添加该参数包含路径的说明。 ### 路径转换器 -你可以使用直接来自 Starlette 的选项来声明一个包含*路径*的*路径参数*: +直接使用 Starlette 的选项声明包含*路径*的*路径参数*: ``` /files/{file_path:path} ``` -在这种情况下,参数的名称为 `file_path`,结尾部分的 `:path` 说明该参数应匹配任意的*路径*。 +本例中,参数名为 `file_path`,结尾部分的 `:path` 说明该参数应匹配*路径*。 -因此,你可以这样使用它: +用法如下: ```Python hl_lines="6" {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip - 你可能会需要参数包含 `/home/johndoe/myfile.txt`,以斜杠(`/`)开头。 +!!! tip "提示" + + 注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。 - 在这种情况下,URL 将会是 `/files//home/johndoe/myfile.txt`,在`files` 和 `home` 之间有一个双斜杠(`//`)。 + 本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。 -## 总结 +## 小结 -使用 **FastAPI**,通过简短、直观和标准的 Python 类型声明,你将获得: +通过简短、直观的 Python 标准类型声明,**FastAPI** 可以获得: -* 编辑器支持:错误检查,代码补全等 -* 数据 "<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">解析</abbr>" -* 数据校验 -* API 标注和自动生成的文档 +- 编辑器支持:错误检查,代码自动补全等 +- 数据**<abbr title="把来自 HTTP 请求中的字符串转换为 Python 数据类型">解析</abbr>** +- 数据校验 +- API 注解和 API 文档 -而且你只需要声明一次即可。 +只需要声明一次即可。 -这可能是 **FastAPI** 与其他框架相比主要的明显优势(除了原始性能以外)。 +这可能是除了性能以外,**FastAPI** 与其它框架相比的主要优势。 From 6eff70f2949d889e4f0bd64097c3fd820cadbaa3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Apr 2024 05:35:49 +0000 Subject: [PATCH 337/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e5b9a5a9d..e3570aadd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/tutorial/body-fields.md`. PR [#3496](https://github.com/tiangolo/fastapi/pull/3496) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/extra-models.md`. PR [#3497](https://github.com/tiangolo/fastapi/pull/3497) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/metadata.md`. PR [#2667](https://github.com/tiangolo/fastapi/pull/2667) by [@tokusumi](https://github.com/tokusumi). * 🌐 Add German translation for `docs/de/docs/contributing.md`. PR [#10487](https://github.com/tiangolo/fastapi/pull/10487) by [@nilslindemann](https://github.com/nilslindemann). From 66dfbb650466b8b235c6cce4152618283e714474 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Mon, 1 Apr 2024 13:36:16 +0800 Subject: [PATCH 338/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/body.md`=20(#3481)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/body.md | 123 ++++++++++++++++++++-------------- 1 file changed, 72 insertions(+), 51 deletions(-) diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 3d615be39..fa8b54d02 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -1,21 +1,24 @@ # 请求体 -当你需要将数据从客户端(例如浏览器)发送给 API 时,你将其作为「请求体」发送。 +FastAPI 使用**请求体**从客户端(例如浏览器)向 API 发送数据。 -**请求**体是客户端发送给 API 的数据。**响应**体是 API 发送给客户端的数据。 +**请求体**是客户端发送给 API 的数据。**响应体**是 API 发送给客户端的数据。 -你的 API 几乎总是要发送**响应**体。但是客户端并不总是需要发送**请求**体。 +API 基本上肯定要发送**响应体**,但是客户端不一定发送**请求体**。 -我们使用 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。 +使用 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 模型声明**请求体**,能充分利用它的功能和优点。 -!!! info - 你不能使用 `GET` 操作(HTTP 方法)发送请求体。 +!!! info "说明" - 要发送数据,你必须使用下列方法之一:`POST`(较常见)、`PUT`、`DELETE` 或 `PATCH`。 + 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 + + 规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。 + + 我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。 ## 导入 Pydantic 的 `BaseModel` -首先,你需要从 `pydantic` 中导入 `BaseModel`: +从 `pydantic` 中导入 `BaseModel`: === "Python 3.10+" @@ -31,9 +34,9 @@ ## 创建数据模型 -然后,将你的数据模型声明为继承自 `BaseModel` 的类。 +把数据模型声明为继承 `BaseModel` 的类。 -使用标准的 Python 类型来声明所有属性: +使用 Python 标准类型声明所有属性: === "Python 3.10+" @@ -47,9 +50,9 @@ {!> ../../../docs_src/body/tutorial001.py!} ``` -和声明查询参数时一样,当一个模型属性具有默认值时,它不是必需的。否则它是一个必需属性。将默认值设为 `None` 可使其成为可选属性。 +与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 -例如,上面的模型声明了一个这样的 JSON「`object`」(或 Python `dict`): +例如,上述模型声明如下 JSON **对象**(即 Python **字典**): ```JSON { @@ -60,7 +63,7 @@ } ``` -...由于 `description` 和 `tax` 是可选的(它们的默认值为 `None`),下面的 JSON「`object`」也将是有效的: +……由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON **对象**也有效: ```JSON { @@ -69,9 +72,9 @@ } ``` -## 声明为参数 +## 声明请求体参数 -使用与声明路径和查询参数的相同方式声明请求体,即可将其添加到「路径操作」中: +使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: === "Python 3.10+" @@ -85,56 +88,68 @@ {!> ../../../docs_src/body/tutorial001.py!} ``` -...并且将它的类型声明为你创建的 `Item` 模型。 +……此处,请求体参数的类型为 `Item` 模型。 -## 结果 +## 结论 -仅仅使用了 Python 类型声明,**FastAPI** 将会: +仅使用 Python 类型声明,**FastAPI** 就可以: -* 将请求体作为 JSON 读取。 -* 转换为相应的类型(在需要时)。 -* 校验数据。 - * 如果数据无效,将返回一条清晰易读的错误信息,指出不正确数据的确切位置和内容。 -* 将接收的数据赋值到参数 `item` 中。 - * 由于你已经在函数中将它声明为 `Item` 类型,你还将获得对于所有属性及其类型的一切编辑器支持(代码补全等)。 -* 为你的模型生成 <a href="https://json-schema.org" class="external-link" target="_blank">JSON 模式</a> 定义,你还可以在其他任何对你的项目有意义的地方使用它们。 -* 这些模式将成为生成的 OpenAPI 模式的一部分,并且被自动化文档 <abbr title="用户界面">UI</abbr> 所使用。 +* 以 JSON 形式读取请求体 +* (在必要时)把请求体转换为对应的类型 +* 校验数据: + * 数据无效时返回错误信息,并指出错误数据的确切位置和内容 +* 把接收的数据赋值给参数 `item` + * 把函数中请求体参数的类型声明为 `Item`,还能获得代码补全等编辑器支持 +* 为模型生成 <a href="https://json-schema.org" class="external-link" target="_blank">JSON Schema</a>,在项目中所需的位置使用 +* 这些概图是 OpenAPI 概图的部件,用于 API 文档 <abbr title="用户界面">UI</abbr> -## 自动化文档 +## API 文档 -你所定义模型的 JSON 模式将成为生成的 OpenAPI 模式的一部分,并且在交互式 API 文档中展示: +Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文档中显示: -<img src="https://fastapi.tiangolo.com/img/tutorial/body/image01.png"> +<img src="/img/tutorial/body/image01.png"> -而且还将在每一个需要它们的*路径操作*的 API 文档中使用: +而且,还会用于 API 文档中使用了概图的*路径操作*: -<img src="https://fastapi.tiangolo.com/img/tutorial/body/image02.png"> +<img src="/img/tutorial/body/image02.png"> ## 编辑器支持 -在你的编辑器中,你会在函数内部的任意地方得到类型提示和代码补全(如果你接收的是一个 `dict` 而不是 Pydantic 模型,则不会发生这种情况): +在编辑器中,函数内部均可使用类型提示、代码补全(如果接收的不是 Pydantic 模型,而是**字典**,就没有这样的支持): + +<img src="/img/tutorial/body/image03.png"> + +还支持检查错误的类型操作: + +<img src="/img/tutorial/body/image04.png"> -<img src="https://fastapi.tiangolo.com/img/tutorial/body/image03.png"> +这并非偶然,整个 **FastAPI** 框架都是围绕这种思路精心设计的。 -你还会获得对不正确的类型操作的错误检查: +并且,在 FastAPI 的设计阶段,我们就已经进行了全面测试,以确保 FastAPI 可以获得所有编辑器的支持。 -<img src="https://fastapi.tiangolo.com/img/tutorial/body/image04.png"> +我们还改进了 Pydantic,让它也支持这些功能。 -这并非偶然,整个框架都是围绕该设计而构建。 +虽然上面的截图取自 <a href="https://code.visualstudio.com" class="external-link" target="_blank">Visual Studio Code</a>。 -并且在进行任何实现之前,已经在设计阶段经过了全面测试,以确保它可以在所有的编辑器中生效。 +但 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 和大多数 Python 编辑器也支持同样的功能: -Pydantic 本身甚至也进行了一些更改以支持此功能。 +<img src="/img/tutorial/body/image05.png"> -上面的截图取自 <a href="https://code.visualstudio.com" class="external-link" target="_blank">Visual Studio Code</a>。 +!!! tip "提示" -但是在 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 和绝大多数其他 Python 编辑器中你也会获得同样的编辑器支持: + 使用 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 编辑器时,推荐安装 <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm 插件</a>。 -<img src="https://fastapi.tiangolo.com/img/tutorial/body/image05.png"> + 该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下: + + * 自动补全 + * 类型检查 + * 代码重构 + * 查找 + * 代码审查 ## 使用模型 -在函数内部,你可以直接访问模型对象的所有属性: +在*路径操作*函数内部直接访问模型对象的属性: === "Python 3.10+" @@ -150,9 +165,9 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。 ## 请求体 + 路径参数 -你可以同时声明路径参数和请求体。 +**FastAPI** 支持同时声明路径参数和请求体。 -**FastAPI** 将识别出与路径参数匹配的函数参数应**从路径中获取**,而声明为 Pydantic 模型的函数参数应**从请求体中获取**。 +**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 === "Python 3.10+" @@ -168,9 +183,9 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。 ## 请求体 + 路径参数 + 查询参数 -你还可以同时声明**请求体**、**路径参数**和**查询参数**。 +**FastAPI** 支持同时声明**请求体**、**路径参数**和**查询参数**。 -**FastAPI** 会识别它们中的每一个,并从正确的位置获取数据。 +**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 === "Python 3.10+" @@ -184,12 +199,18 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。 {!> ../../../docs_src/body/tutorial004.py!} ``` -函数参数将依次按如下规则进行识别: +函数参数按如下规则进行识别: + +- **路径**中声明了相同参数的参数,是路径参数 +- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数 +- 类型是 **Pydantic 模型**的参数,是**请求体** + +!!! note "笔记" + + 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 -* 如果在**路径**中也声明了该参数,它将被用作路径参数。 -* 如果参数属于**单一类型**(比如 `int`、`float`、`str`、`bool` 等)它将被解释为**查询**参数。 -* 如果参数的类型被声明为一个 **Pydantic 模型**,它将被解释为**请求体**。 + FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。 ## 不使用 Pydantic -如果你不想使用 Pydantic 模型,你还可以使用 **Body** 参数。请参阅文档 [请求体 - 多个参数:请求体中的单一值](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}。 +即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#singular-values-in-body){.internal-link target=\_blank}。 From ec96922a28bd67ce3db65af2d85edd3df7ff4233 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Apr 2024 05:36:23 +0000 Subject: [PATCH 339/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e3570aadd..63b660bea 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#3479](https://github.com/tiangolo/fastapi/pull/3479) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/body-fields.md`. PR [#3496](https://github.com/tiangolo/fastapi/pull/3496) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/extra-models.md`. PR [#3497](https://github.com/tiangolo/fastapi/pull/3497) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/metadata.md`. PR [#2667](https://github.com/tiangolo/fastapi/pull/2667) by [@tokusumi](https://github.com/tokusumi). From ffb036b7d8e3a29d615d9d8f3c50f6dcd8247a77 Mon Sep 17 00:00:00 2001 From: jaystone776 <jilei776@gmail.com> Date: Mon, 1 Apr 2024 13:36:47 +0800 Subject: [PATCH 340/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/query-params.md`=20(#3480?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/tutorial/query-params.md | 102 ++++++++++++++------------ 1 file changed, 55 insertions(+), 47 deletions(-) diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index a0cc7fea3..308dd68a4 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -1,67 +1,67 @@ # 查询参数 -声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数 +声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。 ```Python hl_lines="9" {!../../../docs_src/query_params/tutorial001.py!} ``` -查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,并以 `&` 符号分隔。 +查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。 -例如,在以下 url 中: +例如,以下 URL 中: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -...查询参数为: +……查询参数为: -* `skip`:对应的值为 `0` -* `limit`:对应的值为 `10` +* `skip`:值为 `0` +* `limit`:值为 `10` -由于它们是 URL 的一部分,因此它们的"原始值"是字符串。 +这些值都是 URL 的组成部分,因此,它们的类型**本应**是字符串。 -但是,当你为它们声明了 Python 类型(在上面的示例中为 `int`)时,它们将转换为该类型并针对该类型进行校验。 +但声明 Python 类型(上例中为 `int`)之后,这些值就会转换为声明的类型,并进行类型校验。 -应用于路径参数的所有相同过程也适用于查询参数: +所有应用于路径参数的流程也适用于查询参数: -* (很明显的)编辑器支持 -* 数据<abbr title="将来自 HTTP 请求的字符串转换为 Python 数据类型">"解析"</abbr> +* (显而易见的)编辑器支持 +* 数据<abbr title="将来自 HTTP 请求的字符串转换为 Python 数据类型">**解析**</abbr> * 数据校验 -* 自动生成文档 +* API 文档 ## 默认值 -由于查询参数不是路径的固定部分,因此它们可以是可选的,并且可以有默认值。 +查询参数不是路径的固定内容,它是可选的,还支持默认值。 -在上面的示例中,它们具有 `skip=0` 和 `limit=10` 的默认值。 +上例用 `skip=0` 和 `limit=10` 设定默认值。 -因此,访问 URL: +访问 URL: ``` http://127.0.0.1:8000/items/ ``` -将与访问以下地址相同: +与访问以下地址相同: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -但是,如果你访问的是: +但如果访问: ``` http://127.0.0.1:8000/items/?skip=20 ``` -函数中的参数值将会是: +查询参数的值就是: * `skip=20`:在 URL 中设定的值 * `limit=10`:使用默认值 ## 可选参数 -通过同样的方式,你可以将它们的默认值设置为 `None` 来声明可选查询参数: +同理,把默认值设为 `None` 即可声明**可选的**查询参数: === "Python 3.10+" @@ -76,20 +76,27 @@ http://127.0.0.1:8000/items/?skip=20 ``` -在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`。 +本例中,查询参数 `q` 是可选的,默认值为 `None`。 -!!! check - 还要注意的是,**FastAPI** 足够聪明,能够分辨出参数 `item_id` 是路径参数而 `q` 不是,因此 `q` 是一个查询参数。 +!!! check "检查" + + 注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。 + +!!! note "笔记" + + 因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。 + + FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。 ## 查询参数类型转换 -你还可以声明 `bool` 类型,它们将被自动转换: +参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型: -```Python hl_lines="7" +```Python hl_lines="9" {!../../../docs_src/query_params/tutorial003.py!} ``` -这个例子中,如果你访问: +本例中,访问: ``` http://127.0.0.1:8000/items/foo?short=1 @@ -119,42 +126,42 @@ http://127.0.0.1:8000/items/foo?short=on http://127.0.0.1:8000/items/foo?short=yes ``` -或任何其他的变体形式(大写,首字母大写等等),你的函数接收的 `short` 参数都会是布尔值 `True`。对于值为 `False` 的情况也是一样的。 +或其它任意大小写形式(大写、首字母大写等),函数接收的 `short` 参数都是布尔值 `True`。值为 `False` 时也一样。 ## 多个路径和查询参数 -你可以同时声明多个路径参数和查询参数,**FastAPI** 能够识别它们。 +**FastAPI** 可以识别同时声明的多个路径参数和查询参数。 -而且你不需要以任何特定的顺序来声明。 +而且声明查询参数的顺序并不重要。 -它们将通过名称被检测到: +FastAPI 通过参数名进行检测: -```Python hl_lines="6 8" +```Python hl_lines="8 10" {!../../../docs_src/query_params/tutorial004.py!} ``` -## 必需查询参数 +## 必选查询参数 -当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。 +为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。 -如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 `None`。 +如果只想把参数设为**可选**,但又不想指定参数的值,则要把默认值设为 `None`。 -但当你想让一个查询参数成为必需的,不声明任何默认值就可以: +如果要把查询参数设置为**必选**,就不要声明默认值: ```Python hl_lines="6-7" {!../../../docs_src/query_params/tutorial005.py!} ``` -这里的查询参数 `needy` 是类型为 `str` 的必需查询参数。 +这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。 -如果你在浏览器中打开一个像下面的 URL: +在浏览器中打开如下 URL: ``` http://127.0.0.1:8000/items/foo-item ``` -...因为没有添加必需的参数 `needy`,你将看到类似以下的错误: +……因为路径中没有必选参数 `needy`,返回的响应中会显示如下错误信息: ```JSON { @@ -171,13 +178,13 @@ http://127.0.0.1:8000/items/foo-item } ``` -由于 `needy` 是必需参数,因此你需要在 URL 中设置它的值: +`needy` 是必选参数,因此要在 URL 中设置值: ``` http://127.0.0.1:8000/items/foo-item?needy=sooooneedy ``` -...这样就正常了: +……这样就正常了: ```JSON { @@ -186,17 +193,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy } ``` -当然,你也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的: +当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的: -```Python hl_lines="7" +```Python hl_lines="10" {!../../../docs_src/query_params/tutorial006.py!} ``` -在这个例子中,有3个查询参数: +本例中有 3 个查询参数: + +* `needy`,必选的 `str` 类型参数 +* `skip`,默认值为 `0` 的 `int` 类型参数 +* `limit`,可选的 `int` 类型参数 -* `needy`,一个必需的 `str` 类型参数。 -* `skip`,一个默认值为 `0` 的 `int` 类型参数。 -* `limit`,一个可选的 `int` 类型参数。 +!!! tip "提示" -!!! tip - 你还可以像在 [路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。 + 还可以像在[路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。 From 796d0c00a6e7bcee528f0f266fe634a997238b52 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Apr 2024 05:38:55 +0000 Subject: [PATCH 341/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 63b660bea..4d0ac7a0c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/body.md`. PR [#3481](https://github.com/tiangolo/fastapi/pull/3481) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#3479](https://github.com/tiangolo/fastapi/pull/3479) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/body-fields.md`. PR [#3496](https://github.com/tiangolo/fastapi/pull/3496) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/extra-models.md`. PR [#3497](https://github.com/tiangolo/fastapi/pull/3497) by [@jaystone776](https://github.com/jaystone776). From 093a75d885fbf5eb9e55ec8d8eed6a4ac0bad2c0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Apr 2024 05:42:37 +0000 Subject: [PATCH 342/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4d0ac7a0c..ec58d7031 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#3480](https://github.com/tiangolo/fastapi/pull/3480) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/body.md`. PR [#3481](https://github.com/tiangolo/fastapi/pull/3481) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#3479](https://github.com/tiangolo/fastapi/pull/3479) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/tutorial/body-fields.md`. PR [#3496](https://github.com/tiangolo/fastapi/pull/3496) by [@jaystone776](https://github.com/jaystone776). From 7fbaa1f7d84763c27a14403ba06f6b6c7709bc88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 1 Apr 2024 11:48:56 -0500 Subject: [PATCH 343/846] =?UTF-8?q?=E2=9E=95=20Replace=20mkdocs-markdownex?= =?UTF-8?q?tradata-plugin=20with=20mkdocs-macros-plugin=20(#11383)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 9 +++++++-- requirements-docs.txt | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 9e22e3a22..933e7e4a2 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -41,8 +41,13 @@ repo_url: https://github.com/tiangolo/fastapi edit_uri: '' plugins: search: null - markdownextradata: - data: ../en/data + macros: + include_yaml: + - external_links: ../en/data/external_links.yml + - github_sponsors: ../en/data/github_sponsors.yml + - people: ../en/data/people.yml + - sponsors_badge: ../en/data/sponsors_badge.yml + - sponsors: ../en/data/sponsors.yml redirects: redirect_maps: deployment/deta.md: deployment/cloud.md diff --git a/requirements-docs.txt b/requirements-docs.txt index 28408a9f1..a97f988cb 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -2,7 +2,6 @@ -r requirements-docs-tests.txt mkdocs-material==9.4.7 mdx-include >=1.4.1,<2.0.0 -mkdocs-markdownextradata-plugin >=0.1.7,<0.3.0 mkdocs-redirects>=1.2.1,<1.3.0 typer-cli >=0.0.13,<0.0.14 typer[all] >=0.6.1,<0.8.0 @@ -17,3 +16,4 @@ mkdocstrings[python]==0.23.0 griffe-typingdoc==0.2.2 # For griffe, it formats with black black==23.3.0 +mkdocs-macros-plugin==1.0.5 From 9f882de82689ccdc8747ca04dc79422a94de7b1b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Apr 2024 16:49:18 +0000 Subject: [PATCH 344/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ec58d7031..97889ab9f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -162,6 +162,7 @@ hide: ### Internal +* ➕ Replace mkdocs-markdownextradata-plugin with mkdocs-macros-plugin. PR [#11383](https://github.com/tiangolo/fastapi/pull/11383) by [@tiangolo](https://github.com/tiangolo). * 👷 Disable MkDocs insiders social plugin while an issue in MkDocs Material is handled. PR [#11373](https://github.com/tiangolo/fastapi/pull/11373) by [@tiangolo](https://github.com/tiangolo). * 👷 Fix logic for when to install and use MkDocs Insiders. PR [#11372](https://github.com/tiangolo/fastapi/pull/11372) by [@tiangolo](https://github.com/tiangolo). * 👷 Do not use Python packages cache for publish. PR [#11366](https://github.com/tiangolo/fastapi/pull/11366) by [@tiangolo](https://github.com/tiangolo). From 5282481d0fc699ffec6b988b59c05777e1e64eb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 1 Apr 2024 18:12:23 -0500 Subject: [PATCH 345/846] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20(#11387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions <github-actions@github.com> --- docs/en/data/github_sponsors.yml | 108 +++---- docs/en/data/people.yml | 504 +++++++++++++++---------------- 2 files changed, 300 insertions(+), 312 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index fb690708f..385bcb498 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -2,9 +2,6 @@ sponsors: - - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh - - login: Alek99 - avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 - url: https://github.com/Alek99 - login: porter-dev avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 url: https://github.com/porter-dev @@ -14,6 +11,9 @@ sponsors: - login: zanfaruqui avatarUrl: https://avatars.githubusercontent.com/u/104461687?v=4 url: https://github.com/zanfaruqui + - login: Alek99 + avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 + url: https://github.com/Alek99 - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi @@ -56,24 +56,21 @@ sponsors: - login: acsone avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4 url: https://github.com/acsone -- - login: Trivie +- - login: owlur + avatarUrl: https://avatars.githubusercontent.com/u/20010787?v=4 + url: https://github.com/owlur + - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie - - login: americanair avatarUrl: https://avatars.githubusercontent.com/u/12281813?v=4 url: https://github.com/americanair - - login: 84adam - avatarUrl: https://avatars.githubusercontent.com/u/13172004?u=293f3cc6bb7e6f6ecfcdd64489a3202468321254&v=4 - url: https://github.com/84adam - login: CanoaPBC avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 url: https://github.com/CanoaPBC - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: doseiai - avatarUrl: https://avatars.githubusercontent.com/u/57115726?v=4 - url: https://github.com/doseiai - login: AccentDesign avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4 url: https://github.com/AccentDesign @@ -104,15 +101,15 @@ sponsors: - login: koconder avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 url: https://github.com/koconder + - login: b-rad-c + avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 + url: https://github.com/b-rad-c - login: ehaca avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 url: https://github.com/ehaca - login: timlrx avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 url: https://github.com/timlrx - - login: mattmalcher - avatarUrl: https://avatars.githubusercontent.com/u/31312775?v=4 - url: https://github.com/mattmalcher - login: Leay15 avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 url: https://github.com/Leay15 @@ -137,6 +134,12 @@ sponsors: - login: mjohnsey avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 url: https://github.com/mjohnsey + - login: ashi-agrawal + avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 + url: https://github.com/ashi-agrawal + - login: sepsi77 + avatarUrl: https://avatars.githubusercontent.com/u/18682303?v=4 + url: https://github.com/sepsi77 - login: wedwardbeck avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4 url: https://github.com/wedwardbeck @@ -146,9 +149,12 @@ sponsors: - login: Filimoa avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 url: https://github.com/Filimoa - - login: b-rad-c - avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 - url: https://github.com/b-rad-c + - login: prodhype + avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 + url: https://github.com/prodhype + - login: yakkonaut + avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 + url: https://github.com/yakkonaut - login: patsatsia avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 url: https://github.com/patsatsia @@ -167,6 +173,9 @@ sponsors: - login: apitally avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 url: https://github.com/apitally + - login: logic-automation + avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 + url: https://github.com/logic-automation - login: thenickben avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 url: https://github.com/thenickben @@ -179,12 +188,6 @@ sponsors: - login: dudikbender avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 url: https://github.com/dudikbender - - login: prodhype - avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 - url: https://github.com/prodhype - - login: yakkonaut - avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 - url: https://github.com/yakkonaut - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith @@ -233,9 +236,6 @@ sponsors: - login: mintuhouse avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 url: https://github.com/mintuhouse - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - login: Rehket avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 url: https://github.com/Rehket @@ -248,9 +248,9 @@ sponsors: - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow - - login: drcat101 + - login: catherinenelson1 avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 - url: https://github.com/drcat101 + url: https://github.com/catherinenelson1 - login: zsinx6 avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 url: https://github.com/zsinx6 @@ -276,23 +276,26 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4 url: https://github.com/ennui93 - login: ternaus - avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=fabc8d75c921b3380126adb5a931c5da6e7db04f&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4 url: https://github.com/ternaus - login: eseglem avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4 url: https://github.com/eseglem - - login: Yaleesa - avatarUrl: https://avatars.githubusercontent.com/u/6135475?v=4 - url: https://github.com/Yaleesa - login: FernandoCelmer avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw - - login: getsentry avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 url: https://github.com/getsentry - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy + - login: nisutec + avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 + url: https://github.com/nisutec - login: hoenie-ams avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4 url: https://github.com/hoenie-ams @@ -302,9 +305,6 @@ sponsors: - login: rlnchow avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 url: https://github.com/rlnchow - - login: HosamAlmoghraby - avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 - url: https://github.com/HosamAlmoghraby - login: dvlpjrs avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 url: https://github.com/dvlpjrs @@ -314,9 +314,9 @@ sponsors: - login: bnkc avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 url: https://github.com/bnkc - - login: curegit - avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 - url: https://github.com/curegit + - login: petercool + avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 + url: https://github.com/petercool - login: JimFawkes avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 url: https://github.com/JimFawkes @@ -341,12 +341,6 @@ sponsors: - login: SebTota avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 url: https://github.com/SebTota - - login: nisutec - avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 - url: https://github.com/nisutec - - login: 0417taehyun - avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 - url: https://github.com/0417taehyun - login: fernandosmither avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 url: https://github.com/fernandosmither @@ -356,18 +350,15 @@ sponsors: - login: PelicanQ avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 url: https://github.com/PelicanQ - - login: tim-habitat - avatarUrl: https://avatars.githubusercontent.com/u/86600518?u=7389dd77fe6a0eb8d13933356120b7d2b32d7bb4&v=4 - url: https://github.com/tim-habitat - login: jugeeem avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 url: https://github.com/jugeeem - login: tahmarrrr23 avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 url: https://github.com/tahmarrrr23 - - login: lukzmu - avatarUrl: https://avatars.githubusercontent.com/u/155924127?u=2e52e40b3134bef370b52bf2e40a524f307c2a05&v=4 - url: https://github.com/lukzmu + - login: curegit + avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 + url: https://github.com/curegit - login: kristiangronberg avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 url: https://github.com/kristiangronberg @@ -377,9 +368,6 @@ sponsors: - login: arrrrrmin avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=36a3880a6eb29309c19e6cadbb173bafbe91deb1&v=4 url: https://github.com/arrrrrmin - - login: rbtrsv - avatarUrl: https://avatars.githubusercontent.com/u/43938206?u=09955f324da271485a7edaf9241f449e88a1388a&v=4 - url: https://github.com/rbtrsv - login: mobyw avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 url: https://github.com/mobyw @@ -452,6 +440,9 @@ sponsors: - login: moonape1226 avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 url: https://github.com/moonape1226 + - login: msehnout + avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 + url: https://github.com/msehnout - login: xncbf avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 url: https://github.com/xncbf @@ -489,7 +480,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4 url: https://github.com/sdevkota - login: brizzbuzz - avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=1ffbf39f5bb8736b75c0d235707d6e8f803725c5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=58d5aae33bc97e52f11f334d2702e8710314b5c1&v=4 url: https://github.com/brizzbuzz - login: Baghdady92 avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 @@ -497,7 +488,10 @@ sponsors: - login: jakeecolution avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 url: https://github.com/jakeecolution -- - login: danburonline +- - login: abizovnuralem + avatarUrl: https://avatars.githubusercontent.com/u/33475993?u=6ce72b11a16a8232d3dd1f958f460b4735f520d8&v=4 + url: https://github.com/abizovnuralem + - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline - login: sadikkuzu @@ -506,6 +500,12 @@ sponsors: - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd + - login: YungBricoCoop + avatarUrl: https://avatars.githubusercontent.com/u/42273436?u=80470b400c416d1eabc2cc71b1efffc0e3503146&v=4 + url: https://github.com/YungBricoCoop + - login: nlazaro + avatarUrl: https://avatars.githubusercontent.com/u/44237350?u=939a570fc965d93e9db1284b5acc173c1a0be4a0&v=4 + url: https://github.com/nlazaro - login: Patechoc avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 url: https://github.com/Patechoc diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 710c650fd..cc5479c82 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo answers: 1878 - prs: 550 + prs: 559 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 596 + count: 598 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -14,7 +14,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: jgould22 - count: 232 + count: 235 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: Mause @@ -23,7 +23,7 @@ experts: url: https://github.com/Mause - login: ycd count: 217 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 url: https://github.com/ycd - login: JarroVGIT count: 193 @@ -58,7 +58,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben - login: JavierSanchezCastro - count: 52 + count: 55 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: n8sty @@ -77,10 +77,6 @@ experts: count: 47 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: Dustyposa - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 - url: https://github.com/Dustyposa - login: adriangb count: 45 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 @@ -89,6 +85,14 @@ experts: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 url: https://github.com/insomnes +- login: Dustyposa + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa +- login: YuriiMotov + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 @@ -129,10 +133,6 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes -- login: YuriiMotov - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov - login: acnebs count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 @@ -153,6 +153,10 @@ experts: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf +- login: hasansezertasan + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 @@ -165,10 +169,6 @@ experts: count: 20 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt -- login: hasansezertasan - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: retnikt count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 @@ -177,6 +177,10 @@ experts: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 url: https://github.com/zoliknemet +- login: nkhitrov + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4 + url: https://github.com/nkhitrov - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -185,10 +189,6 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/1765494?u=5b1ab7c582db4b4016fa31affe977d10af108ad4&v=4 url: https://github.com/harunyasar -- login: nkhitrov - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4 - url: https://github.com/nkhitrov - login: caeser1996 count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 @@ -199,41 +199,41 @@ experts: url: https://github.com/jonatasoli last_month_experts: - login: YuriiMotov - count: 24 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: Kludex - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex - login: JavierSanchezCastro - count: 13 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: Kludex + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex - login: jgould22 - count: 11 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: GodMoonGoodman - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman -- login: n8sty - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -- login: flo-at - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: ahmedabdou14 +- login: omarcruzpantoja + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: pythonweb2 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: PhysicallyActive + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: VatsalJagani + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 + url: https://github.com/VatsalJagani +- login: khaledadrani + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 + url: https://github.com/khaledadrani - login: chrisK824 count: 2 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 @@ -242,41 +242,33 @@ last_month_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 url: https://github.com/ThirVondukr -- login: richin13 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 - login: hussein-awala count: 2 avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 url: https://github.com/hussein-awala -- login: admo1 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 three_months_experts: - login: Kludex - count: 90 + count: 84 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: JavierSanchezCastro - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro +- login: YuriiMotov + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: jgould22 - count: 28 + count: 30 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: YuriiMotov +- login: JavierSanchezCastro count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: n8sty - count: 12 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: hasansezertasan - count: 12 + count: 8 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: dolfinus @@ -287,14 +279,6 @@ three_months_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 url: https://github.com/aanchlia -- login: Ventura94 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 - url: https://github.com/Ventura94 -- login: shashstormer - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 - url: https://github.com/shashstormer - login: GodMoonGoodman count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 @@ -307,6 +291,14 @@ three_months_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 +- login: omarcruzpantoja + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: fmelihh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + url: https://github.com/fmelihh - login: ahmedabdou14 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 @@ -315,10 +307,26 @@ three_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: fmelihh - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 - url: https://github.com/fmelihh +- login: pythonweb2 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: PhysicallyActive + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: VatsalJagani + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 + url: https://github.com/VatsalJagani +- login: khaledadrani + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 + url: https://github.com/khaledadrani - login: acidjunk count: 2 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 @@ -331,10 +339,6 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 url: https://github.com/ThirVondukr -- login: richin13 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 - login: hussein-awala count: 2 avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 @@ -375,10 +379,6 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4 url: https://github.com/DJoepie -- login: alex-pobeditel-2004 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 - url: https://github.com/alex-pobeditel-2004 - login: binbjz count: 2 avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 @@ -391,14 +391,6 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/7178184?v=4 url: https://github.com/TarasKuzyo -- login: kiraware - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/117554978?v=4 - url: https://github.com/kiraware -- login: iudeen - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen - login: msehnout count: 2 avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 @@ -415,43 +407,39 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 url: https://github.com/garg10may -- login: taegyunum - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/16094650?v=4 - url: https://github.com/taegyunum six_months_experts: - login: Kludex - count: 112 + count: 108 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: jgould22 - count: 66 + count: 67 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: JavierSanchezCastro - count: 32 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: YuriiMotov - count: 24 + count: 43 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: JavierSanchezCastro + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: n8sty - count: 24 + count: 21 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: hasansezertasan - count: 19 + count: 20 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: WilliamStam count: 9 avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 url: https://github.com/WilliamStam -- login: iudeen +- login: pythonweb2 count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 @@ -464,22 +452,14 @@ six_months_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 url: https://github.com/Ventura94 -- login: nymous - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous - login: White-Mask count: 6 avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 url: https://github.com/White-Mask -- login: chrisK824 - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: alex-pobeditel-2004 +- login: nymous count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 - url: https://github.com/alex-pobeditel-2004 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: shashstormer count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 @@ -496,26 +476,30 @@ six_months_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at -- login: ebottos94 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 - login: estebanx64 count: 4 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 -- login: pythonweb2 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: ahmedabdou14 +- login: omarcruzpantoja count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja - login: fmelihh count: 3 avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 url: https://github.com/fmelihh +- login: ahmedabdou14 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: chrisK824 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: ebottos94 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: binbjz count: 3 avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 @@ -524,18 +508,10 @@ six_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 url: https://github.com/theobouwman -- login: Ryandaydev - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 - url: https://github.com/Ryandaydev - login: sriram-kondakindi count: 3 avatarUrl: https://avatars.githubusercontent.com/u/32274323?v=4 url: https://github.com/sriram-kondakindi -- login: NeilBotelho - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 - url: https://github.com/NeilBotelho - login: yinziyan1206 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 @@ -544,14 +520,54 @@ six_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/48502122?u=89fe3e55f3cfd15d34ffac239b32af358cca6481&v=4 url: https://github.com/pcorvoh +- login: osangu + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 + url: https://github.com/osangu +- login: PhysicallyActive + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: richin13 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: amacfie + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie +- login: WSH032 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/126865849?v=4 + url: https://github.com/WSH032 +- login: MRigal + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2190327?u=557f399ee90319da7bc4a7d9274e110836b0bd60&v=4 + url: https://github.com/MRigal +- login: VatsalJagani + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 + url: https://github.com/VatsalJagani +- login: nameer + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer +- login: kiraware + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/117554978?v=4 + url: https://github.com/kiraware +- login: iudeen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: khaledadrani + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 + url: https://github.com/khaledadrani - login: acidjunk count: 2 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: shashiwtt - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/87797476?v=4 - url: https://github.com/shashiwtt - login: yavuzakyazici count: 2 avatarUrl: https://avatars.githubusercontent.com/u/148442912?u=1d2d150172c53daf82020b950c6483a6c6a77b7e&v=4 @@ -568,10 +584,6 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 url: https://github.com/ThirVondukr -- login: richin13 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 - login: hussein-awala count: 2 avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 @@ -580,10 +592,6 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/996689?v=4 url: https://github.com/jcphlux -- login: Matthieu-LAURENT39 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/91389613?v=4 - url: https://github.com/Matthieu-LAURENT39 - login: bhumkong count: 2 avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 @@ -596,95 +604,79 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 url: https://github.com/mielvds -- login: admo1 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 -- login: pbasista - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 - url: https://github.com/pbasista -- login: osangu - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 - url: https://github.com/osangu -- login: bogdan-coman-uv - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 - url: https://github.com/bogdan-coman-uv -- login: leonidktoto - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 - url: https://github.com/leonidktoto one_year_experts: - login: Kludex - count: 231 + count: 218 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: jgould22 - count: 132 + count: 133 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: JavierSanchezCastro - count: 52 + count: 55 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: n8sty - count: 39 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: YuriiMotov - count: 24 + count: 43 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: n8sty + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 - login: hasansezertasan - count: 19 + count: 20 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: abhint - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint -- login: ahmedabdou14 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 - login: nymous count: 13 avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 url: https://github.com/nymous -- login: iudeen +- login: ahmedabdou14 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: abhint count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint - login: arjwilliams count: 12 avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 url: https://github.com/arjwilliams -- login: ebottos94 - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: Viicos - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4 - url: https://github.com/Viicos +- login: iudeen + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen - login: WilliamStam count: 10 avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 url: https://github.com/WilliamStam - login: yinziyan1206 - count: 10 + count: 9 avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 url: https://github.com/yinziyan1206 - login: mateoradman count: 7 avatarUrl: https://avatars.githubusercontent.com/u/48420316?u=066f36b8e8e263b0d90798113b0f291d3266db7c&v=4 url: https://github.com/mateoradman +- login: Viicos + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4 + url: https://github.com/Viicos +- login: pythonweb2 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: ebottos94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 @@ -733,14 +725,14 @@ one_year_experts: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 url: https://github.com/wu-clan -- login: adriangb - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb - login: 8thgencore count: 5 avatarUrl: https://avatars.githubusercontent.com/u/30128845?u=a747e840f751a1d196d70d0ecf6d07a530d412a1&v=4 url: https://github.com/8thgencore +- login: anthonycepeda + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda - login: acidjunk count: 4 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 @@ -773,53 +765,49 @@ one_year_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/977953?u=d94445b7b87b7096a92a2d4b652ca6c560f34039&v=4 url: https://github.com/sanzoghenzo -- login: hochstibe - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/48712216?u=1862e0265e06be7ff710f7dc12094250c0616313&v=4 - url: https://github.com/hochstibe -- login: pythonweb2 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: nameer - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 - url: https://github.com/nameer -- login: anthonycepeda +- login: adriangb count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 - url: https://github.com/anthonycepeda + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb - login: 9en9i count: 4 avatarUrl: https://avatars.githubusercontent.com/u/44907258?u=297d0f31ea99c22b718118c1deec82001690cadb&v=4 url: https://github.com/9en9i -- login: AlexanderPodorov - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/54511144?v=4 - url: https://github.com/AlexanderPodorov -- login: sharonyogev - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/31185192?u=b13ea64b3cdaf3903390c555793aba4aff45c5e6&v=4 - url: https://github.com/sharonyogev +- login: mht2953658596 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4 + url: https://github.com/mht2953658596 +- login: omarcruzpantoja + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja - login: fmelihh count: 3 avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 url: https://github.com/fmelihh -- login: jinluyang +- login: amacfie count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15670327?v=4 - url: https://github.com/jinluyang -- login: mht2953658596 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie +- login: nameer count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4 - url: https://github.com/mht2953658596 + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer +- login: hhartzer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/100533792?v=4 + url: https://github.com/hhartzer +- login: binbjz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz top_contributors: - login: nilslindemann - count: 30 + count: 127 avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 url: https://github.com/nilslindemann - login: jaystone776 - count: 27 + count: 49 avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 url: https://github.com/jaystone776 - login: waynerv @@ -827,7 +815,7 @@ top_contributors: avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 url: https://github.com/waynerv - login: tokusumi - count: 23 + count: 24 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi - login: Kludex @@ -870,6 +858,10 @@ top_contributors: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders +- login: alejsdev + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + url: https://github.com/alejsdev - login: KaniKim count: 10 avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=d8ff6fca8542d22f94388cd2c4292e76e3898584&v=4 @@ -906,10 +898,6 @@ top_contributors: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 url: https://github.com/batlopes -- login: alejsdev - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 - url: https://github.com/alejsdev - login: wshayes count: 5 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 @@ -944,7 +932,7 @@ top_contributors: url: https://github.com/jfunez - login: ycd count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 url: https://github.com/ycd - login: komtaki count: 4 @@ -1000,7 +988,7 @@ top_contributors: url: https://github.com/pawamoy top_reviewers: - login: Kludex - count: 155 + count: 156 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan @@ -1033,7 +1021,7 @@ top_reviewers: url: https://github.com/Laineyzhang55 - login: ycd count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 url: https://github.com/ycd - login: cikay count: 41 @@ -1079,6 +1067,10 @@ top_reviewers: count: 24 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 url: https://github.com/LorhanSohaky +- login: YuriiMotov + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: dmontagu count: 23 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -1091,10 +1083,6 @@ top_reviewers: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders -- login: YuriiMotov - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov - login: rjNemo count: 21 avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 @@ -1155,6 +1143,10 @@ top_reviewers: count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk +- login: junah201 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 - login: wdh99 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 @@ -1191,19 +1183,15 @@ top_reviewers: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 url: https://github.com/mariacamilagl -- login: raphaelauv - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 - url: https://github.com/raphaelauv top_translations_reviewers: +- login: s111d + count: 143 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d - login: Xewus count: 128 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus -- login: s111d - count: 122 - avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 - url: https://github.com/s111d - login: tokusumi count: 104 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 @@ -1250,7 +1238,7 @@ top_translations_reviewers: url: https://github.com/solomein-sv - login: alperiox count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=0688c1dc00988150a82d299106062c062ed1ba13&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 url: https://github.com/alperiox - login: lsglucas count: 36 @@ -1342,7 +1330,7 @@ top_translations_reviewers: url: https://github.com/Attsun1031 - login: ycd count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 url: https://github.com/ycd - login: delhi09 count: 20 From 8ed3b734cd10067b0d2a99b27a5690144f3d6a8d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Apr 2024 23:12:42 +0000 Subject: [PATCH 346/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 97889ab9f..54a38c8fb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +* 👥 Update FastAPI People. PR [#11387](https://github.com/tiangolo/fastapi/pull/11387) by [@tiangolo](https://github.com/tiangolo). + ### Refactors * ♻️ Simplify string format with f-strings in `fastapi/applications.py`. PR [#11335](https://github.com/tiangolo/fastapi/pull/11335) by [@igeni](https://github.com/igeni). From ce2a580dd99308c9bff768f484f2cc53051318bc Mon Sep 17 00:00:00 2001 From: Esteban Maya <emayacadavid9@gmail.com> Date: Mon, 1 Apr 2024 20:54:47 -0500 Subject: [PATCH 347/846] =?UTF-8?q?=F0=9F=91=B7=20Add=20cron=20to=20run=20?= =?UTF-8?q?test=20once=20a=20week=20on=20monday=20(#11377)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b6b173685..cb14fce19 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,9 @@ on: types: - opened - synchronize + schedule: + # cron every week on monday + - cron: "0 0 * * 1" jobs: lint: From 3c4945e9eac2124adfdf57e6343ee8d6cdad6443 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 01:55:09 +0000 Subject: [PATCH 348/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 54a38c8fb..1b0af1156 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -164,6 +164,7 @@ hide: ### Internal +* 👷 Add cron to run test once a week on monday. PR [#11377](https://github.com/tiangolo/fastapi/pull/11377) by [@estebanx64](https://github.com/estebanx64). * ➕ Replace mkdocs-markdownextradata-plugin with mkdocs-macros-plugin. PR [#11383](https://github.com/tiangolo/fastapi/pull/11383) by [@tiangolo](https://github.com/tiangolo). * 👷 Disable MkDocs insiders social plugin while an issue in MkDocs Material is handled. PR [#11373](https://github.com/tiangolo/fastapi/pull/11373) by [@tiangolo](https://github.com/tiangolo). * 👷 Fix logic for when to install and use MkDocs Insiders. PR [#11372](https://github.com/tiangolo/fastapi/pull/11372) by [@tiangolo](https://github.com/tiangolo). From 0cf5ad8619412df6be12f595eef7a546c6bf5277 Mon Sep 17 00:00:00 2001 From: Rafael Barbosa <106251929+nothielf@users.noreply.github.com> Date: Mon, 1 Apr 2024 23:28:39 -0300 Subject: [PATCH 349/846] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Starlett?= =?UTF-8?q?e=20to=20>=3D0.37.2,<0.38.0,=20remove=20Starlette=20filterwarni?= =?UTF-8?q?ng=20for=20internal=20tests=20(#11266)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c3801600a..6c3bebf2b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.36.3,<0.37.0", + "starlette>=0.37.2,<0.38.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", ] @@ -121,9 +121,6 @@ filterwarnings = [ # - https://github.com/mpdavis/python-jose/issues/332 # - https://github.com/mpdavis/python-jose/issues/334 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', - # TODO: remove after upgrading Starlette to a version including https://github.com/encode/starlette/pull/2406 - # Probably Starlette 0.36.0 - "ignore: The 'method' parameter is not used, and it will be removed.:DeprecationWarning:starlette", ] [tool.coverage.run] From 2c0c220948210f7689274a86b865c253c2f8707f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 02:29:00 +0000 Subject: [PATCH 350/846] =?UTF-8?q?=F0=9F=93=9D=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 1b0af1156..9b0b1f0fb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,10 @@ hide: * ♻️ Simplify string format with f-strings in `fastapi/applications.py`. PR [#11335](https://github.com/tiangolo/fastapi/pull/11335) by [@igeni](https://github.com/igeni). +### Upgrades + +* ⬆️ Upgrade Starlette to >=0.37.2,<0.38.0, remove Starlette filterwarning for internal tests. PR [#11266](https://github.com/tiangolo/fastapi/pull/11266) by [@nothielf](https://github.com/nothielf). + ### Docs * 📝 Tweak docs and translations links and remove old docs translations. PR [#11381](https://github.com/tiangolo/fastapi/pull/11381) by [@tiangolo](https://github.com/tiangolo). From 4d2e77cdb7cbb05293053a5524391c1005634234 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Tue, 2 Apr 2024 04:32:57 +0200 Subject: [PATCH 351/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/response-status-code.md`=20(#?= =?UTF-8?q?10357)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/response-status-code.md | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 docs/de/docs/tutorial/response-status-code.md diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..a9cc238f8 --- /dev/null +++ b/docs/de/docs/tutorial/response-status-code.md @@ -0,0 +1,89 @@ +# Response-Statuscode + +So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Response deklarieren, mithilfe des Parameters `status_code`, und zwar in jeder der *Pfadoperationen*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* usw. + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +!!! note "Hinweis" + Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. + +Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben. + +!!! info + Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. + +Das wird: + +* Diesen Statuscode mit der Response zurücksenden. +* Ihn als solchen im OpenAPI-Schema dokumentieren (und somit in den Benutzeroberflächen): + +<img src="/img/tutorial/response-status-code/image01.png"> + +!!! note "Hinweis" + Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. + + FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt. + +## Über HTTP-Statuscodes + +!!! note "Hinweis" + Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode. + +Diese Statuscodes haben einen Namen zugeordnet, um sie besser zu erkennen, aber der wichtige Teil ist die Zahl. + +Kurz: + +* `100` und darüber stehen für „Information“. Diese verwenden Sie selten direkt. Responses mit diesen Statuscodes können keinen Body haben. +* **`200`** und darüber stehen für Responses, die „Successful“ („Erfolgreich“) waren. Diese verwenden Sie am häufigsten. + * `200` ist der Default-Statuscode, welcher bedeutet, alles ist „OK“. + * Ein anderes Beispiel ist `201`, „Created“ („Erzeugt“). Wird in der Regel verwendet, wenn ein neuer Datensatz in der Datenbank erzeugt wurde. + * Ein spezieller Fall ist `204`, „No Content“ („Kein Inhalt“). Diese Response wird verwendet, wenn es keinen Inhalt gibt, der zum Client zurückgeschickt wird, diese Response hat also keinen Body. +* **`300`** und darüber steht für „Redirection“ („Umleitung“). Responses mit diesen Statuscodes können einen oder keinen Body haben, mit Ausnahme von `304`, „Not Modified“ („Nicht verändert“), welche keinen haben darf. +* **`400`** und darüber stehen für „Client error“-Responses („Client-Fehler“). Auch diese verwenden Sie am häufigsten. + * Ein Beispiel ist `404`, für eine „Not Found“-Response („Nicht gefunden“). + * Für allgemeine Fehler beim Client können Sie einfach `400` verwenden. +* `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben. + +!!! tip "Tipp" + Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr> Dokumentation über HTTP-Statuscodes</a>. + +## Abkürzung, um die Namen zu erinnern + +Schauen wir uns das vorherige Beispiel noch einmal an: + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +`201` ist der Statuscode für „Created“ („Erzeugt“). + +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!} +``` + +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: + +<img src="/img/tutorial/response-status-code/image02.png"> + +!!! note "Technische Details" + Sie können auch `from starlette import status` verwenden. + + **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. + +## Den Defaultwert ändern + +Später sehen Sie, im [Handbuch für fortgeschrittene Benutzer](../advanced/response-change-status-code.md){.internal-link target=_blank}, wie Sie einen anderen Statuscode zurückgeben können, als den Default, den Sie hier deklarieren. From 1fcf3884e1fca0f42daa8e228610eec0ba1e2d06 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 02:34:42 +0000 Subject: [PATCH 352/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9b0b1f0fb..bc6b77bfe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/response-status-code.md`. PR [#10357](https://github.com/tiangolo/fastapi/pull/10357) by [@nilslindemann](https://github.com/nilslindemann). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#3480](https://github.com/tiangolo/fastapi/pull/3480) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/body.md`. PR [#3481](https://github.com/tiangolo/fastapi/pull/3481) by [@jaystone776](https://github.com/jaystone776). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#3479](https://github.com/tiangolo/fastapi/pull/3479) by [@jaystone776](https://github.com/jaystone776). From 9c80842ceaf86f2ecb68ae7b3be47ea5e622c260 Mon Sep 17 00:00:00 2001 From: Aleksei Kotenko <alexey@kotenko.me> Date: Tue, 2 Apr 2024 03:48:51 +0100 Subject: [PATCH 353/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Update=20mypy=20(#?= =?UTF-8?q?11049)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- fastapi/applications.py | 2 +- fastapi/background.py | 2 +- fastapi/datastructures.py | 2 +- fastapi/encoders.py | 2 +- fastapi/exceptions.py | 2 +- fastapi/openapi/docs.py | 2 +- fastapi/param_functions.py | 2 +- fastapi/routing.py | 2 +- fastapi/security/api_key.py | 2 +- fastapi/security/http.py | 2 +- fastapi/security/oauth2.py | 2 +- fastapi/security/open_id_connect_url.py | 2 +- requirements-tests.txt | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index d3edcc880..4446cacfb 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -40,7 +40,7 @@ from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated AppType = TypeVar("AppType", bound="FastAPI") diff --git a/fastapi/background.py b/fastapi/background.py index 35ab1b227..203578a41 100644 --- a/fastapi/background.py +++ b/fastapi/background.py @@ -1,7 +1,7 @@ from typing import Any, Callable from starlette.background import BackgroundTasks as StarletteBackgroundTasks -from typing_extensions import Annotated, Doc, ParamSpec # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, ParamSpec P = ParamSpec("P") diff --git a/fastapi/datastructures.py b/fastapi/datastructures.py index ce03e3ce4..cf8406b0f 100644 --- a/fastapi/datastructures.py +++ b/fastapi/datastructures.py @@ -24,7 +24,7 @@ from starlette.datastructures import Headers as Headers # noqa: F401 from starlette.datastructures import QueryParams as QueryParams # noqa: F401 from starlette.datastructures import State as State # noqa: F401 from starlette.datastructures import UploadFile as StarletteUploadFile -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class UploadFile(StarletteUploadFile): diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 431387f71..2f9c4a4f7 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -22,7 +22,7 @@ from pydantic import BaseModel from pydantic.color import Color from pydantic.networks import AnyUrl, NameEmail from pydantic.types import SecretBytes, SecretStr -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc from ._compat import PYDANTIC_V2, Url, _model_dump diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py index 680d288e4..44d4ada86 100644 --- a/fastapi/exceptions.py +++ b/fastapi/exceptions.py @@ -3,7 +3,7 @@ from typing import Any, Dict, Optional, Sequence, Type, Union from pydantic import BaseModel, create_model from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import WebSocketException as StarletteWebSocketException -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class HTTPException(StarletteHTTPException): diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index 69473d19c..67815e0fb 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -3,7 +3,7 @@ from typing import Any, Dict, Optional from fastapi.encoders import jsonable_encoder from starlette.responses import HTMLResponse -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc swagger_ui_default_parameters: Annotated[ Dict[str, Any], diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 3f6dbc959..6722a7d66 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -3,7 +3,7 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated _Unset: Any = Undefined diff --git a/fastapi/routing.py b/fastapi/routing.py index 23a32d15f..fa1351859 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -69,7 +69,7 @@ from starlette.routing import ( from starlette.routing import Mount as Mount # noqa from starlette.types import ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py index b1a6b4f94..b74a017f1 100644 --- a/fastapi/security/api_key.py +++ b/fastapi/security/api_key.py @@ -5,7 +5,7 @@ from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class APIKeyBase(SecurityBase): diff --git a/fastapi/security/http.py b/fastapi/security/http.py index 738455de3..b45bee55c 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -10,7 +10,7 @@ from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class HTTPBasicCredentials(BaseModel): diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index d7ba44bce..9720cace0 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -10,7 +10,7 @@ from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN # TODO: import from typing when deprecating Python 3.9 -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class OAuth2PasswordRequestForm: diff --git a/fastapi/security/open_id_connect_url.py b/fastapi/security/open_id_connect_url.py index 1d255877d..c8cceb911 100644 --- a/fastapi/security/open_id_connect_url.py +++ b/fastapi/security/open_id_connect_url.py @@ -5,7 +5,7 @@ from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class OpenIdConnect(SecurityBase): diff --git a/requirements-tests.txt b/requirements-tests.txt index 09ca9cb52..30762bc64 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,7 @@ pydantic-settings >=2.0.0 pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 -mypy ==1.4.1 +mypy ==1.8.0 ruff ==0.2.0 email_validator >=1.1.1,<3.0.0 dirty-equals ==0.6.0 From 58a1a7e8e184a4adf080e5f0eb766512877e38ed Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 02:49:14 +0000 Subject: [PATCH 354/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bc6b77bfe..382d528bb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Refactors +* ♻️ Update mypy. PR [#11049](https://github.com/tiangolo/fastapi/pull/11049) by [@k0t3n](https://github.com/k0t3n). * ♻️ Simplify string format with f-strings in `fastapi/applications.py`. PR [#11335](https://github.com/tiangolo/fastapi/pull/11335) by [@igeni](https://github.com/igeni). ### Upgrades From cf6070a49156282c1a3187fa7346c51819ca9e4b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 21:50:33 -0500 Subject: [PATCH 355/846] =?UTF-8?q?=E2=AC=86=20Bump=20black=20from=2023.3.?= =?UTF-8?q?0=20to=2024.3.0=20(#11325)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [black](https://github.com/psf/black) from 23.3.0 to 24.3.0. - [Release notes](https://github.com/psf/black/releases) - [Changelog](https://github.com/psf/black/blob/main/CHANGES.md) - [Commits](https://github.com/psf/black/compare/23.3.0...24.3.0) --- updated-dependencies: - dependency-name: black dependency-type: direct:production ... Signed-off-by: dependabot[bot] <support@github.com> 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 a97f988cb..374f18205 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -15,5 +15,5 @@ cairosvg==2.7.0 mkdocstrings[python]==0.23.0 griffe-typingdoc==0.2.2 # For griffe, it formats with black -black==23.3.0 +black==24.3.0 mkdocs-macros-plugin==1.0.5 From 7fb46eab0762034f9cc44693e7e1ee35e69015a9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 2 Apr 2024 02:50:49 +0000 Subject: [PATCH 356/846] =?UTF-8?q?=E2=AC=86=20Bump=20pillow=20from=2010.1?= =?UTF-8?q?.0=20to=2010.2.0=20(#11011)?= 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.1.0 to 10.2.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.1.0...10.2.0) --- updated-dependencies: - dependency-name: pillow dependency-type: direct:production ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 374f18205..e59521c61 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -9,7 +9,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.1.0 +pillow==10.2.0 # For image processing by Material for MkDocs cairosvg==2.7.0 mkdocstrings[python]==0.23.0 From dce7c6627517fbed4591c193b5529e0373b08d10 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 02:51:05 +0000 Subject: [PATCH 357/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 382d528bb..7e1e409ab 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -170,6 +170,7 @@ hide: ### Internal +* ⬆ Bump black from 23.3.0 to 24.3.0. PR [#11325](https://github.com/tiangolo/fastapi/pull/11325) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👷 Add cron to run test once a week on monday. PR [#11377](https://github.com/tiangolo/fastapi/pull/11377) by [@estebanx64](https://github.com/estebanx64). * ➕ Replace mkdocs-markdownextradata-plugin with mkdocs-macros-plugin. PR [#11383](https://github.com/tiangolo/fastapi/pull/11383) by [@tiangolo](https://github.com/tiangolo). * 👷 Disable MkDocs insiders social plugin while an issue in MkDocs Material is handled. PR [#11373](https://github.com/tiangolo/fastapi/pull/11373) by [@tiangolo](https://github.com/tiangolo). From 3c39b1cc0bb1f3620178db887eecabfa57b8dc09 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 21:51:11 -0500 Subject: [PATCH 358/846] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.8.11=20to=201.8.14=20(#11318)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.11 to 1.8.14. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.11...v1.8.14) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> 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 899e49057..d2ebc1645 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -26,7 +26,7 @@ jobs: - name: Build distribution run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.11 + uses: pypa/gh-action-pypi-publish@v1.8.14 with: password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context From eec612ca8d79a6144d773af2229ef046c7a29138 Mon Sep 17 00:00:00 2001 From: Nadav Zingerman <7372858+nzig@users.noreply.github.com> Date: Tue, 2 Apr 2024 05:52:56 +0300 Subject: [PATCH 359/846] =?UTF-8?q?=F0=9F=90=9B=20Fix=20parameterless=20`D?= =?UTF-8?q?epends()`=20with=20generics=20(#9479)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- fastapi/dependencies/utils.py | 4 +- tests/test_generic_parameterless_depends.py | 77 +++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 tests/test_generic_parameterless_depends.py diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 02284b4ed..4f984177a 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,6 +1,6 @@ import inspect from contextlib import AsyncExitStack, contextmanager -from copy import deepcopy +from copy import copy, deepcopy from typing import ( Any, Callable, @@ -384,6 +384,8 @@ def analyze_param( field_info.annotation = type_annotation if depends is not None and depends.dependency is None: + # Copy `depends` before mutating it + depends = copy(depends) depends.dependency = type_annotation if lenient_issubclass( diff --git a/tests/test_generic_parameterless_depends.py b/tests/test_generic_parameterless_depends.py new file mode 100644 index 000000000..fe13ff89b --- /dev/null +++ b/tests/test_generic_parameterless_depends.py @@ -0,0 +1,77 @@ +from typing import TypeVar + +from fastapi import Depends, FastAPI +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + +T = TypeVar("T") + +Dep = Annotated[T, Depends()] + + +class A: + pass + + +class B: + pass + + +@app.get("/a") +async def a(dep: Dep[A]): + return {"cls": dep.__class__.__name__} + + +@app.get("/b") +async def b(dep: Dep[B]): + return {"cls": dep.__class__.__name__} + + +client = TestClient(app) + + +def test_generic_parameterless_depends(): + response = client.get("/a") + assert response.status_code == 200, response.text + assert response.json() == {"cls": "A"} + + response = client.get("/b") + assert response.status_code == 200, response.text + assert response.json() == {"cls": "B"} + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "info": {"title": "FastAPI", "version": "0.1.0"}, + "openapi": "3.1.0", + "paths": { + "/a": { + "get": { + "operationId": "a_a_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "A", + } + }, + "/b": { + "get": { + "operationId": "b_b_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "B", + } + }, + }, + } From 597741771d99bae6526e9c31789a385e6de4f5e5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 02:53:07 +0000 Subject: [PATCH 360/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7e1e409ab..d39ffaf88 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -170,6 +170,7 @@ hide: ### Internal +* ⬆ Bump pillow from 10.1.0 to 10.2.0. PR [#11011](https://github.com/tiangolo/fastapi/pull/11011) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 23.3.0 to 24.3.0. PR [#11325](https://github.com/tiangolo/fastapi/pull/11325) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👷 Add cron to run test once a week on monday. PR [#11377](https://github.com/tiangolo/fastapi/pull/11377) by [@estebanx64](https://github.com/estebanx64). * ➕ Replace mkdocs-markdownextradata-plugin with mkdocs-macros-plugin. PR [#11383](https://github.com/tiangolo/fastapi/pull/11383) by [@tiangolo](https://github.com/tiangolo). From c27439d0b4253339bd1b28aceec2cc7cf8f446aa Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 02:54:32 +0000 Subject: [PATCH 361/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d39ffaf88..ef889670b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -170,6 +170,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.11 to 1.8.14. PR [#11318](https://github.com/tiangolo/fastapi/pull/11318) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.1.0 to 10.2.0. PR [#11011](https://github.com/tiangolo/fastapi/pull/11011) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 23.3.0 to 24.3.0. PR [#11325](https://github.com/tiangolo/fastapi/pull/11325) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👷 Add cron to run test once a week on monday. PR [#11377](https://github.com/tiangolo/fastapi/pull/11377) by [@estebanx64](https://github.com/estebanx64). From 2016de07e0c9cbb5591d16eea43d76fca745e378 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 02:56:08 +0000 Subject: [PATCH 362/846] =?UTF-8?q?=F0=9F=93=9D=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 ef889670b..5067768fa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,10 @@ hide: * 👥 Update FastAPI People. PR [#11387](https://github.com/tiangolo/fastapi/pull/11387) by [@tiangolo](https://github.com/tiangolo). +### Fixes + +* 🐛 Fix parameterless `Depends()` with generics. PR [#9479](https://github.com/tiangolo/fastapi/pull/9479) by [@nzig](https://github.com/nzig). + ### Refactors * ♻️ Update mypy. PR [#11049](https://github.com/tiangolo/fastapi/pull/11049) by [@k0t3n](https://github.com/k0t3n). From d3d9f60a1eb0de1c50692515ca21db0c48bd367b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Apr 2024 22:12:00 -0500 Subject: [PATCH 363/846] =?UTF-8?q?=E2=AC=86=20Bump=20actions/cache=20from?= =?UTF-8?q?=203=20to=204=20(#10988)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/cache dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- .github/workflows/build-docs.yml | 6 +++--- .github/workflows/publish.yml | 5 +++++ .github/workflows/test.yml | 4 ++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 9b167ee66..4ff5e26cb 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -45,7 +45,7 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v3 + - uses: actions/cache@v4 id: cache with: path: ${{ env.pythonLocation }} @@ -86,7 +86,7 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v3 + - uses: actions/cache@v4 id: cache with: path: ${{ env.pythonLocation }} @@ -102,7 +102,7 @@ jobs: pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git - name: Update Languages run: python ./scripts/docs.py update-languages - - uses: actions/cache@v3 + - uses: actions/cache@v4 with: key: mkdocs-cards-${{ matrix.lang }}-${{ github.ref }} path: docs/${{ matrix.lang }}/.cache diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d2ebc1645..a5cbf6da4 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -21,6 +21,11 @@ jobs: # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" # cache-dependency-path: pyproject.toml + - uses: actions/cache@v4 + id: cache + with: + path: ${{ env.pythonLocation }} + key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish - name: Install build dependencies run: pip install build - name: Build distribution diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cb14fce19..125265e53 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,7 +28,7 @@ jobs: # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" # cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 + - uses: actions/cache@v4 id: cache with: path: ${{ env.pythonLocation }} @@ -66,7 +66,7 @@ jobs: # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" # cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 + - uses: actions/cache@v4 id: cache with: path: ${{ env.pythonLocation }} From 5f96d7ea8ab53575600e54a99d1ab27a41801fd4 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 03:12:21 +0000 Subject: [PATCH 364/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5067768fa..b043a9a9b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -174,6 +174,7 @@ hide: ### Internal +* ⬆ Bump actions/cache from 3 to 4. PR [#10988](https://github.com/tiangolo/fastapi/pull/10988) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.11 to 1.8.14. PR [#11318](https://github.com/tiangolo/fastapi/pull/11318) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.1.0 to 10.2.0. PR [#11011](https://github.com/tiangolo/fastapi/pull/11011) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 23.3.0 to 24.3.0. PR [#11325](https://github.com/tiangolo/fastapi/pull/11325) by [@dependabot[bot]](https://github.com/apps/dependabot). From 50a880b39f09217ccb9b4144f9f5c8439af54cfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 1 Apr 2024 22:17:13 -0500 Subject: [PATCH 365/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?0.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 ++- fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b043a9a9b..4a52475aa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,7 +7,7 @@ hide: ## Latest Changes -* 👥 Update FastAPI People. PR [#11387](https://github.com/tiangolo/fastapi/pull/11387) by [@tiangolo](https://github.com/tiangolo). +## 0.110.1 ### Fixes @@ -174,6 +174,7 @@ hide: ### Internal +* 👥 Update FastAPI People. PR [#11387](https://github.com/tiangolo/fastapi/pull/11387) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump actions/cache from 3 to 4. PR [#10988](https://github.com/tiangolo/fastapi/pull/10988) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.11 to 1.8.14. PR [#11318](https://github.com/tiangolo/fastapi/pull/11318) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.1.0 to 10.2.0. PR [#11011](https://github.com/tiangolo/fastapi/pull/11011) by [@dependabot[bot]](https://github.com/apps/dependabot). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 234969256..5a77101fb 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.110.0" +__version__ = "0.110.1" from starlette import status as status From 1a24c1ef05eab9a6643932caadf22cb9cd74a1ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 1 Apr 2024 22:21:48 -0500 Subject: [PATCH 366/846] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20version?= =?UTF-8?q?=20of=20typer=20for=20docs=20(#11393)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements-docs.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index e59521c61..8fa64cf39 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -3,8 +3,7 @@ mkdocs-material==9.4.7 mdx-include >=1.4.1,<2.0.0 mkdocs-redirects>=1.2.1,<1.3.0 -typer-cli >=0.0.13,<0.0.14 -typer[all] >=0.6.1,<0.8.0 +typer >=0.12.0 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 From e98eb07944726785f9083cb57c48b4dc664af198 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 03:23:15 +0000 Subject: [PATCH 367/846] =?UTF-8?q?=F0=9F=93=9D=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 4a52475aa..7087d445f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* ⬆️ Upgrade version of typer for docs. PR [#11393](https://github.com/tiangolo/fastapi/pull/11393) by [@tiangolo](https://github.com/tiangolo). + ## 0.110.1 ### Fixes From bfd60609960758014611000d4181b56e618af904 Mon Sep 17 00:00:00 2001 From: JungWooGeon <jwk1734@naver.com> Date: Tue, 2 Apr 2024 13:18:08 +0900 Subject: [PATCH 368/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/debugging.md`=20(#5695)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/ko/docs/tutorial/debugging.md | 112 +++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 docs/ko/docs/tutorial/debugging.md diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md new file mode 100644 index 000000000..c3e588537 --- /dev/null +++ b/docs/ko/docs/tutorial/debugging.md @@ -0,0 +1,112 @@ +# 디버깅 + +예를 들면 Visual Studio Code 또는 PyCharm을 사용하여 편집기에서 디버거를 연결할 수 있습니다. + +## `uvicorn` 호출 + +FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 + +```Python hl_lines="1 15" +{!../../../docs_src/debugging/tutorial001.py!} +``` + +### `__name__ == "__main__"` 에 대하여 + +`__name__ == "__main__"`의 주요 목적은 다음과 같이 파일이 호출될 때 실행되는 일부 코드를 갖는 것입니다. + +<div class="termy"> + +```console +$ python myapp.py +``` + +</div> + +그러나 다음과 같이 다른 파일을 가져올 때는 호출되지 않습니다. + +```Python +from myapp import app +``` + +#### 추가 세부사항 + +파일 이름이 `myapp.py`라고 가정해 보겠습니다. + +다음과 같이 실행하면 + +<div class="termy"> + +```console +$ python myapp.py +``` + +</div> + +Python에 의해 자동으로 생성된 파일의 내부 변수 `__name__`은 문자열 `"__main__"`을 값으로 갖게 됩니다. + +따라서 섹션 + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +이 실행됩니다. + +--- + +해당 모듈(파일)을 가져오면 이런 일이 발생하지 않습니다 + +그래서 다음과 같은 다른 파일 `importer.py`가 있는 경우: + +```Python +from myapp import app + +# Some more code +``` + +이 경우 `myapp.py` 내부의 자동 변수에는 값이 `"__main__"`인 변수 `__name__`이 없습니다. + +따라서 다음 행 + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +은 실행되지 않습니다. + +!!! info "정보" + 자세한 내용은 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">공식 Python 문서</a>를 확인하세요 + +## 디버거로 코드 실행 + +코드에서 직접 Uvicorn 서버를 실행하고 있기 때문에 디버거에서 직접 Python 프로그램(FastAPI 애플리케이션)을 호출할 수 있습니다. + +--- + +예를 들어 Visual Studio Code에서 다음을 수행할 수 있습니다. + +* "Debug" 패널로 이동합니다. +* "Add configuration...". +* "Python"을 선택합니다. +* "`Python: Current File (Integrated Terminal)`" 옵션으로 디버거를 실행합니다. + +그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다. + +다음과 같이 표시됩니다. + +<img src="/img/tutorial/debugging/image01.png"> + +--- + +Pycharm을 사용하는 경우 다음을 수행할 수 있습니다 + +* "Run" 메뉴를 엽니다 +* "Debug..." 옵션을 선택합니다. +* 그러면 상황에 맞는 메뉴가 나타납니다. +* 디버그할 파일을 선택합니다(이 경우 `main.py`). + +그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다. + +다음과 같이 표시됩니다. + +<img src="/img/tutorial/debugging/image02.png"> From c07fd2d4999d626f712aeadc13128e36cedaa806 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 04:18:33 +0000 Subject: [PATCH 369/846] =?UTF-8?q?=F0=9F=93=9D=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 7087d445f..c7ce93c29 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/tutorial/debugging.md`. PR [#5695](https://github.com/tiangolo/fastapi/pull/5695) by [@JungWooGeon](https://github.com/JungWooGeon). + ### Internal * ⬆️ Upgrade version of typer for docs. PR [#11393](https://github.com/tiangolo/fastapi/pull/11393) by [@tiangolo](https://github.com/tiangolo). From a9b09114706c9c8588ba4687e7f8199c1eda860e Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov <drammtv@gmail.com> Date: Tue, 2 Apr 2024 07:21:06 +0300 Subject: [PATCH 370/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/dependencies/dependencies-wi?= =?UTF-8?q?th-yield.md`=20(#10532)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-with-yield.md | 275 ++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..cd524cf66 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,275 @@ +# Зависимости с yield + +FastAPI поддерживает зависимости, которые выполняют некоторые <abbr title='также известные как "exit", "cleanup", "teardown", "close", "context managers", ...'>дополнительные действия после завершения работы</abbr>. + +Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него. + +!!! tip "Подсказка" + Обязательно используйте `yield` один-единственный раз. + +!!! note "Технические детали" + Любая функция, с которой может работать: + + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + + будет корректно использоваться в качестве **FastAPI**-зависимости. + + На самом деле, FastAPI использует эту пару декораторов "под капотом". + +## Зависимость базы данных с помощью `yield` + +Например, с его помощью можно создать сессию работы с базой данных и закрыть его после завершения. + +Перед созданием ответа будет выполнен только код до и включая `yield`. + +```Python hl_lines="2-4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +Код, следующий за оператором `yield`, выполняется после доставки ответа: + +```Python hl_lines="5-6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! tip "Подсказка" + Можно использовать как `async` так и обычные функции. + + **FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями. + +## Зависимость с `yield` и `try` одновременно + +Если использовать блок `try` в зависимости с `yield`, то будет получено всякое исключение, которое было выброшено при использовании зависимости. + +Например, если какой-то код в какой-то момент в середине, в другой зависимости или в *функции операции пути*, сделал "откат" транзакции базы данных или создал любую другую ошибку, то вы получите исключение в своей зависимости. + +Таким образом, можно искать конкретное исключение внутри зависимости с помощью `except SomeException`. + +Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. + +```Python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +## Подзависимости с `yield` + +Вы можете иметь подзависимости и "деревья" подзависимостей любого размера и формы, и любая из них или все они могут использовать `yield`. + +**FastAPI** будет следить за тем, чтобы "код по выходу" в каждой зависимости с `yield` выполнялся в правильном порядке. + +Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: + +=== "Python 3.9+" + + ```Python hl_lines="6 14 22" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="5 13 21" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="4 12 20" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +И все они могут использовать `yield`. + +В этом случае `dependency_c` для выполнения своего кода выхода нуждается в том, чтобы значение из `dependency_b` (здесь `dep_b`) было еще доступно. + +И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. + +=== "Python 3.9+" + + ```Python hl_lines="18-19 26-27" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="17-18 25-26" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="16-17 24-25" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. + +Либо у вас может быть одна зависимость, которая требует несколько других зависимостей с `yield` и т.д. + +Комбинации зависимостей могут быть какими вам угодно. + +**FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке. + +!!! note "Технические детали" + Это работает благодаря <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Контекстным менеджерам</a> в Python. + + **FastAPI** использует их "под капотом" с этой целью. + +## Зависимости с `yield` и `HTTPException` + +Вы видели, что можно использовать зависимости с `yield` совместно с блоком `try`, отлавливающие исключения. + +Таким же образом вы можете поднять исключение `HTTPException` или что-то подобное в завершающем коде, после `yield`. + +Код выхода в зависимостях с `yield` выполняется *после* отправки ответа, поэтому [Обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже будет запущен. В коде выхода (после `yield`) нет ничего, перехватывающего исключения, брошенные вашими зависимостями. + +Таким образом, если после `yield` возникает `HTTPException`, то стандартный (или любой пользовательский) обработчик исключений, который перехватывает `HTTPException` и возвращает ответ HTTP 400, уже не сможет перехватить это исключение. + +Благодаря этому все, что установлено в зависимости (например, сеанс работы с БД), может быть использовано, например, фоновыми задачами. + +Фоновые задачи выполняются *после* отправки ответа. Поэтому нет возможности поднять `HTTPException`, так как нет даже возможности изменить уже отправленный ответ. + +Но если фоновая задача создает ошибку в БД, то, по крайней мере, можно сделать откат или чисто закрыть сессию в зависимости с помощью `yield`, а также, возможно, занести ошибку в журнал или сообщить о ней в удаленную систему отслеживания. + +Если у вас есть код, который, как вы знаете, может вызвать исключение, сделайте самую обычную/"питонячью" вещь и добавьте блок `try` в этот участок кода. + +Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +!!! tip "Подсказка" + Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. + +Последовательность выполнения примерно такая, как на этой схеме. Время течет сверху вниз. А каждый столбец - это одна из частей, взаимодействующих с кодом или выполняющих код. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +!!! info "Дополнительная информация" + Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. + + После отправки одного из этих ответов никакой другой ответ не может быть отправлен. + +!!! tip "Подсказка" + На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + + Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка. + +## Зависимости с `yield`, `HTTPException` и фоновыми задачами + +!!! warning "Внимание" + Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. + + Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах. + +До версии FastAPI 0.106.0 вызывать исключения после `yield` было невозможно, код выхода в зависимостях с `yield` выполнялся *после* отправки ответа, поэтому [Обработчик Ошибок](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже был бы запущен. + +Это было сделано главным образом для того, чтобы позволить использовать те же объекты, "отданные" зависимостями, внутри фоновых задач, поскольку код выхода будет выполняться после завершения фоновых задач. + +Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0. + +!!! tip "Подсказка" + + Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). + Таким образом, вы, вероятно, получите более чистый код. + +Если вы полагались на это поведение, то теперь вам следует создавать ресурсы для фоновых задач внутри самой фоновой задачи, а внутри использовать только те данные, которые не зависят от ресурсов зависимостей с `yield`. + +Например, вместо того чтобы использовать ту же сессию базы данных, вы создадите новую сессию базы данных внутри фоновой задачи и будете получать объекты из базы данных с помощью этой новой сессии. А затем, вместо того чтобы передавать объект из базы данных в качестве параметра в функцию фоновой задачи, вы передадите идентификатор этого объекта, а затем снова получите объект в функции фоновой задачи. + +## Контекстные менеджеры + +### Что такое "контекстные менеджеры" + +"Контекстные менеджеры" - это любые объекты Python, которые можно использовать в операторе `with`. + +Например, <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" class="external-link" target="_blank">можно использовать `with` для чтения файла</a>: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Под капотом" open("./somefile.txt") создаёт объект называемый "контекстным менеджером". + +Когда блок `with` завершается, он обязательно закрывает файл, даже если были исключения. + +Когда вы создаете зависимость с помощью `yield`, **FastAPI** внутренне преобразует ее в контекстный менеджер и объединяет с некоторыми другими связанными инструментами. + +### Использование менеджеров контекста в зависимостях с помощью `yield` + +!!! warning "Внимание" + Это более или менее "продвинутая" идея. + + Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт. + +В Python для создания менеджеров контекста можно <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">создать класс с двумя методами: `__enter__()` и `__exit__()`</a>. + +Вы также можете использовать их внутри зависимостей **FastAPI** с `yield`, используя операторы +`with` или `async with` внутри функции зависимости: + +```Python hl_lines="1-9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip "Подсказка" + Другой способ создания контекстного менеджера - с помощью: + + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + + используйте их для оформления функции с одним `yield`. + + Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`. + + Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит). + + FastAPI сделает это за вас на внутреннем уровне. From 01c3556e79dd65549246602b76dc5c6491bb39d4 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 04:21:47 +0000 Subject: [PATCH 371/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c7ce93c29..9b72a6b4c 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/tutorial/dependencies/dependencies-with-yield.md`. PR [#10532](https://github.com/tiangolo/fastapi/pull/10532) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/debugging.md`. PR [#5695](https://github.com/tiangolo/fastapi/pull/5695) by [@JungWooGeon](https://github.com/JungWooGeon). ### Internal From 6dc9e4a7e4aefd17f8113fd97d306a9d5ce156d2 Mon Sep 17 00:00:00 2001 From: SwftAlpc <alpaca.swift@gmail.com> Date: Tue, 2 Apr 2024 13:31:22 +0900 Subject: [PATCH 372/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/request-forms-and-files.md`?= =?UTF-8?q?=20(#1946)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji <bluce826@gmail.com> Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi <tksmtoms@gmail.com> Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- .../docs/tutorial/request-forms-and-files.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/ja/docs/tutorial/request-forms-and-files.md diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..86913ccac --- /dev/null +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,35 @@ +# リクエストフォームとファイル + +`File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 + +!!! info "情報" + アップロードされたファイルやフォームデータを受信するには、まず<a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 + + 例えば、`pip install python-multipart`のように。 + +## `File`と`Form`のインポート + +```Python hl_lines="1" +{!../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +## `File`と`Form`のパラメータの定義 + +ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します: + +```Python hl_lines="8" +{!../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。 + +また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。 + +!!! warning "注意" + *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 + + これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。 + +## まとめ + +同じリクエストでデータやファイルを受け取る必要がある場合は、`File` と`Form`を一緒に使用します。 From e68b638f6e942995375a572a04c2c5a7652d50ef Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 04:31:41 +0000 Subject: [PATCH 373/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9b72a6b4c..433339617 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/request-forms-and-files.md`. PR [#1946](https://github.com/tiangolo/fastapi/pull/1946) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10532](https://github.com/tiangolo/fastapi/pull/10532) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/debugging.md`. PR [#5695](https://github.com/tiangolo/fastapi/pull/5695) by [@JungWooGeon](https://github.com/JungWooGeon). From 31dabcb99c0aa66d5e15f3d67046f556490969c6 Mon Sep 17 00:00:00 2001 From: SwftAlpc <alpaca.swift@gmail.com> Date: Tue, 2 Apr 2024 13:38:26 +0900 Subject: [PATCH 374/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/path-operation-configuratio?= =?UTF-8?q?n.md`=20(#1954)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji <bluce826@gmail.com> Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi <tksmtoms@gmail.com> Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- .../tutorial/path-operation-configuration.md | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 docs/ja/docs/tutorial/path-operation-configuration.md diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..486c4b204 --- /dev/null +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,97 @@ +# Path Operationの設定 + +*path operationデコレータ*を設定するためのパラメータがいくつかあります。 + +!!! warning "注意" + これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 + +## レスポンスステータスコード + +*path operation*のレスポンスで使用する(HTTP)`status_code`を定義することができます。 + +`404`のように`int`のコードを直接渡すことができます。 + +しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: + +```Python hl_lines="3 17" +{!../../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 + +!!! note "技術詳細" + また、`from starlette import status`を使用することもできます。 + + **FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 + +## タグ + +`tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: + +```Python hl_lines="17 22 27" +{!../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: + +<img src="https://fastapi.tiangolo.com/img/tutorial/path-operation-configuration/image01.png"> + +## 概要と説明 + +`summary`と`description`を追加できます: + +```Python hl_lines="20-21" +{!../../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +## docstringを用いた説明 + +説明文は長くて複数行におよぶ傾向があるので、関数<abbr title="ドキュメントに使用される関数内の最初の式(変数に代入されていない)としての複数行の文字列">docstring</abbr>内に*path operation*の説明文を宣言できます。すると、**FastAPI** は説明文を読み込んでくれます。 + +docstringに<a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a>を記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) + +```Python hl_lines="19-27" +{!../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +これは対話的ドキュメントで使用されます: + +<img src="https://fastapi.tiangolo.com/img/tutorial/path-operation-configuration/image02.png"> + +## レスポンスの説明 + +`response_description`パラメータでレスポンスの説明をすることができます。 + +```Python hl_lines="21" +{!../../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +!!! info "情報" + `respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。 + +!!! check "確認" + OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。 + + そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。 + +<img src="https://fastapi.tiangolo.com/img/tutorial/path-operation-configuration/image03.png"> + +## 非推奨の*path operation* + +*path operation*を<abbr title="非推奨、使わない方がよい">deprecated</abbr>としてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: + +```Python hl_lines="16" +{!../../../docs_src/path_operation_configuration/tutorial006.py!} +``` + +対話的ドキュメントでは非推奨と明記されます: + +<img src="https://fastapi.tiangolo.com/img/tutorial/path-operation-configuration/image04.png"> + +*path operations*が非推奨である場合とそうでない場合でどのように見えるかを確認してください: + +<img src="https://fastapi.tiangolo.com/img/tutorial/path-operation-configuration/image05.png"> + +## まとめ + +*path operationデコレータ*にパラメータを渡すことで、*path operations*のメタデータを簡単に設定・追加することができます。 From 62705820d60365cdb4b05010c103c07020190e99 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 04:38:47 +0000 Subject: [PATCH 375/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 433339617..1117f92b7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-operation-configuration.md`. PR [#1954](https://github.com/tiangolo/fastapi/pull/1954) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/request-forms-and-files.md`. PR [#1946](https://github.com/tiangolo/fastapi/pull/1946) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10532](https://github.com/tiangolo/fastapi/pull/10532) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/debugging.md`. PR [#5695](https://github.com/tiangolo/fastapi/pull/5695) by [@JungWooGeon](https://github.com/JungWooGeon). From c964d04004e85b8399b6d80a2187e7c6d607d34b Mon Sep 17 00:00:00 2001 From: Dong-Young Kim <31337.persona@gmail.com> Date: Wed, 3 Apr 2024 07:35:55 +0900 Subject: [PATCH 376/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/events.md`=20(#5087)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/events.md | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 docs/ko/docs/advanced/events.md diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md new file mode 100644 index 000000000..d3227497b --- /dev/null +++ b/docs/ko/docs/advanced/events.md @@ -0,0 +1,45 @@ +# 이벤트: startup과 shutdown + +필요에 따라 응용 프로그램이 시작되기 전이나 종료될 때 실행되는 이벤트 핸들러(함수)를 정의할 수 있습니다. + +이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. + +!!! warning "경고" + 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. + +## `startup` 이벤트 + +응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: + +```Python hl_lines="8" +{!../../../docs_src/events/tutorial001.py!} +``` + +이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. + +하나 이상의 이벤트 핸들러 함수를 추가할 수도 있습니다. + +그리고 응용 프로그램은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받지 않습니다. + +## `shutdown` 이벤트 + +응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: + +```Python hl_lines="6" +{!../../../docs_src/events/tutorial002.py!} +``` + +이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. + +!!! info "정보" + `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. + +!!! tip "팁" + 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. + + 따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. + + 그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. + +!!! info "정보" + 이벤트 핸들러에 관한 내용은 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 이벤트 문서</a>에서 추가로 확인할 수 있습니다. From a85c02b85ce67dfa20caaf78e328ea080cb7ce08 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 22:36:18 +0000 Subject: [PATCH 377/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1117f92b7..04b3ff87d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/events.md`. PR [#5087](https://github.com/tiangolo/fastapi/pull/5087) by [@pers0n4](https://github.com/pers0n4). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-operation-configuration.md`. PR [#1954](https://github.com/tiangolo/fastapi/pull/1954) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/request-forms-and-files.md`. PR [#1946](https://github.com/tiangolo/fastapi/pull/1946) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10532](https://github.com/tiangolo/fastapi/pull/10532) by [@AlertRED](https://github.com/AlertRED). From 5a297971a114d72ce16bf00659ab4507ac9814a3 Mon Sep 17 00:00:00 2001 From: kty4119 <49435654+kty4119@users.noreply.github.com> Date: Wed, 3 Apr 2024 07:36:57 +0900 Subject: [PATCH 378/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/help-fastapi.md`=20(#4139)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/help-fastapi.md | 158 +++++++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 docs/ko/docs/help-fastapi.md diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md new file mode 100644 index 000000000..4faf4c1f0 --- /dev/null +++ b/docs/ko/docs/help-fastapi.md @@ -0,0 +1,158 @@ +* # FastAPI 지원 - 도움말 받기 + + **FastAPI** 가 마음에 드시나요? + + FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요? + + 혹은 **FastAPI** 에 대해 도움이 필요하신가요? + + 아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로). + + 또한 도움을 받을 수 있는 방법도 몇 가지 있습니다. + + ## 뉴스레터 구독 + + [**FastAPI와 친구** 뉴스레터](https://github.com/tiangolo/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}: + + - FastAPI 와 그 친구들에 대한 뉴스 🚀 + - 가이드 📝 + - 특징 ✨ + - 획기적인 변화 🚨 + - 팁과 요령 ✅ + + ## 트위터에서 FastAPI 팔로우하기 + + [Follow @fastapi on **Twitter**](https://twitter.com/fastapi) 를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦 + + ## Star **FastAPI** in GitHub + + GitHub에서 FastAPI에 "star"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/tiangolo/fastapi. ⭐️ + + 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. + + ## GitHub 저장소에서 릴리즈 확인 + + GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/tiangolo/fastapi. 👀 + + 여기서 "Releases only"을 선택할 수 있습니다. + + 이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다. + + ## 개발자와의 연결 + + 개발자인 [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com/) 와 연락을 취할 수 있습니다. + + 여러분은 할 수 있습니다: + + - [**GitHub**에서 팔로우하기](https://github.com/tiangolo). + - 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오. + - 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오. + + - [**Twitter**에서 팔로우하기](https://twitter.com/tiangolo). + - FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다). + - 발표 또는 새로운 툴 출시할 때 들으십시오. + - [follow @fastapi on Twitter](https://twitter.com/fastapi) (별도 계정에서) 할 수 있습니다. + + - [**Linkedin**에서의 연결](https://www.linkedin.com/in/tiangolo/). + - 새로운 툴의 발표나 릴리스를 들을 수 있습니다 (단, Twitter를 더 자주 사용합니다 🤷♂). + + - [**Dev.to**](https://dev.to/tiangolo) 또는 [**Medium**](https://medium.com/@tiangolo)에서 제가 작성한 내용을 읽어 보십시오(또는 팔로우). + - 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오. + - 새로운 기사를 읽기 위해 팔로우 하십시오. + + ## **FastAPI**에 대한 트윗 + + [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 + + **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. + + ## FastAPI에 투표하기 + + - [Slant에서 **FastAPI** 에 대해 투표하십시오](https://www.slant.co/options/34241/~fastapi-review). + - [AlternativeTo**FastAPI** 에 대해 투표하십시오](https://alternativeto.net/software/fastapi/). + + ## GitHub의 이슈로 다른사람 돕기 + + [존재하는 이슈](https://github.com/tiangolo/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓 + + 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉 + + ## GitHub 저장소 보기 + + GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/tiangolo/fastapi. 👀 + + "Releases only" 대신 "Watching"을 선택하면 다른 사용자가 새로운 issue를 생성할 때 알림이 수신됩니다. + + 그런 다음 이런 issues를 해결 할 수 있도록 도움을 줄 수 있습니다. + + ## 이슈 생성하기 + + GitHub 저장소에 [새로운 이슈 생성](https://github.com/tiangolo/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다: + + - **질문**을 하거나 **문제**에 대해 질문합니다. + - 새로운 **기능**을 제안 합니다. + + **참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉 + + ## Pull Request를 만드십시오 + + Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: + + - 문서에서 찾은 오타를 수정할 때. + + - FastAPI를 [편집하여](https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때. + + - 해당 섹션의 시작 부분에 링크를 추가했는지 확인하십시오. + + - 당신의 언어로 [문서 번역하는데](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때. + + - 또한 다른 사용자가 만든 번역을 검토하는데 도움을 줄 수도 있습니다. + + - 새로운 문서의 섹션을 제안할 때. + + - 기존 문제/버그를 수정할 때. + + - 새로운 feature를 추가할 때. + + ## 채팅에 참여하십시오 + + 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. + + !!! tip 질문이 있는 경우, [GitHub 이슈 ](https://github.com/tiangolo/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . + + ``` + 다른 일반적인 대화에서만 채팅을 사용하십시오. + ``` + + 기존 [지터 채팅](https://gitter.im/tiangolo/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다. + + ### 질문을 위해 채팅을 사용하지 마십시오 + + 채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다. + + GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 + + 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다. + + 반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 + + ## 개발자 스폰서가 되십시오 + + [GitHub 스폰서](https://github.com/sponsors/tiangolo) 를 통해 개발자를 경제적으로 지원할 수 있습니다. + + 감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄 + + 또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉 + + ## FastAPI를 강화하는 도구의 스폰서가 되십시오 + + 문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다. + + 다음의 스폰서가 될 수 있습니다 + + - [Samuel Colvin (Pydantic)](https://github.com/sponsors/samuelcolvin) + - [Encode (Starlette, Uvicorn)](https://github.com/sponsors/encode) + + ------ + + 감사합니다! 🚀 From d6997ab2a0560f95e12959bf61ba17d5c549d6de Mon Sep 17 00:00:00 2001 From: DoHyun Kim <tnghwk0661@gmail.com> Date: Wed, 3 Apr 2024 07:37:23 +0900 Subject: [PATCH 379/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/security/simple-oauth2.md`=20?= =?UTF-8?q?(#5744)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/tutorial/security/simple-oauth2.md | 315 ++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 docs/ko/docs/tutorial/security/simple-oauth2.md diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..1e33f5766 --- /dev/null +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,315 @@ +# 패스워드와 Bearer를 이용한 간단한 OAuth2 + +이제 이전 장에서 빌드하고 누락된 부분을 추가하여 완전한 보안 흐름을 갖도록 하겠습니다. + +## `username`와 `password` 얻기 + +**FastAPI** 보안 유틸리티를 사용하여 `username` 및 `password`를 가져올 것입니다. + +OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 때 클라이언트/유저가 `username` 및 `password` 필드를 폼 데이터로 보내야 함을 지정합니다. + +그리고 사양에는 필드의 이름을 그렇게 지정해야 한다고 나와 있습니다. 따라서 `user-name` 또는 `email`은 작동하지 않습니다. + +하지만 걱정하지 않아도 됩니다. 프런트엔드에서 최종 사용자에게 원하는 대로 표시할 수 있습니다. + +그리고 데이터베이스 모델은 원하는 다른 이름을 사용할 수 있습니다. + +그러나 로그인 *경로 작동*의 경우 사양과 호환되도록 이러한 이름을 사용해야 합니다(예를 들어 통합 API 문서 시스템을 사용할 수 있어야 합니다). + +사양에는 또한 `username`과 `password`가 폼 데이터로 전송되어야 한다고 명시되어 있습니다(따라서 여기에는 JSON이 없습니다). + +### `scope` + +사양에는 클라이언트가 다른 폼 필드 "`scope`"를 보낼 수 있다고 나와 있습니다. + +폼 필드 이름은 `scope`(단수형)이지만 실제로는 공백으로 구분된 "범위"가 있는 긴 문자열입니다. + +각 "범위"는 공백이 없는 문자열입니다. + +일반적으로 특정 보안 권한을 선언하는 데 사용됩니다. 다음을 봅시다: + +* `users:read` 또는 `users:write`는 일반적인 예시입니다. +* `instagram_basic`은 페이스북/인스타그램에서 사용합니다. +* `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다. + +!!! 정보 + OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. + + `:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다. + + 이러한 세부 사항은 구현에 따라 다릅니다. + + OAuth2의 경우 문자열일 뿐입니다. + +## `username`과 `password`를 가져오는 코드 + +이제 **FastAPI**에서 제공하는 유틸리티를 사용하여 이를 처리해 보겠습니다. + +### `OAuth2PasswordRequestForm` + +먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. + +=== "파이썬 3.7 이상" + + ```Python hl_lines="4 76" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="2 74" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +`OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: + +* `username`. +* `password`. +* `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다. +* `grant_type`(선택적으로 사용). + +!!! 팁 + OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. + + 사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다. + +* `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다). +* `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다). + +!!! 정보 + `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. + + `OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다. + + 그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다. + + 그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다. + +### 폼 데이터 사용하기 + +!!! 팁 + 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. + + 이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다. + +이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다. + +해당 사용자가 없으면 "잘못된 사용자 이름 또는 패스워드"라는 오류가 반환됩니다. + +오류의 경우 `HTTPException` 예외를 사용합니다: + +=== "파이썬 3.7 이상" + + ```Python hl_lines="3 77-79" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="1 75-77" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +### 패스워드 확인하기 + +이 시점에서 데이터베이스의 사용자 데이터 형식을 확인했지만 암호를 확인하지 않았습니다. + +먼저 데이터를 Pydantic `UserInDB` 모델에 넣겠습니다. + +일반 텍스트 암호를 저장하면 안 되니 (가짜) 암호 해싱 시스템을 사용합니다. + +두 패스워드가 일치하지 않으면 동일한 오류가 반환됩니다. + +#### 패스워드 해싱 + +"해싱"은 일부 콘텐츠(이 경우 패스워드)를 횡설수설하는 것처럼 보이는 일련의 바이트(문자열)로 변환하는 것을 의미합니다. + +정확히 동일한 콘텐츠(정확히 동일한 패스워드)를 전달할 때마다 정확히 동일한 횡설수설이 발생합니다. + +그러나 횡설수설에서 암호로 다시 변환할 수는 없습니다. + +##### 패스워드 해싱을 사용해야 하는 이유 + +데이터베이스가 유출된 경우 해커는 사용자의 일반 텍스트 암호가 아니라 해시만 갖게 됩니다. + +따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다). + +=== "P파이썬 3.7 이상" + + ```Python hl_lines="80-83" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="78-81" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +#### `**user_dict`에 대해 + +`UserInDB(**user_dict)`는 다음을 의미한다: + +*`user_dict`의 키와 값을 다음과 같은 키-값 인수로 직접 전달합니다:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +!!! 정보 + `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. + +## 토큰 반환하기 + +`token` 엔드포인트의 응답은 JSON 객체여야 합니다. + +`token_type`이 있어야 합니다. 여기서는 "Bearer" 토큰을 사용하므로 토큰 유형은 "`bearer`"여야 합니다. + +그리고 액세스 토큰을 포함하는 문자열과 함께 `access_token`이 있어야 합니다. + +이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다. + +!!! 팁 + 다음 장에서는 패스워드 해싱 및 <abbr title="JSON Web Tokens">JWT</abbr> 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. + + 하지만 지금은 필요한 세부 정보에 집중하겠습니다. + +=== "파이썬 3.7 이상" + + ```Python hl_lines="85" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="83" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +!!! 팁 + 사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. + + 이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다. + + 사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다. + + 나머지는 **FastAPI**가 처리합니다. + +## 의존성 업데이트하기 + +이제 의존성을 업데이트를 할 겁니다. + +이 사용자가 활성화되어 있는 *경우에만* `current_user`를 가져올 겁니다. + +따라서 `get_current_user`를 의존성으로 사용하는 추가 종속성 `get_current_active_user`를 만듭니다. + +이러한 의존성 모두, 사용자가 존재하지 않거나 비활성인 경우 HTTP 오류를 반환합니다. + +따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: + +=== "파이썬 3.7 이상" + + ```Python hl_lines="58-66 69-72 90" + {!> ../../../docs_src/security/tutorial003.py!} + ``` + +=== "파이썬 3.10 이상" + + ```Python hl_lines="55-64 67-70 88" + {!> ../../../docs_src/security/tutorial003_py310.py!} + ``` + +!!! 정보 + 여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. + + 모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다. + + 베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다. + + 실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다. + + 그러나 여기에서는 사양을 준수하도록 제공됩니다. + + 또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다. + + 그것이 표준의 이점입니다 ... + +## 확인하기 + +대화형 문서 열기: <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +### 인증하기 + +"Authorize" 버튼을 눌러봅시다. + +자격 증명을 사용합니다. + +유저명: `johndoe` + +패스워드: `secret` + +<img src="/img/tutorial/security/image04.png"> + +시스템에서 인증하면 다음과 같이 표시됩니다: + +<img src="/img/tutorial/security/image05.png"> + +### 자신의 유저 데이터 가져오기 + +이제 `/users/me` 경로에 `GET` 작업을 진행합시다. + +다음과 같은 사용자 데이터를 얻을 수 있습니다: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + +<img src="/img/tutorial/security/image06.png"> + +잠금 아이콘을 클릭하고 로그아웃한 다음 동일한 작업을 다시 시도하면 다음과 같은 HTTP 401 오류가 발생합니다. + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### 비활성된 유저 + +이제 비활성된 사용자로 시도하고, 인증해봅시다: + +유저명: `alice` + +패스워드: `secret2` + +그리고 `/users/me` 경로와 함께 `GET` 작업을 사용해 봅시다. + +다음과 같은 "Inactive user" 오류가 발생합니다: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## 요약 + +이제 API에 대한 `username` 및 `password`를 기반으로 완전한 보안 시스템을 구현할 수 있는 도구가 있습니다. + +이러한 도구를 사용하여 보안 시스템을 모든 데이터베이스 및 모든 사용자 또는 데이터 모델과 호환되도록 만들 수 있습니다. + +유일한 오점은 아직 실제로 "안전"하지 않다는 것입니다. + +다음 장에서는 안전한 패스워드 해싱 라이브러리와 <abbr title="JSON Web Tokens">JWT</abbr> 토큰을 사용하는 방법을 살펴보겠습니다. From ebcbe3c32566cca320a6b67c26e1517fde948d7e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 22:38:22 +0000 Subject: [PATCH 380/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 04b3ff87d..35edde954 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#4139](https://github.com/tiangolo/fastapi/pull/4139) by [@kty4119](https://github.com/kty4119). * 🌐 Add Korean translation for `docs/ko/docs/advanced/events.md`. PR [#5087](https://github.com/tiangolo/fastapi/pull/5087) by [@pers0n4](https://github.com/pers0n4). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-operation-configuration.md`. PR [#1954](https://github.com/tiangolo/fastapi/pull/1954) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/request-forms-and-files.md`. PR [#1946](https://github.com/tiangolo/fastapi/pull/1946) by [@SwftAlpc](https://github.com/SwftAlpc). From a09c1a034db795db047efa93660ce9bbaa35f7c8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 2 Apr 2024 22:38:55 +0000 Subject: [PATCH 381/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 35edde954..fad29e894 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#5744](https://github.com/tiangolo/fastapi/pull/5744) by [@KdHyeon0661](https://github.com/KdHyeon0661). * 🌐 Add Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#4139](https://github.com/tiangolo/fastapi/pull/4139) by [@kty4119](https://github.com/kty4119). * 🌐 Add Korean translation for `docs/ko/docs/advanced/events.md`. PR [#5087](https://github.com/tiangolo/fastapi/pull/5087) by [@pers0n4](https://github.com/pers0n4). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-operation-configuration.md`. PR [#1954](https://github.com/tiangolo/fastapi/pull/1954) by [@SwftAlpc](https://github.com/SwftAlpc). From 71321f012966759273755365575de3248c7b71b7 Mon Sep 17 00:00:00 2001 From: Jordan Shatford <37837288+jordanshatford@users.noreply.github.com> Date: Wed, 3 Apr 2024 14:42:11 +1100 Subject: [PATCH 382/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20OpenAPI=20clien?= =?UTF-8?q?t=20generation=20docs=20to=20use=20`@hey-api/openapi-ts`=20(#11?= =?UTF-8?q?339)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/de/docs/advanced/generate-clients.md | 20 ++++++++++---------- docs/em/docs/advanced/generate-clients.md | 20 ++++++++++---------- docs/en/docs/advanced/generate-clients.md | 20 ++++++++++---------- docs/zh/docs/advanced/generate-clients.md | 20 ++++++++++---------- 4 files changed, 40 insertions(+), 40 deletions(-) diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index 2fcba5956..7d1d69353 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -10,7 +10,7 @@ Es gibt viele Tools zum Generieren von Clients aus **OpenAPI**. Ein gängiges Tool ist <a href="https://openapi-generator.tech/" class="external-link" target="_blank">OpenAPI Generator</a>. -Wenn Sie ein **Frontend** erstellen, ist <a href="https://github.com/ferdikoomen/openapi-typescript-codegen" class="external-link" target="_blank">openapi-typescript-codegen</a> eine sehr interessante Alternative. +Wenn Sie ein **Frontend** erstellen, ist <a href="https://github.com/hey-api/openapi-ts" class="external-link" target="_blank">openapi-ts</a> eine sehr interessante Alternative. ## Client- und SDK-Generatoren – Sponsor @@ -58,14 +58,14 @@ Und dieselben Informationen aus den Modellen, die in OpenAPI enthalten sind, kö Nachdem wir nun die Anwendung mit den Modellen haben, können wir den Client-Code für das Frontend generieren. -#### `openapi-typescript-codegen` installieren +#### `openapi-ts` installieren -Sie können `openapi-typescript-codegen` in Ihrem Frontend-Code installieren mit: +Sie können `openapi-ts` in Ihrem Frontend-Code installieren mit: <div class="termy"> ```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -74,7 +74,7 @@ $ npm install openapi-typescript-codegen --save-dev #### Client-Code generieren -Um den Client-Code zu generieren, können Sie das Kommandozeilentool `openapi` verwenden, das soeben installiert wurde. +Um den Client-Code zu generieren, können Sie das Kommandozeilentool `openapi-ts` verwenden, das soeben installiert wurde. Da es im lokalen Projekt installiert ist, könnten Sie diesen Befehl wahrscheinlich nicht direkt aufrufen, sondern würden ihn in Ihre Datei `package.json` einfügen. @@ -87,12 +87,12 @@ Diese könnte so aussehen: "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -106,7 +106,7 @@ Nachdem Sie das NPM-Skript `generate-client` dort stehen haben, können Sie es a $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ``` </div> @@ -254,12 +254,12 @@ Da das Endergebnis nun in einer Datei `openapi.json` vorliegt, würden Sie die ` "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index 30560c8c6..261f9fb61 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -10,7 +10,7 @@ ⚠ 🧰 <a href="https://openapi-generator.tech/" class="external-link" target="_blank">🗄 🚂</a>. -🚥 👆 🏗 **🕸**, 📶 😌 🎛 <a href="https://github.com/ferdikoomen/openapi-typescript-codegen" class="external-link" target="_blank">🗄-📕-🇦🇪</a>. +🚥 👆 🏗 **🕸**, 📶 😌 🎛 <a href="https://github.com/hey-api/openapi-ts" class="external-link" target="_blank">🗄-📕-🇦🇪</a>. ## 🏗 📕 🕸 👩💻 @@ -46,14 +46,14 @@ 🔜 👈 👥 ✔️ 📱 ⏮️ 🏷, 👥 💪 🏗 👩💻 📟 🕸. -#### ❎ `openapi-typescript-codegen` +#### ❎ `openapi-ts` -👆 💪 ❎ `openapi-typescript-codegen` 👆 🕸 📟 ⏮️: +👆 💪 ❎ `openapi-ts` 👆 🕸 📟 ⏮️: <div class="termy"> ```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -62,7 +62,7 @@ $ npm install openapi-typescript-codegen --save-dev #### 🏗 👩💻 📟 -🏗 👩💻 📟 👆 💪 ⚙️ 📋 ⏸ 🈸 `openapi` 👈 🔜 🔜 ❎. +🏗 👩💻 📟 👆 💪 ⚙️ 📋 ⏸ 🈸 `openapi-ts` 👈 🔜 🔜 ❎. ↩️ ⚫️ ❎ 🇧🇿 🏗, 👆 🎲 🚫🔜 💪 🤙 👈 📋 🔗, ✋️ 👆 🔜 🚮 ⚫️ 🔛 👆 `package.json` 📁. @@ -75,12 +75,12 @@ $ npm install openapi-typescript-codegen --save-dev "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -94,7 +94,7 @@ $ npm install openapi-typescript-codegen --save-dev $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ``` </div> @@ -235,12 +235,12 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 3a810baee..c333ddf85 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -10,7 +10,7 @@ There are many tools to generate clients from **OpenAPI**. A common tool is <a href="https://openapi-generator.tech/" class="external-link" target="_blank">OpenAPI Generator</a>. -If you are building a **frontend**, a very interesting alternative is <a href="https://github.com/ferdikoomen/openapi-typescript-codegen" class="external-link" target="_blank">openapi-typescript-codegen</a>. +If you are building a **frontend**, a very interesting alternative is <a href="https://github.com/hey-api/openapi-ts" class="external-link" target="_blank">openapi-ts</a>. ## Client and SDK Generators - Sponsor @@ -58,14 +58,14 @@ And that same information from the models that is included in OpenAPI is what ca Now that we have the app with the models, we can generate the client code for the frontend. -#### Install `openapi-typescript-codegen` +#### Install `openapi-ts` -You can install `openapi-typescript-codegen` in your frontend code with: +You can install `openapi-ts` in your frontend code with: <div class="termy"> ```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -74,7 +74,7 @@ $ npm install openapi-typescript-codegen --save-dev #### Generate Client Code -To generate the client code you can use the command line application `openapi` that would now be installed. +To generate the client code you can use the command line application `openapi-ts` that would now be installed. Because it is installed in the local project, you probably wouldn't be able to call that command directly, but you would put it on your `package.json` file. @@ -87,12 +87,12 @@ It could look like this: "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -106,7 +106,7 @@ After having that NPM `generate-client` script there, you can run it with: $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ``` </div> @@ -254,12 +254,12 @@ Now as the end result is in a file `openapi.json`, you would modify the `package "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index e222e479c..c4ffcb46c 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -10,7 +10,7 @@ 一个常见的工具是 <a href="https://openapi-generator.tech/" class="external-link" target="_blank">OpenAPI Generator</a>。 -如果您正在开发**前端**,一个非常有趣的替代方案是 <a href="https://github.com/ferdikoomen/openapi-typescript-codegen" class="external-link" target="_blank">openapi-typescript-codegen</a>。 +如果您正在开发**前端**,一个非常有趣的替代方案是 <a href="https://github.com/hey-api/openapi-ts" class="external-link" target="_blank">openapi-ts</a>。 ## 生成一个 TypeScript 前端客户端 @@ -46,14 +46,14 @@ OpenAPI中所包含的模型里有相同的信息可以用于 **生成客户端 现在我们有了带有模型的应用,我们可以为前端生成客户端代码。 -#### 安装 `openapi-typescript-codegen` +#### 安装 `openapi-ts` -您可以使用以下工具在前端代码中安装 `openapi-typescript-codegen`: +您可以使用以下工具在前端代码中安装 `openapi-ts`: <div class="termy"> ```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -62,7 +62,7 @@ $ npm install openapi-typescript-codegen --save-dev #### 生成客户端代码 -要生成客户端代码,您可以使用现在将要安装的命令行应用程序 `openapi`。 +要生成客户端代码,您可以使用现在将要安装的命令行应用程序 `openapi-ts`。 因为它安装在本地项目中,所以您可能无法直接使用此命令,但您可以将其放在 `package.json` 文件中。 @@ -75,12 +75,12 @@ $ npm install openapi-typescript-codegen --save-dev "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -94,7 +94,7 @@ $ npm install openapi-typescript-codegen --save-dev $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ``` </div> @@ -234,12 +234,12 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } From 9490491595aa2f9eb0326109237be762dfff06a5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 3 Apr 2024 03:42:35 +0000 Subject: [PATCH 383/846] =?UTF-8?q?=F0=9F=93=9D=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 fad29e894..5ff713473 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update OpenAPI client generation docs to use `@hey-api/openapi-ts`. PR [#11339](https://github.com/tiangolo/fastapi/pull/11339) by [@jordanshatford](https://github.com/jordanshatford). + ### Translations * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#5744](https://github.com/tiangolo/fastapi/pull/5744) by [@KdHyeon0661](https://github.com/KdHyeon0661). From 2e552038798efe30a26bbd4c764456de7dc0bada Mon Sep 17 00:00:00 2001 From: Sk Imtiaz Ahmed <imtiaz101325@gmail.com> Date: Wed, 3 Apr 2024 17:34:37 +0200 Subject: [PATCH 384/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Bengali=20translat?= =?UTF-8?q?ions=20for=20`docs/bn/docs/python-types.md`=20(#11376)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/bn/docs/python-types.md | 537 +++++++++++++++++++++++++++++++++++ 1 file changed, 537 insertions(+) create mode 100644 docs/bn/docs/python-types.md diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md new file mode 100644 index 000000000..6923363dd --- /dev/null +++ b/docs/bn/docs/python-types.md @@ -0,0 +1,537 @@ +# পাইথন এর <abbr title="একটি ভেরিয়েবল কি ধরনের ডেটা ধারণ করতে পারে।">টাইপ্স</abbr> পরিচিতি + +Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাইপ অ্যানোটেশন" নামেও পরিচিত) এর জন্য সাপোর্ট রয়েছে। + +এই **"টাইপ হিন্ট"** বা অ্যানোটেশনগুলি এক ধরণের বিশেষ <abbr title="সিনট্যাক্স হল প্রোগ্রামিং ভাষায় কোড লেখার নিয়ম ও গঠন।">সিনট্যাক্স</abbr> যা একটি ভেরিয়েবলের <abbr title="যেমন: str, int, float, bool">টাইপ</abbr> ঘোষণা করতে দেয়। + +ভেরিয়েবলগুলির জন্য টাইপ ঘোষণা করলে, এডিটর এবং টুলগুলি আপনাকে আরও ভালো সাপোর্ট দিতে পারে। + +এটি পাইথন টাইপ হিন্ট সম্পর্কে একটি দ্রুত **টিউটোরিয়াল / রিফ্রেশার** মাত্র। এটি **FastAPI** এর সাথে ব্যবহার করার জন্য শুধুমাত্র ন্যূনতম প্রয়োজনীয়তা কভার করে... যা আসলে খুব একটা বেশি না। + +**FastAPI** এই টাইপ হিন্টগুলির উপর ভিত্তি করে নির্মিত, যা এটিকে অনেক সুবিধা এবং লাভ প্রদান করে। + +তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে। + +!!! Note + যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান। + +## প্রেরণা + +চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +এই প্রোগ্রামটি কল করলে আউটপুট হয়: + +``` +John Doe +``` + +ফাংশনটি নিম্নলিখিত কাজ করে: + +* `first_name` এবং `last_name` নেয়। +* প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে। +* তাদেরকে মাঝখানে একটি স্পেস দিয়ে <abbr title="একটার পরে একটা একত্রিত করা">concatenate</abbr> করে। + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### এটি সম্পাদনা করুন + +এটি একটি খুব সাধারণ প্রোগ্রাম। + +কিন্তু এখন কল্পনা করুন যে আপনি এটি শুরু থেকে লিখছিলেন। + +এক পর্যায়ে আপনি ফাংশনের সংজ্ঞা শুরু করেছিলেন, আপনার প্যারামিটারগুলি প্রস্তুত ছিল... + +কিন্তু তারপর আপনাকে "সেই method কল করতে হবে যা প্রথম অক্ষরকে বড় হাতের অক্ষরে রূপান্তর করে"। + +এটা কি `upper` ছিল? নাকি `uppercase`? `first_uppercase`? `capitalize`? + +তারপর, আপনি পুরোনো প্রোগ্রামারের বন্ধু, এডিটর অটোকমপ্লিশনের সাহায্যে নেওয়ার চেষ্টা করেন। + +আপনি ফাংশনের প্রথম প্যারামিটার `first_name` টাইপ করেন, তারপর একটি ডট (`.`) টাইপ করেন এবং `Ctrl+Space` চাপেন অটোকমপ্লিশন ট্রিগার করার জন্য। + +কিন্তু, দুর্ভাগ্যবশত, আপনি কিছুই উপযোগী পান না: + +<img src="/img/python-types/image01.png"> + +### টাইপ যোগ করুন + +আসুন আগের সংস্করণ থেকে একটি লাইন পরিবর্তন করি। + +আমরা ঠিক এই অংশটি পরিবর্তন করব অর্থাৎ ফাংশনের প্যারামিটারগুলি, এইগুলি: + +```Python + first_name, last_name +``` + +থেকে এইগুলি: + +```Python + first_name: str, last_name: str +``` + +ব্যাস। + +এগুলিই "টাইপ হিন্ট": + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: + +```Python + first_name="john", last_name="doe" +``` + +এটি একটি ভিন্ন জিনিস। + +আমরা সমান (`=`) নয়, কোলন (`:`) ব্যবহার করছি। + +এবং টাইপ হিন্ট যোগ করা সাধারণত তেমন কিছু পরিবর্তন করে না যা টাইপ হিন্ট ছাড়াই ঘটত। + +কিন্তু এখন, কল্পনা করুন আপনি আবার সেই ফাংশন তৈরির মাঝখানে আছেন, কিন্তু টাইপ হিন্ট সহ। + +একই পর্যায়ে, আপনি অটোকমপ্লিট ট্রিগার করতে `Ctrl+Space` চাপেন এবং আপনি দেখতে পান: + +<img src="/img/python-types/image02.png"> + +এর সাথে, আপনি অপশনগুলি দেখে, স্ক্রল করতে পারেন, যতক্ষণ না আপনি এমন একটি অপশন খুঁজে পান যা কিছু মনে পরিয়ে দেয়: + +<img src="/img/python-types/image03.png"> + +## আরও প্রেরণা + +এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: + +<img src="/img/python-types/image04.png"> + +এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## টাইপ ঘোষণা + +আপনি এতক্ষন টাইপ হিন্ট ঘোষণা করার মূল স্থানটি দেখে ফেলেছেন-- ফাংশন প্যারামিটার হিসেবে। + +সাধারণত এটি **FastAPI** এর ক্ষেত্রেও একই। + +### সিম্পল টাইপ + +আপনি `str` ছাড়াও সমস্ত স্ট্যান্ডার্ড পাইথন টাইপ ঘোষণা করতে পারেন। + +উদাহরণস্বরূপ, আপনি এগুলো ব্যবহার করতে পারেন: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### টাইপ প্যারামিটার সহ জেনেরিক টাইপ + +কিছু ডাটা স্ট্রাকচার অন্যান্য মান ধারণ করতে পারে, যেমন `dict`, `list`, `set` এবং `tuple`। এবং অভ্যন্তরীণ মানগুলোরও নিজেদের টাইপ থাকতে পারে। + +এই ধরনের টাইপগুলিকে বলা হয় "**জেনেরিক**" টাইপ এবং এগুলিকে তাদের অভ্যন্তরীণ টাইপগুলি সহ ঘোষণা করা সম্ভব। + +এই টাইপগুলি এবং অভ্যন্তরীণ টাইপগুলি ঘোষণা করতে, আপনি Python মডিউল `typing` ব্যবহার করতে পারেন। এটি বিশেষভাবে এই টাইপ হিন্টগুলি সমর্থন করার জন্য রয়েছে। + +#### Python এর নতুন সংস্করণ + +`typing` ব্যবহার করা সিনট্যাক্সটি Python 3.6 থেকে সর্বশেষ সংস্করণগুলি পর্যন্ত, অর্থাৎ Python 3.9, Python 3.10 ইত্যাদি সহ সকল সংস্করণের সাথে **সামঞ্জস্যপূর্ণ**। + +Python যত এগিয়ে যাচ্ছে, **নতুন সংস্করণগুলি** এই টাইপ অ্যানোটেশনগুলির জন্য তত উন্নত সাপোর্ট নিয়ে আসছে এবং অনেক ক্ষেত্রে আপনাকে টাইপ অ্যানোটেশন ঘোষণা করতে `typing` মডিউল ইম্পোর্ট এবং ব্যবহার করার প্রয়োজন হবে না। + +যদি আপনি আপনার প্রজেক্টের জন্য Python-এর আরও সাম্প্রতিক সংস্করণ নির্বাচন করতে পারেন, তাহলে আপনি সেই অতিরিক্ত সরলতা থেকে সুবিধা নিতে পারবেন। + +ডক্সে রয়েছে Python-এর প্রতিটি সংস্করণের সাথে সামঞ্জস্যপূর্ণ উদাহরণগুলি (যখন পার্থক্য আছে)। + +উদাহরণস্বরূপ, "**Python 3.6+**" মানে এটি Python 3.6 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.7, 3.8, 3.9, 3.10, ইত্যাদি অন্তর্ভুক্ত)। এবং "**Python 3.9+**" মানে এটি Python 3.9 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.10, ইত্যাদি অন্তর্ভুক্ত)। + +যদি আপনি Python-এর **সর্বশেষ সংস্করণগুলি ব্যবহার করতে পারেন**, তাহলে সর্বশেষ সংস্করণের জন্য উদাহরণগুলি ব্যবহার করুন, সেগুলি আপনাকে **সর্বোত্তম এবং সহজতম সিনট্যাক্স** প্রদান করবে, যেমন, "**Python 3.10+**"। + +#### লিস্ট + +উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক। + +=== "Python 3.9+" + + ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + + টাইপ হিসেবে, `list` ব্যবহার করুন। + + যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006_py39.py!} + ``` + +=== "Python 3.8+" + + `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: + + ``` Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + + ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + + টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন। + + যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: + + ```Python hl_lines="4" + {!> ../../../docs_src/python_types/tutorial006.py!} + ``` + +!!! Info + স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে। + + এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার। + +এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।" + +!!! Tip + যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন। + +এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে: + +<img src="/img/python-types/image05.png"> + +টাইপগুলি ছাড়া, এটি করা প্রায় অসম্ভব। + +লক্ষ্য করুন যে ভেরিয়েবল `item` হল `items` লিস্টের একটি এলিমেন্ট। + +তবুও, এডিটর জানে যে এটি একটি `str`, এবং তার জন্য সাপোর্ট প্রদান করে। + +#### টাপল এবং সেট + +আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন: + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial007_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial007.py!} + ``` + +এর মানে হল: + +* ভেরিয়েবল `items_t` হল একটি `tuple` যা ৩টি আইটেম ধারণ করে, একটি `int`, অন্য একটি `int`, এবং একটি `str`। +* ভেরিয়েবল `items_s` হল একটি `set`, এবং এর প্রতিটি আইটেম হল `bytes` টাইপের। + +#### ডিক্ট + +একটি `dict` সংজ্ঞায়িত করতে, আপনি ২টি টাইপ প্যারামিটার কমা দ্বারা পৃথক করে দেবেন। + +প্রথম টাইপ প্যারামিটারটি হল `dict`-এর কীগুলির জন্য। + +দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য: + +=== "Python 3.9+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008.py!} + ``` + + +এর মানে হল: + +* ভেরিয়েবল `prices` হল একটি `dict`: + * এই `dict`-এর কীগুলি হল `str` টাইপের (ধরা যাক, প্রতিটি আইটেমের নাম)। + * এই `dict`-এর মানগুলি হল `float` টাইপের (ধরা যাক, প্রতিটি আইটেমের দাম)। + +#### ইউনিয়ন + +আপনি একটি ভেরিয়েবলকে এমনভাবে ঘোষণা করতে পারেন যেন তা **একাধিক টাইপের** হয়, উদাহরণস্বরূপ, একটি `int` অথবা `str`। + +Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অন্তর্ভুক্ত) আপনি `typing` থেকে `Union` টাইপ ব্যবহার করতে পারেন এবং স্কোয়ার ব্র্যাকেটের মধ্যে গ্রহণযোগ্য টাইপগুলি রাখতে পারেন। + +Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> দ্বারা পৃথক করতে পারেন। + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial008b_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial008b.py!} + ``` + +উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`। + +#### সম্ভবত `None` + +আপনি এমনভাবে ঘোষণা করতে পারেন যে একটি মান হতে পারে এক টাইপের, যেমন `str`, আবার এটি `None`-ও হতে পারে। + +Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন। + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +`Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও। + +`Optional[Something]` মূলত `Union[Something, None]`-এর একটি শর্টকাট, এবং তারা সমতুল্য। + +এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন: + +=== "Python 3.10+" + + ```Python hl_lines="1" + {!> ../../../docs_src/python_types/tutorial009_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009.py!} + ``` + +=== "Python 3.8+ বিকল্প" + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial009b.py!} + ``` + +#### `Union` বা `Optional` ব্যবহার + +যদি আপনি Python 3.10-এর নীচের সংস্করণ ব্যবহার করেন, তবে এখানে আমার খুবই **ব্যক্তিগত** দৃষ্টিভঙ্গি থেকে একটি টিপস: + +* 🚨 `Optional[SomeType]` ব্যবহার এড়িয়ে চলুন। +* এর পরিবর্তে ✨ **`Union[SomeType, None]` ব্যবহার করুন** ✨। + +উভয়ই সমতুল্য এবং মূলে একই, কিন্তু আমি `Union`-এর পক্ষে সুপারিশ করব কারণ "**অপশনাল**" শব্দটি মনে হতে পারে যে মানটি ঐচ্ছিক,অথচ এটি আসলে মানে "এটি হতে পারে `None`", এমনকি যদি এটি ঐচ্ছিক না হয়েও আবশ্যিক হয়। + +আমি মনে করি `Union[SomeType, None]` এর অর্থ আরও স্পষ্টভাবে প্রকাশ করে। + +এটি কেবল শব্দ এবং নামের ব্যাপার। কিন্তু সেই শব্দগুলি আপনি এবং আপনার সহকর্মীরা কোড সম্পর্কে কীভাবে চিন্তা করেন তা প্রভাবিত করতে পারে। + +একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c.py!} +``` + +`name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: + +```Python +say_hi() # ওহ না, এটি একটি ত্রুটি নিক্ষেপ করবে! 😱 +``` + +`name` প্যারামিটারটি **এখনও আবশ্যিক** (নন-অপশনাল) কারণ এটির কোনো ডিফল্ট মান নেই। তবুও, `name` এর মান হিসেবে `None` গ্রহণযোগ্য: + +```Python +say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 +``` + +সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c_py310.py!} +``` + +এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 + +#### জেনেরিক টাইপস + +স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন: + +=== "Python 3.10+" + আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + + * `list` + * `tuple` + * `set` + * `dict` + + এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: + + * `Union` + * `Optional` (Python 3.8 এর মতোই) + * ...এবং অন্যান্য। + + Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ। + +=== "Python 3.9+" + + আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + + * `list` + * `tuple` + * `set` + * `dict` + + এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: + + * `Union` + * `Optional` + * ...এবং অন্যান্য। + +=== "Python 3.8+" + + * `List` + * `Tuple` + * `Set` + * `Dict` + * `Union` + * `Optional` + * ...এবং অন্যান্য। + +### ক্লাস হিসেবে টাইপস + +আপনি একটি ভেরিয়েবলের টাইপ হিসেবে একটি ক্লাস ঘোষণা করতে পারেন। + +ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: + +```Python hl_lines="1-3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: + +<img src="/img/python-types/image06.png"> + +লক্ষ্য করুন যে এর মানে হল "`one_person` হল ক্লাস `Person`-এর একটি **ইন্সট্যান্স**।" + +এর মানে এটি নয় যে "`one_person` হল **ক্লাস** যাকে বলা হয় `Person`।" + +## Pydantic মডেল + +[Pydantic](https://docs.pydantic.dev/) হল একটি Python লাইব্রেরি যা ডাটা ভ্যালিডেশন সম্পাদন করে। + +আপনি ডাটার "আকার" এট্রিবিউট সহ ক্লাস হিসেবে ঘোষণা করেন। + +এবং প্রতিটি এট্রিবিউট এর একটি টাইপ থাকে। + +তারপর আপনি যদি কিছু মান দিয়ে সেই ক্লাসের একটি ইন্সট্যান্স তৈরি করেন-- এটি মানগুলিকে ভ্যালিডেট করবে, প্রয়োজন অনুযায়ী তাদেরকে উপযুক্ত টাইপে রূপান্তর করবে এবং আপনাকে সমস্ত ডাটা সহ একটি অবজেক্ট প্রদান করবে। + +এবং আপনি সেই ফলাফল অবজেক্টের সাথে এডিটর সাপোর্ট পাবেন। + +অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ: + +=== "Python 3.10+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python + {!> ../../../docs_src/python_types/tutorial011.py!} + ``` + +!!! Info + [Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)। + +**FastAPI** মূলত Pydantic-এর উপর নির্মিত। + +আপনি এই সমস্ত কিছুর অনেক বাস্তবসম্মত উদাহরণ পাবেন [টিউটোরিয়াল - ইউজার গাইডে](https://fastapi.tiangolo.com/tutorial/)। + +!!! Tip + যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন। + +## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস + +Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়। + +=== "Python 3.9+" + + Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013_py39.py!} + ``` + +=== "Python 3.8+" + + Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন। + + এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। + + ```Python hl_lines="1 4" + {!> ../../../docs_src/python_types/tutorial013.py!} + ``` + +Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`। + +কিন্তু আপনি এই `Annotated` এর মধ্যকার জায়গাটির মধ্যে **FastAPI**-এ কীভাবে আপনার অ্যাপ্লিকেশন আচরণ করুক তা সম্পর্কে অতিরিক্ত মেটাডাটা প্রদান করার জন্য ব্যবহার করতে পারেন। + +মনে রাখার গুরুত্বপূর্ণ বিষয় হল যে **প্রথম *টাইপ প্যারামিটার*** আপনি `Annotated`-এ পাস করেন সেটি হল **আসল টাইপ**। বাকি শুধুমাত্র অন্যান্য টুলগুলির জন্য মেটাডাটা। + +এখন আপনার কেবল জানা প্রয়োজন যে `Annotated` বিদ্যমান, এবং এটি স্ট্যান্ডার্ড Python। 😎 + +পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে। + +!!! Tip + এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨ + + এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀 + +## **FastAPI**-এ টাইপ হিন্টস + +**FastAPI** এই টাইপ হিন্টগুলি ব্যবহার করে বেশ কিছু জিনিস করে। + +**FastAPI**-এ আপনি টাইপ হিন্টগুলি সহ প্যারামিটার ঘোষণা করেন এবং আপনি পান: + +* **এডিটর সাপোর্ট**। +* **টাইপচেক**। + +...এবং **FastAPI** একই ঘোষণাগুলি ব্যবহার করে: + +* **রিকুইরেমেন্টস সংজ্ঞায়িত করে**: রিকোয়েস্ট পাথ প্যারামিটার, কুয়েরি প্যারামিটার, হেডার, বডি, ডিপেন্ডেন্সিস, ইত্যাদি থেকে। +* **ডেটা রূপান্তর করে**: রিকোয়েস্ট থেকে প্রয়োজনীয় টাইপে ডেটা। +* **ডেটা যাচাই করে**: প্রতিটি রিকোয়েস্ট থেকে আসা ডেটা: + * যখন ডেটা অবৈধ হয় তখন **স্বয়ংক্রিয় ত্রুটি** গ্রাহকের কাছে ফেরত পাঠানো। +* **API ডকুমেন্টেশন তৈরি করে**: OpenAPI ব্যবহার করে: + * যা স্বয়ংক্রিয় ইন্টার্যাক্টিভ ডকুমেন্টেশন ইউজার ইন্টারফেস দ্বারা ব্যবহৃত হয়। + +এই সব কিছু আপনার কাছে অস্পষ্ট মনে হতে পারে। চিন্তা করবেন না। আপনি [টিউটোরিয়াল - ইউজার গাইড](https://fastapi.tiangolo.com/tutorial/) এ এই সব কিছু প্র্যাকটিসে দেখতে পাবেন। + +গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে। + +!!! Info + যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে। From 247b58e0f50c0eaa14b5a3acc620d83a12cfefa0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 3 Apr 2024 15:35:08 +0000 Subject: [PATCH 385/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5ff713473..f3aff2ebd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Bengali translations for `docs/bn/docs/python-types.md`. PR [#11376](https://github.com/tiangolo/fastapi/pull/11376) by [@imtiaz101325](https://github.com/imtiaz101325). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#5744](https://github.com/tiangolo/fastapi/pull/5744) by [@KdHyeon0661](https://github.com/KdHyeon0661). * 🌐 Add Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#4139](https://github.com/tiangolo/fastapi/pull/4139) by [@kty4119](https://github.com/kty4119). * 🌐 Add Korean translation for `docs/ko/docs/advanced/events.md`. PR [#5087](https://github.com/tiangolo/fastapi/pull/5087) by [@pers0n4](https://github.com/pers0n4). From 7ae1f9003f80688ea23106758eb4685a57830db6 Mon Sep 17 00:00:00 2001 From: Lufa1u <112495876+Lufa1u@users.noreply.github.com> Date: Wed, 3 Apr 2024 19:22:47 +0300 Subject: [PATCH 386/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Russian=20trans?= =?UTF-8?q?lations=20for=20deployments=20docs=20(#11271)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/deployment/concepts.md | 80 ++++++++++----------- docs/ru/docs/deployment/docker.md | 108 ++++++++++++++-------------- docs/ru/docs/deployment/https.md | 30 ++++---- docs/ru/docs/deployment/index.md | 2 +- docs/ru/docs/deployment/manually.md | 26 +++---- 5 files changed, 123 insertions(+), 123 deletions(-) diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index 681acf15e..771f4bf68 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -1,6 +1,6 @@ # Концепции развёртывания -Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых Вы можете выбрать **наиболее подходящий** способ. +Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых вы можете выбрать **наиболее подходящий** способ. Самые важные из них: @@ -13,11 +13,11 @@ Рассмотрим ниже влияние каждого из них на процесс **развёртывания**. -Наша конечная цель - **обслуживать клиентов Вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀 +Наша конечная цель - **обслуживать клиентов вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀 -Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у Вас сложится **интуитивное понимание**, какой способ выбрать при развертывании Вашего API в различных окружениях, возможно, даже **ещё не существующих**. +Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у вас сложится **интуитивное понимание**, какой способ выбрать при развертывании вашего API в различных окружениях, возможно, даже **ещё не существующих**. -Ознакомившись с этими концепциями, Вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**. +Ознакомившись с этими концепциями, вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**. В последующих главах я предоставлю Вам **конкретные рецепты** развёртывания приложения FastAPI. @@ -25,15 +25,15 @@ ## Использование более безопасного протокола HTTPS -В [предыдущей главе об HTTPS](./https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для Вашего API. +В [предыдущей главе об HTTPS](./https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для вашего API. -Также мы заметили, что обычно для работы с HTTPS Вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**. +Также мы заметили, что обычно для работы с HTTPS вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**. И если прокси-сервер не умеет сам **обновлять сертификаты HTTPS**, то нужен ещё один компонент для этого действия. ### Примеры инструментов для работы с HTTPS -Вот некоторые инструменты, которые Вы можете применять как прокси-серверы: +Вот некоторые инструменты, которые вы можете применять как прокси-серверы: * Traefik * С автоматическим обновлением сертификатов ✨ @@ -47,7 +47,7 @@ * С дополнительным компонентом типа cert-manager для обновления сертификатов * Использование услуг облачного провайдера (читайте ниже 👇) -В последнем варианте Вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера. +В последнем варианте вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера. В дальнейшем я покажу Вам некоторые конкретные примеры их применения. @@ -63,7 +63,7 @@ Термином **программа** обычно описывают множество вещей: -* **Код**, который Вы написали, в нашем случае **Python-файлы**. +* **Код**, который вы написали, в нашем случае **Python-файлы**. * **Файл**, который может быть **исполнен** операционной системой, например `python`, `python.exe` или `uvicorn`. * Конкретная программа, **запущенная** операционной системой и использующая центральный процессор и память. В таком случае это также называется **процесс**. @@ -74,13 +74,13 @@ * Конкретная программа, **запущенная** операционной системой. * Это не имеет отношения к какому-либо файлу или коду, но нечто **определённое**, управляемое и **выполняемое** операционной системой. * Любая программа, любой код, **могут делать что-то** только когда они **выполняются**. То есть, когда являются **работающим процессом**. -* Процесс может быть **прерван** (или "убит") Вами или Вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**. -* Каждое приложение, которое Вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов. +* Процесс может быть **прерван** (или "убит") Вами или вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**. +* Каждое приложение, которое вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов. * И **одна программа** может запустить **несколько параллельных процессов**. -Если Вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) Вашей операционной системы, то увидите множество работающих процессов. +Если вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) вашей операционной системы, то увидите множество работающих процессов. -Вполне вероятно, что Вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы. +Вполне вероятно, что вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы. <img class="shadow" src="/img/deployment/concepts/image01.png"> @@ -90,21 +90,21 @@ ## Настройки запуска приложения -В большинстве случаев когда Вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у Вас могут быть причины, чтоб оно запускалось только при определённых условиях. +В большинстве случаев когда вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у вас могут быть причины, чтоб оно запускалось только при определённых условиях. ### Удалённый сервер -Когда Вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как Вы делаете при локальной разработке. +Когда вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как вы делаете при локальной разработке. Это рабочий способ и он полезен **во время разработки**. -Но если Вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**. +Но если вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**. -И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), Вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱 +И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱 ### Автоматический запуск программ -Вероятно Вы пожелаете, чтоб Ваша серверная программа (такая как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI). +Вероятно вы захотите, чтоб Ваша серверная программа (такая, как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI). ### Отдельная программа @@ -127,7 +127,7 @@ ## Перезапуск -Вы, вероятно, также пожелаете, чтоб Ваше приложение **перезапускалось**, если в нём произошёл сбой. +Вы, вероятно, также захотите, чтоб ваше приложение **перезапускалось**, если в нём произошёл сбой. ### Мы ошибаемся @@ -137,7 +137,7 @@ ### Небольшие ошибки обрабатываются автоматически -Когда Вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡 +Когда вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡 Клиент получит ошибку **500 Internal Server Error** в ответ на свой запрос, но приложение не сломается и будет продолжать работать с последующими запросами. @@ -152,11 +152,11 @@ Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз... !!! tip "Заметка" - ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, Вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. + ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. -Возможно Вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск Вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в Вашем коде внутри приложения, не может быть выполнено в принципе. +Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе. ### Примеры инструментов для автоматического перезапуска @@ -181,7 +181,7 @@ ### Множество процессов - Воркеры (Workers) -Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то Вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами. +Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами. **Несколько запущенных процессов** одной и той же API-программы часто называют **воркерами**. @@ -197,11 +197,11 @@ Работающая программа загружает в память данные, необходимые для её работы, например, переменные содержащие модели машинного обучения или большие файлы. Каждая переменная **потребляет некоторое количество оперативной памяти (RAM)** сервера. -Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения Вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти. +Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти. ### Память сервера -Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда Вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если Вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате Вашему API потребуется **4 ГБ оперативной памяти (RAM)**. +Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате вашему API потребуется **4 ГБ оперативной памяти (RAM)**. И если Ваш удалённый сервер или виртуальная машина располагает только 3 ГБ памяти, то попытка загрузить в неё 4 ГБ данных вызовет проблемы. 🚨 @@ -211,15 +211,15 @@ Менеджер процессов будет слушать определённый **сокет** (IP:порт) и передавать данные работающим процессам. -Каждый из этих процессов будет запускать Ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память. +Каждый из этих процессов будет запускать ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память. <img src="/img/deployment/concepts/process-ram.svg"> -Безусловно, на этом же сервере будут работать и **другие процессы**, которые не относятся к Вашему приложению. +Безусловно, на этом же сервере будут работать и **другие процессы**, которые не относятся к вашему приложению. -Интересная деталь - обычно в течение времени процент **использования центрального процессора (CPU)** каждым процессом может очень сильно **изменяться**, но объём занимаемой **оперативной памяти (RAM)** остаётся относительно **стабильным**. +Интересная деталь заключается в том, что процент **использования центрального процессора (CPU)** каждым процессом может сильно меняться с течением времени, но объём занимаемой **оперативной памяти (RAM)** остаётся относительно **стабильным**. -Если у Вас есть API, который каждый раз выполняет сопоставимый объем вычислений, и у Вас много клиентов, то **загрузка процессора**, вероятно, *также будет стабильной* (вместо того, чтобы постоянно быстро увеличиваться и уменьшаться). +Если у вас есть API, который каждый раз выполняет сопоставимый объем вычислений, и у вас много клиентов, то **загрузка процессора**, вероятно, *также будет стабильной* (вместо того, чтобы постоянно быстро увеличиваться и уменьшаться). ### Примеры стратегий и инструментов для запуска нескольких экземпляров приложения @@ -236,10 +236,10 @@ * **Kubernetes** и аналогичные **контейнерные системы** * Какой-то компонент в **Kubernetes** будет слушать **IP:port**. Необходимое количество запущенных экземпляров приложения будет осуществляться посредством запуска **нескольких контейнеров**, в каждом из которых работает **один процесс Uvicorn**. * **Облачные сервисы**, которые позаботятся обо всём за Вас - * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб Вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, Вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. + * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. !!! tip "Заметка" - Если Вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. + Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](./docker.md){.internal-link target=_blank}. @@ -253,18 +253,18 @@ Поэтому Вам нужен будет **один процесс**, выполняющий эти **подготовительные шаги** до запуска приложения. -Также Вам нужно будет убедиться, что этот процесс выполнил подготовительные шаги *даже* если впоследствии Вы запустите **несколько процессов** (несколько воркеров) самого приложения. Если бы эти шаги выполнялись в каждом **клонированном процессе**, они бы **дублировали** работу, пытаясь выполнить её **параллельно**. И если бы эта работа была бы чем-то деликатным, вроде миграции базы данных, то это может вызвать конфликты между ними. +Также Вам нужно будет убедиться, что этот процесс выполнил подготовительные шаги *даже* если впоследствии вы запустите **несколько процессов** (несколько воркеров) самого приложения. Если бы эти шаги выполнялись в каждом **клонированном процессе**, они бы **дублировали** работу, пытаясь выполнить её **параллельно**. И если бы эта работа была бы чем-то деликатным, вроде миграции базы данных, то это может вызвать конфликты между ними. Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще. !!! tip "Заметка" - Имейте в виду, что в некоторых случаях запуск Вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. + Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 ### Примеры стратегий запуска предварительных шагов -Существует **сильная зависимость** от того, как Вы **развёртываете свою систему**, запускаете программы, обрабатываете перезапуски и т.д. +Существует **сильная зависимость** от того, как вы **развёртываете свою систему**, запускаете программы, обрабатываете перезапуски и т.д. Вот некоторые возможные идеи: @@ -279,19 +279,19 @@ Ваш сервер располагает ресурсами, которые Ваши программы могут потреблять или **утилизировать**, а именно - время работы центрального процессора и объём оперативной памяти. -Как много системных ресурсов Вы предполагаете потребить/утилизировать? Если не задумываться, то можно ответить - "немного", но на самом деле Вы, вероятно, пожелаете использовать **максимально возможное количество**. +Как много системных ресурсов вы предполагаете потребить/утилизировать? Если не задумываться, то можно ответить - "немного", но на самом деле Вы, вероятно, захотите использовать **максимально возможное количество**. -Если Вы платите за содержание трёх серверов, но используете лишь малую часть системных ресурсов каждого из них, то Вы **выбрасываете деньги на ветер**, а также **впустую тратите электроэнергию** и т.п. +Если вы платите за содержание трёх серверов, но используете лишь малую часть системных ресурсов каждого из них, то вы **выбрасываете деньги на ветер**, а также **впустую тратите электроэнергию** и т.п. В таком случае было бы лучше обойтись двумя серверами, но более полно утилизировать их ресурсы (центральный процессор, оперативную память, жёсткий диск, сети передачи данных и т.д). -С другой стороны, если Вы располагаете только двумя серверами и используете **на 100% их процессоры и память**, но какой-либо процесс запросит дополнительную память, то операционная система сервера будет использовать жёсткий диск для расширения оперативной памяти (а диск работает в тысячи раз медленнее), а то вовсе **упадёт**. Или если какому-то процессу понадобится произвести вычисления, то ему придётся подождать, пока процессор освободится. +С другой стороны, если вы располагаете только двумя серверами и используете **на 100% их процессоры и память**, но какой-либо процесс запросит дополнительную память, то операционная система сервера будет использовать жёсткий диск для расширения оперативной памяти (а диск работает в тысячи раз медленнее), а то вовсе **упадёт**. Или если какому-то процессу понадобится произвести вычисления, то ему придётся подождать, пока процессор освободится. В такой ситуации лучше подключить **ещё один сервер** и перераспределить процессы между серверами, чтоб всем **хватало памяти и процессорного времени**. -Также есть вероятность, что по какой-то причине возник **всплеск** запросов к Вашему API. Возможно, это был вирус, боты или другие сервисы начали пользоваться им. И для таких происшествий Вы можете захотеть иметь дополнительные ресурсы. +Также есть вероятность, что по какой-то причине возник **всплеск** запросов к вашему API. Возможно, это был вирус, боты или другие сервисы начали пользоваться им. И для таких происшествий вы можете захотеть иметь дополнительные ресурсы. -При настройке логики развёртываний, Вы можете указать **целевое значение** утилизации ресурсов, допустим, **от 50% до 90%**. Обычно эти метрики и используют. +При настройке логики развёртываний, вы можете указать **целевое значение** утилизации ресурсов, допустим, **от 50% до 90%**. Обычно эти метрики и используют. Вы можете использовать простые инструменты, такие как `htop`, для отслеживания загрузки центрального процессора и оперативной памяти сервера, в том числе каждым процессом. Или более сложные системы мониторинга нескольких серверов. @@ -308,4 +308,4 @@ Осознание этих идей и того, как их применять, должно дать Вам интуитивное понимание, необходимое для принятия решений при настройке развертываний. 🤓 -В следующих разделах я приведу более конкретные примеры возможных стратегий, которым Вы можете следовать. 🚀 +В следующих разделах я приведу более конкретные примеры возможных стратегий, которым вы можете следовать. 🚀 diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index f045ca944..78d3ec1b4 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -70,19 +70,19 @@ Docker является одним оз основных инструменто и т.п. -Использование подготовленных образов значительно упрощает **комбинирование** и использование разных инструментов. Например, Вы можете попытаться использовать новую базу данных. В большинстве случаев можно использовать **официальный образ** и всего лишь указать переменные окружения. +Использование подготовленных образов значительно упрощает **комбинирование** и использование разных инструментов. Например, вы можете попытаться использовать новую базу данных. В большинстве случаев можно использовать **официальный образ** и всего лишь указать переменные окружения. -Таким образом, Вы можете изучить, что такое контейнеризация и Docker, и использовать полученные знания с разными инструментами и компонентами. +Таким образом, вы можете изучить, что такое контейнеризация и Docker, и использовать полученные знания с разными инструментами и компонентами. -Так, Вы можете запустить одновременно **множество контейнеров** с базой данных, Python-приложением, веб-сервером, React-приложением и соединить их вместе через внутреннюю сеть. +Так, вы можете запустить одновременно **множество контейнеров** с базой данных, Python-приложением, веб-сервером, React-приложением и соединить их вместе через внутреннюю сеть. Все системы управления контейнерами (такие, как Docker или Kubernetes) имеют встроенные возможности для организации такого сетевого взаимодействия. ## Контейнеры и процессы -Обычно **образ контейнера** содержит метаданные предустановленной программы или команду, которую следует выполнить при запуске **контейнера**. Также он может содержать параметры, передаваемые предустановленной программе. Похоже на то, как если бы Вы запускали такую программу через терминал. +Обычно **образ контейнера** содержит метаданные предустановленной программы или команду, которую следует выполнить при запуске **контейнера**. Также он может содержать параметры, передаваемые предустановленной программе. Похоже на то, как если бы вы запускали такую программу через терминал. -Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но Вы можете изменить его так, чтоб он выполнял другие команды и программы. +Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но вы можете изменить его так, чтоб он выполнял другие команды и программы. Контейнер буде работать до тех пор, пока выполняется его **главный процесс** (команда или программа). @@ -100,11 +100,11 @@ Docker является одним оз основных инструменто * Использование с **Kubernetes** или аналогичным инструментом * Запуск в **Raspberry Pi** -* Использование в облачных сервисах, запускающих образы контейнеров для Вас и т.п. +* Использование в облачных сервисах, запускающих образы контейнеров для вас и т.п. ### Установить зависимости -Обычно Вашему приложению необходимы **дополнительные библиотеки**, список которых находится в отдельном файле. +Обычно вашему приложению необходимы **дополнительные библиотеки**, список которых находится в отдельном файле. На название и содержание такого файла влияет выбранный Вами инструмент **установки** этих библиотек (зависимостей). @@ -135,7 +135,7 @@ Successfully installed fastapi pydantic uvicorn !!! info "Информация" Существуют и другие инструменты управления зависимостями. - В этом же разделе, но позже, я покажу Вам пример использования Poetry. 👇 + В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇 ### Создать приложение **FastAPI** @@ -195,7 +195,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Сначала копируйте **только** файл с зависимостями. - Этот файл **изменяется довольно редко**, Docker ищет изменения при постройке образа и если не находит, то использует **кэш**, в котором хранятся предыдущии версии сборки образа. + Этот файл **изменяется довольно редко**, Docker ищет изменения при постройке образа и если не находит, то использует **кэш**, в котором хранятся предыдущие версии сборки образа. 4. Установите библиотеки перечисленные в файле с зависимостями. @@ -208,7 +208,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Ка и в предыдущем шаге с копированием файла, этот шаг также будет использовать **кэш Docker** в случае отсутствия изменений. - Использрвание кэша, особенно на этом шаге, позволит Вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. + Использование кэша, особенно на этом шаге, позволит вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. 5. Скопируйте директорию `./app` внутрь директории `/code` (в контейнере). @@ -216,11 +216,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 6. Укажите **команду**, запускающую сервер `uvicorn`. - `CMD` принимает список строк, разделённых запятыми, но при выполнении объединит их через пробел, собрав из них одну команду, которую Вы могли бы написать в терминале. + `CMD` принимает список строк, разделённых запятыми, но при выполнении объединит их через пробел, собрав из них одну команду, которую вы могли бы написать в терминале. - Эта команда будет выполнена в **текущей рабочей директории**, а именно в директории `/code`, котоая указана командой `WORKDIR /code`. + Эта команда будет выполнена в **текущей рабочей директории**, а именно в директории `/code`, которая указана в команде `WORKDIR /code`. - Так как команда выполняется внутрии директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. + Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. !!! tip "Подсказка" Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 @@ -238,7 +238,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] #### Использование прокси-сервера -Если Вы запускаете контейнер за прокси-сервером завершения TLS (балансирующего нагрузку), таким как Nginx или Traefik, добавьте опцию `--proxy-headers`, которая укажет Uvicorn, что он работает позади прокси-сервера и может доверять заголовкам отправляемым им. +Если вы запускаете контейнер за прокси-сервером завершения TLS (балансирующего нагрузку), таким как Nginx или Traefik, добавьте опцию `--proxy-headers`, которая укажет Uvicorn, что он работает позади прокси-сервера и может доверять заголовкам отправляемым им. ```Dockerfile CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] @@ -269,7 +269,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt Для загрузки и установки необходимых библиотек **может понадобиться несколько минут**, но использование **кэша** занимает несколько **секунд** максимум. -И так как во время разработки Вы будете часто пересобирать контейнер для проверки работоспособности внесённых изменений, то сэкономленные минуты сложатся в часы, а то и дни. +И так как во время разработки вы будете часто пересобирать контейнер для проверки работоспособности внесённых изменений, то сэкономленные минуты сложатся в часы, а то и дни. Так как папка с кодом приложения **изменяется чаще всего**, то мы расположили её в конце `Dockerfile`, ведь после внесённых в код изменений кэш не будет использован на этом и следующих шагах. @@ -301,7 +301,7 @@ $ docker build -t myimage . ### Запуск Docker-контейнера -* Запустите контейнер, основанный на Вашем образе: +* Запустите контейнер, основанный на вашем образе: <div class="termy"> @@ -315,7 +315,7 @@ $ docker run -d --name mycontainer -p 80:80 myimage Вы можете проверить, что Ваш Docker-контейнер работает перейдя по ссылке: <a href="http://192.168.99.100/items/5?q=somequery" class="external-link" target="_blank">http://192.168.99.100/items/5?q=somequery</a> или <a href="http://127.0.0.1/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1/items/5?q=somequery</a> (или похожей, которую использует Ваш Docker-хост). -Там Вы увидите: +Там вы увидите: ```JSON {"item_id": 5, "q": "somequery"} @@ -325,21 +325,21 @@ $ docker run -d --name mycontainer -p 80:80 myimage Теперь перейдите по ссылке <a href="http://192.168.99.100/docs" class="external-link" target="_blank">http://192.168.99.100/docs</a> или <a href="http://127.0.0.1/docs" class="external-link" target="_blank">http://127.0.0.1/docs</a> (или похожей, которую использует Ваш Docker-хост). -Здесь Вы увидите автоматическую интерактивную документацию API (предоставляемую <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>): +Здесь вы увидите автоматическую интерактивную документацию API (предоставляемую <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):  ## Альтернативная документация API -Также Вы можете перейти по ссылке <a href="http://192.168.99.100/redoc" class="external-link" target="_blank">http://192.168.99.100/redoc</a> or <a href="http://127.0.0.1/redoc" class="external-link" target="_blank">http://127.0.0.1/redoc</a> (или похожей, которую использует Ваш Docker-хост). +Также вы можете перейти по ссылке <a href="http://192.168.99.100/redoc" class="external-link" target="_blank">http://192.168.99.100/redoc</a> or <a href="http://127.0.0.1/redoc" class="external-link" target="_blank">http://127.0.0.1/redoc</a> (или похожей, которую использует Ваш Docker-хост). -Здесь Вы увидите альтернативную автоматическую документацию API (предоставляемую <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>): +Здесь вы увидите альтернативную автоматическую документацию API (предоставляемую <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):  ## Создание Docker-образа на основе однофайлового приложения FastAPI -Если Ваше приложение FastAPI помещено в один файл, например, `main.py` и структура Ваших файлов похожа на эту: +Если ваше приложение FastAPI помещено в один файл, например, `main.py` и структура Ваших файлов похожа на эту: ``` . @@ -376,7 +376,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Давайте вспомним о [Концепциях развёртывания](./concepts.md){.internal-link target=_blank} и применим их к контейнерам. -Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязыают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. +Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязывают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. **Хорошая новость** в том, что независимо от выбранной стратегии, мы всё равно можем покрыть все концепции развёртывания. 🎉 @@ -412,7 +412,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Запуск нескольких экземпляров приложения - Указание количества процессов -Если у Вас есть <abbr title="Несколько серверов настроенных для совместной работы.">кластер</abbr> машин под управлением **Kubernetes**, Docker Swarm Mode, Nomad или аналогичной сложной системой оркестрации контейнеров, скорее всего, вместо использования менеджера процессов (типа Gunicorn и его воркеры) в каждом контейнере, Вы захотите **управлять количеством запущенных экземпляров приложения** на **уровне кластера**. +Если у вас есть <abbr title="Несколько серверов настроенных для совместной работы.">кластер</abbr> машин под управлением **Kubernetes**, Docker Swarm Mode, Nomad или аналогичной сложной системой оркестрации контейнеров, скорее всего, вместо использования менеджера процессов (типа Gunicorn и его воркеры) в каждом контейнере, вы захотите **управлять количеством запущенных экземпляров приложения** на **уровне кластера**. В любую из этих систем управления контейнерами обычно встроен способ управления **количеством запущенных контейнеров** для распределения **нагрузки** от входящих запросов на **уровне кластера**. @@ -427,17 +427,17 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] !!! tip "Подсказка" **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. -Система оркестрации, которую Вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). +Система оркестрации, которую вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). ### Один балансировщик - Множество контейнеров -При работе с **Kubernetes** или аналогичными системами оркестрации использование их внутреннней сети позволяет иметь один **балансировщик нагрузки**, который прослушивает **главный** порт и передаёт запросы **множеству запущенных контейнеров** с Вашими приложениями. +При работе с **Kubernetes** или аналогичными системами оркестрации использование их внутренней сети позволяет иметь один **балансировщик нагрузки**, который прослушивает **главный** порт и передаёт запросы **множеству запущенных контейнеров** с Вашими приложениями. В каждом из контейнеров обычно работает **только один процесс** (например, процесс Uvicorn управляющий Вашим приложением FastAPI). Контейнеры могут быть **идентичными**, запущенными на основе одного и того же образа, но у каждого будут свои отдельные процесс, память и т.п. Таким образом мы получаем преимущества **распараллеливания** работы по **разным ядрам** процессора или даже **разным машинам**. Система управления контейнерами с **балансировщиком нагрузки** будет **распределять запросы** к контейнерам с приложениями **по очереди**. То есть каждый запрос будет обработан одним из множества **одинаковых контейнеров** с одним и тем же приложением. -**Балансировщик нагрузки** может обрабатывать запросы к *разным* приложениям, расположенным в Вашем кластере (например, если у них разные домены или префиксы пути) и передавать запросы нужному контейнеру с требуемым приложением. +**Балансировщик нагрузки** может обрабатывать запросы к *разным* приложениям, расположенным в вашем кластере (например, если у них разные домены или префиксы пути) и передавать запросы нужному контейнеру с требуемым приложением. ### Один процесс на контейнер @@ -449,35 +449,35 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ### <a name="special-cases"></a>Множество процессов внутри контейнера для особых случаев</a> -Безусловно, бывают **особые случаи**, когда может понадобится внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. +Безусловно, бывают **особые случаи**, когда может понадобиться внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. -Для таких случаев Вы можете использовать **официальный Docker-образ** (прим. пер: - *здесь и далее на этой странице, если Вы встретите сочетание "официальный Docker-образ" без уточнений, то автор имеет в виду именно предоставляемый им образ*), где в качестве менеджера процессов используется **Gunicorn**, запускающий несколько **процессов Uvicorn** и некоторые настройки по умолчанию, автоматически устанавливающие количество запущенных процессов в зависимости от количества ядер Вашего процессора. Я расскажу Вам об этом подробнее тут: [Официальный Docker-образ со встроенными Gunicorn и Uvicorn](#docker-gunicorn-uvicorn). +Для таких случаев вы можете использовать **официальный Docker-образ** (прим. пер: - *здесь и далее на этой странице, если вы встретите сочетание "официальный Docker-образ" без уточнений, то автор имеет в виду именно предоставляемый им образ*), где в качестве менеджера процессов используется **Gunicorn**, запускающий несколько **процессов Uvicorn** и некоторые настройки по умолчанию, автоматически устанавливающие количество запущенных процессов в зависимости от количества ядер вашего процессора. Я расскажу вам об этом подробнее тут: [Официальный Docker-образ со встроенными Gunicorn и Uvicorn](#docker-gunicorn-uvicorn). Некоторые примеры подобных случаев: #### Простое приложение -Вы можете использовать менеджер процессов внутри контейнера, если Ваше приложение **настолько простое**, что у Вас нет необходимости (по крайней мере, пока нет) в тщательных настройках количества процессов и Вам достаточно имеющихся настроек по умолчанию (если используется официальный Docker-образ) для запуска приложения **только на одном сервере**, а не в кластере. +Вы можете использовать менеджер процессов внутри контейнера, если ваше приложение **настолько простое**, что у вас нет необходимости (по крайней мере, пока нет) в тщательных настройках количества процессов и вам достаточно имеющихся настроек по умолчанию (если используется официальный Docker-образ) для запуска приложения **только на одном сервере**, а не в кластере. #### Docker Compose -С помощью **Docker Compose** можно разворачивать несколько контейнеров на **одном сервере** (не кластере), но при это у Вас не будет простого способа управления количеством запущенных контейнеров с одновременным сохранением общей сети и **балансировки нагрузки**. +С помощью **Docker Compose** можно разворачивать несколько контейнеров на **одном сервере** (не кластере), но при это у вас не будет простого способа управления количеством запущенных контейнеров с одновременным сохранением общей сети и **балансировки нагрузки**. В этом случае можно использовать **менеджер процессов**, управляющий **несколькими процессами**, внутри **одного контейнера**. #### Prometheus и прочие причины -У Вас могут быть и **другие причины**, когда использование **множества процессов** внутри **одного контейнера** будет проще, нежели запуск **нескольких контейнеров** с **единственным процессом** в каждом из них. +У вас могут быть и **другие причины**, когда использование **множества процессов** внутри **одного контейнера** будет проще, нежели запуск **нескольких контейнеров** с **единственным процессом** в каждом из них. -Например (в зависимости от конфигурации), у Вас могут быть инструменты подобные экспортёру Prometheus, которые должны иметь доступ к **каждому запросу** приходящему в контейнер. +Например (в зависимости от конфигурации), у вас могут быть инструменты подобные экспортёру Prometheus, которые должны иметь доступ к **каждому запросу** приходящему в контейнер. -Если у Вас будет **несколько контейнеров**, то Prometheus, по умолчанию, **при сборе метрик** получит их **только с одного контейнера**, который обрабатывает конкретный запрос, вместо **сбора метрик** со всех работающих контейнеров. +Если у вас будет **несколько контейнеров**, то Prometheus, по умолчанию, **при сборе метрик** получит их **только с одного контейнера**, который обрабатывает конкретный запрос, вместо **сбора метрик** со всех работающих контейнеров. В таком случае может быть проще иметь **один контейнер** со **множеством процессов**, с нужным инструментом (таким как экспортёр Prometheus) в этом же контейнере и собирающем метрики со всех внутренних процессов этого контейнера. --- -Самое главное - **ни одно** из перечисленных правил не является **высеченным в камне** и Вы не обязаны слепо их повторять. Вы можете использовать эти идеи при **рассмотрении Вашего конкретного случая** и самостоятельно решать, какая из концепции подходит лучше: +Самое главное - **ни одно** из перечисленных правил не является **высеченным на камне** и вы не обязаны слепо их повторять. вы можете использовать эти идеи при **рассмотрении вашего конкретного случая** и самостоятельно решать, какая из концепции подходит лучше: * Использование более безопасного протокола HTTPS * Настройки запуска приложения @@ -488,41 +488,41 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Управление памятью -При **запуске одного процесса на контейнер** Вы получаете относительно понятный, стабильный и ограниченный объём памяти, потребляемый одним контейнером. +При **запуске одного процесса на контейнер** вы получаете относительно понятный, стабильный и ограниченный объём памяти, потребляемый одним контейнером. Вы можете установить аналогичные ограничения по памяти при конфигурировании своей системы управления контейнерами (например, **Kubernetes**). Таким образом система сможет **изменять количество контейнеров** на **доступных ей машинах** приводя в соответствие количество памяти нужной контейнерам с количеством памяти доступной в кластере (наборе доступных машин). -Если у Вас **простенькое** приложение, вероятно у Вас не будет **необходимости** устанавливать жёсткие ограничения на выделяемую ему память. Но если приложение **использует много памяти** (например, оно использует модели **машинного обучения**), Вам следует проверить, как много памяти ему требуется и отрегулировать **количество контейнеров** запущенных на **каждой машине** (может быть даже добавить машин в кластер). +Если у вас **простенькое** приложение, вероятно у вас не будет **необходимости** устанавливать жёсткие ограничения на выделяемую ему память. Но если приложение **использует много памяти** (например, оно использует модели **машинного обучения**), вам следует проверить, как много памяти ему требуется и отрегулировать **количество контейнеров** запущенных на **каждой машине** (может быть даже добавить машин в кластер). -Если Вы запускаете **несколько процессов в контейнере**, то должны быть уверены, что эти процессы не **займут памяти больше**, чем доступно для контейнера. +Если вы запускаете **несколько процессов в контейнере**, то должны быть уверены, что эти процессы не **займут памяти больше**, чем доступно для контейнера. ## Подготовительные шаги при запуске контейнеров -Есть два основных подхода, которые Вы можете использовать при запуске контейнеров (Docker, Kubernetes и т.п.). +Есть два основных подхода, которые вы можете использовать при запуске контейнеров (Docker, Kubernetes и т.п.). ### Множество контейнеров -Когда Вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). +Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). !!! info "Информация" При использовании Kubernetes, это может быть <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Инициализирующий контейнер</a>. -При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), Вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. +При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. ### Только один контейнер -Если у Вас несложное приложение для работы которого достаточно **одного контейнера**, но в котором работает **несколько процессов** (или один процесс), то прохождение предварительных шагов можно осуществить в этом же контейнере до запуска основного процесса. Официальный Docker-образ поддерживает такие действия. +Если у вас несложное приложение для работы которого достаточно **одного контейнера**, но в котором работает **несколько процессов** (или один процесс), то прохождение предварительных шагов можно осуществить в этом же контейнере до запуска основного процесса. Официальный Docker-образ поддерживает такие действия. ## Официальный Docker-образ с Gunicorn и Uvicorn -Я подготовил для Вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](./server-workers.md){.internal-link target=_blank}. +Я подготовил для вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](./server-workers.md){.internal-link target=_blank}. Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#special-cases). * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. !!! warning "Предупреждение" - Скорее всего у Вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). + Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). В этом образе есть **автоматический** механизм подстройки для запуска **необходимого количества процессов** в соответствии с доступным количеством ядер процессора. @@ -539,11 +539,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это означает, что он будет пытаться **выжать** из процессора как можно больше **производительности**. -Но Вы можете изменять и обновлять конфигурацию с помощью **переменных окружения** и т.п. +Но вы можете изменять и обновлять конфигурацию с помощью **переменных окружения** и т.п. Поскольку количество процессов зависит от процессора, на котором работает контейнер, **объём потребляемой памяти** также будет зависеть от этого. -А значит, если Вашему приложению требуется много оперативной памяти (например, оно использует модели машинного обучения) и Ваш сервер имеет центральный процессор с большим количеством ядер, но **не слишком большим объёмом оперативной памяти**, то может дойти до того, что контейнер попытается занять памяти больше, чем доступно, из-за чего будет падение производительности (или сервер вовсе упадёт). 🚨 +А значит, если вашему приложению требуется много оперативной памяти (например, оно использует модели машинного обучения) и Ваш сервер имеет центральный процессор с большим количеством ядер, но **не слишком большим объёмом оперативной памяти**, то может дойти до того, что контейнер попытается занять памяти больше, чем доступно, из-за чего будет падение производительности (или сервер вовсе упадёт). 🚨 ### Написание `Dockerfile` @@ -562,7 +562,7 @@ COPY ./app /app ### Большие приложения -Если Вы успели ознакомиться с разделом [Приложения содержащие много файлов](../tutorial/bigger-applications.md){.internal-link target=_blank}, состоящие из множества файлов, Ваш Dockerfile может выглядеть так: +Если вы успели ознакомиться с разделом [Приложения содержащие много файлов](../tutorial/bigger-applications.md){.internal-link target=_blank}, состоящие из множества файлов, Ваш Dockerfile может выглядеть так: ```Dockerfile hl_lines="7" FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 @@ -576,9 +576,9 @@ COPY ./app /app/app ### Как им пользоваться -Если Вы используете **Kubernetes** (или что-то вроде того), скорее всего Вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). +Если вы используете **Kubernetes** (или что-то вроде того), скорее всего вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). -Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#special-cases). Например, если Ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же Вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д +Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#special-cases). Например, если ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д ## Развёртывание образа контейнера @@ -590,11 +590,11 @@ COPY ./app /app/app * С использованием **Kubernetes** в кластере * С использованием режима Docker Swarm в кластере * С использованием других инструментов, таких как Nomad -* С использованием облачного сервиса, который будет управлять разворачиванием Вашего контейнера +* С использованием облачного сервиса, который будет управлять разворачиванием вашего контейнера ## Docker-образ и Poetry -Если Вы пользуетесь <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> для управления зависимостями Вашего проекта, то можете использовать многоэтапную сборку образа: +Если вы пользуетесь <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> для управления зависимостями вашего проекта, то можете использовать многоэтапную сборку образа: ```{ .dockerfile .annotate } # (1) @@ -664,19 +664,19 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] **Этапы сборки Docker-образа** являются частью `Dockerfile` и работают как **временные образы контейнеров**. Они нужны только для создания файлов, используемых в дальнейших этапах. -Первый этап был нужен только для **установки Poetry** и **создания файла `requirements.txt`**, в которым прописаны зависимости Вашего проекта, взятые из файла `pyproject.toml`. +Первый этап был нужен только для **установки Poetry** и **создания файла `requirements.txt`**, в которым прописаны зависимости вашего проекта, взятые из файла `pyproject.toml`. На **следующем этапе** `pip` будет использовать файл `requirements.txt`. В итоговом образе будет содержаться **только последний этап сборки**, предыдущие этапы будут отброшены. -При использовании Poetry, имеет смысл использовать **многоэтапную сборку Docker-образа**, потому что на самом деле Вам не нужен Poetry и его зависимости в окончательном образе контейнера, Вам **нужен только** сгенерированный файл `requirements.txt` для установки зависимостей Вашего проекта. +При использовании Poetry, имеет смысл использовать **многоэтапную сборку Docker-образа**, потому что на самом деле вам не нужен Poetry и его зависимости в окончательном образе контейнера, вам **нужен только** сгенерированный файл `requirements.txt` для установки зависимостей вашего проекта. А на последнем этапе, придерживаясь описанных ранее правил, создаётся итоговый образ ### Использование прокси-сервера завершения TLS и Poetry -И снова повторюсь, если используете прокси-сервер (балансировщик нагрузки), такой, как Nginx или Traefik, добавьте в команду запуска опцию `--proxy-headers`: +И снова повторюсь, если используете прокси-сервер (балансировщик нагрузки), такой как Nginx или Traefik, добавьте в команду запуска опцию `--proxy-headers`: ```Dockerfile CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] @@ -695,6 +695,6 @@ CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port" В большинстве случаев Вам, вероятно, не нужно использовать какой-либо базовый образ, **лучше создать образ контейнера с нуля** на основе официального Docker-образа Python. -Позаботившись о **порядке написания** инструкций в `Dockerfile`, Вы сможете использовать **кэш Docker'а**, **минимизировав время сборки**, максимально повысив свою производительность (и избежать скуки). 😎 +Позаботившись о **порядке написания** инструкций в `Dockerfile`, вы сможете использовать **кэш Docker'а**, **минимизировав время сборки**, максимально повысив свою производительность (и не заскучать). 😎 В некоторых особых случаях вы можете использовать официальный образ Docker для FastAPI. 🤓 diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index a53ab6927..5aa300331 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -1,11 +1,11 @@ # Об HTTPS -Обычно представляется, что HTTPS это некая опция, которая либо "включена", либо нет. +Обычно представляется, что HTTPS это некая опция, которая либо "включена", либо нет. Но всё несколько сложнее. !!! tip "Заметка" - Если Вы торопитесь или Вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. + Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. Чтобы **изучить основы HTTPS** для клиента, перейдите по ссылке <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>. @@ -22,8 +22,8 @@ * **TCP не знает о "доменах"**, но знает об IP-адресах. * Информация о **запрашиваемом домене** извлекается из запроса **на уровне HTTP**. * **Сертификаты HTTPS** "сертифицируют" **конкретный домен**, но проверка сертификатов и шифрование данных происходит на уровне протокола TCP, то есть **до того**, как станет известен домен-получатель данных. -* **По умолчанию** это означает, что у Вас может быть **только один сертификат HTTPS на один IP-адрес**. - * Не важно, насколько большой у Вас сервер и насколько маленькие приложения на нём могут быть. +* **По умолчанию** это означает, что у вас может быть **только один сертификат HTTPS на один IP-адрес**. + * Не важно, насколько большой у вас сервер и насколько маленькие приложения на нём могут быть. * Однако, у этой проблемы есть **решение**. * Существует **расширение** протокола **TLS** (который работает на уровне TCP, то есть до HTTP) называемое **<a href="https://en.wikipedia.org/wiki/Server_Name_Indication" class="external-link" target="_blank"><abbr title="Указание имени сервера">SNI</abbr></a>**. * Расширение SNI позволяет одному серверу (с **одним IP-адресом**) иметь **несколько сертификатов HTTPS** и обслуживать **множество HTTPS-доменов/приложений**. @@ -35,12 +35,12 @@ * получение **зашифрованных HTTPS-запросов** * отправка **расшифрованных HTTP запросов** в соответствующее HTTP-приложение, работающее на том же сервере (в нашем случае, это приложение **FastAPI**) -* получние **HTTP-ответа** от приложения +* получение **HTTP-ответа** от приложения * **шифрование ответа** используя подходящий **сертификат HTTPS** * отправка зашифрованного **HTTPS-ответа клиенту**. Такой сервер часто называют **<a href="https://en.wikipedia.org/wiki/TLS_termination_proxy" class="external-link" target="_blank">Прокси-сервер завершения работы TLS</a>** или просто "прокси-сервер". -Вот некоторые варианты, которые Вы можете использовать в качестве такого прокси-сервера: +Вот некоторые варианты, которые вы можете использовать в качестве такого прокси-сервера: * Traefik (может обновлять сертификаты) * Caddy (может обновлять сертификаты) @@ -67,11 +67,11 @@ ### Имя домена -Чаще всего, всё начинается с **приобретения имени домена**. Затем нужно настроить DNS-сервер (вероятно у того же провайдера, который выдал Вам домен). +Чаще всего, всё начинается с **приобретения имени домена**. Затем нужно настроить DNS-сервер (вероятно у того же провайдера, который выдал вам домен). -Далее, возможно, Вы получаете "облачный" сервер (виртуальную машину) или что-то типа этого, у которого есть <abbr title="Не изменяемый">постоянный</abbr> **публичный IP-адрес**. +Далее, возможно, вы получаете "облачный" сервер (виртуальную машину) или что-то типа этого, у которого есть <abbr title="Не изменяемый">постоянный</abbr> **публичный IP-адрес**. -На DNS-сервере (серверах) Вам следует настроить соответствующую ресурсную запись ("`запись A`"), указав, что **Ваш домен** связан с публичным **IP-адресом Вашего сервера**. +На DNS-сервере (серверах) вам следует настроить соответствующую ресурсную запись ("`запись A`"), указав, что **Ваш домен** связан с публичным **IP-адресом вашего сервера**. Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера. @@ -82,9 +82,9 @@ Теперь давайте сфокусируемся на работе с HTTPS. -Всё начинается с того, что браузер спрашивает у **DNS-серверов**, какой **IP-адрес связан с доменом**, для примера возьмём домен `someapp.example.com`. +Всё начинается с того, что браузер спрашивает у **DNS-серверов**, какой **IP-адрес связан с доменом**, для примера возьмём домен `someapp.example.com`. -DNS-сервера присылают браузеру определённый **IP-адрес**, тот самый публичный IP-адрес Вашего сервера, который Вы указали в ресурсной "записи А" при настройке. +DNS-сервера присылают браузеру определённый **IP-адрес**, тот самый публичный IP-адрес вашего сервера, который вы указали в ресурсной "записи А" при настройке. <img src="/img/deployment/https/https01.svg"> @@ -96,7 +96,7 @@ DNS-сервера присылают браузеру определённый <img src="/img/deployment/https/https02.svg"> -Эта часть клиент-серверного взаимодействия устанавливает TLS-соединение и называется **TLS-рукопожатием**. +Эта часть клиент-серверного взаимодействия устанавливает TLS-соединение и называется **TLS-рукопожатием**. ### TLS с расширением SNI @@ -185,7 +185,7 @@ DNS-сервера присылают браузеру определённый * **Запуск в качестве программы-сервера** (как минимум, на время обновления сертификатов) на публичном IP-адресе домена. * Как уже не раз упоминалось, только один процесс может прослушивать определённый порт определённого IP-адреса. * Это одна из причин использования прокси-сервера ещё и в качестве программы обновления сертификатов. - * В случае, если обновлением сертификатов занимается другая программа, Вам понадобится остановить прокси-сервер, запустить программу обновления сертификатов на сокете, предназначенном для прокси-сервера, настроить прокси-сервер на работу с новыми сертификатами и перезапустить его. Эта схема далека от идеальной, так как Ваши приложения будут недоступны на время отключения прокси-сервера. + * В случае, если обновлением сертификатов занимается другая программа, вам понадобится остановить прокси-сервер, запустить программу обновления сертификатов на сокете, предназначенном для прокси-сервера, настроить прокси-сервер на работу с новыми сертификатами и перезапустить его. Эта схема далека от идеальной, так как Ваши приложения будут недоступны на время отключения прокси-сервера. Весь этот процесс обновления, одновременный с обслуживанием запросов, является одной из основных причин, по которой желательно иметь **отдельную систему для работы с HTTPS** в виде прокси-сервера завершения TLS, а не просто использовать сертификаты TLS непосредственно с сервером приложений (например, Uvicorn). @@ -193,6 +193,6 @@ DNS-сервера присылают браузеру определённый Наличие **HTTPS** очень важно и довольно **критично** в большинстве случаев. Однако, Вам, как разработчику, не нужно тратить много сил на это, достаточно **понимать эти концепции** и принципы их работы. -Но узнав базовые основы **HTTPS** Вы можете легко совмещать разные инструменты, которые помогут Вам в дальнейшей разработке. +Но узнав базовые основы **HTTPS** вы можете легко совмещать разные инструменты, которые помогут вам в дальнейшей разработке. -В следующих главах я покажу Вам несколько примеров, как настраивать **HTTPS** для приложений **FastAPI**. 🔒 +В следующих главах я покажу вам несколько примеров, как настраивать **HTTPS** для приложений **FastAPI**. 🔒 diff --git a/docs/ru/docs/deployment/index.md b/docs/ru/docs/deployment/index.md index d214a9d62..e88ddc3e2 100644 --- a/docs/ru/docs/deployment/index.md +++ b/docs/ru/docs/deployment/index.md @@ -8,7 +8,7 @@ Обычно **веб-приложения** размещают на удалённом компьютере с серверной программой, которая обеспечивает хорошую производительность, стабильность и т. д., Чтобы ваши пользователи могли эффективно, беспрерывно и беспроблемно обращаться к приложению. -Это отличется от **разработки**, когда вы постоянно меняете код, делаете в нём намеренные ошибки и исправляете их, останавливаете и перезапускаете сервер разработки и т. д. +Это отличается от **разработки**, когда вы постоянно меняете код, делаете в нём намеренные ошибки и исправляете их, останавливаете и перезапускаете сервер разработки и т. д. ## Стратегии развёртывания diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index 1d00b3086..a24580489 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -1,6 +1,6 @@ # Запуск сервера вручную - Uvicorn -Для запуска приложения **FastAPI** на удалённой серверной машине Вам необходим программный сервер, поддерживающий протокол ASGI, такой как **Uvicorn**. +Для запуска приложения **FastAPI** на удалённой серверной машине вам необходим программный сервер, поддерживающий протокол ASGI, такой как **Uvicorn**. Существует три наиболее распространённые альтернативы: @@ -10,16 +10,16 @@ ## Сервер как машина и сервер как программа -В этих терминах есть некоторые различия и Вам следует запомнить их. 💡 +В этих терминах есть некоторые различия и вам следует запомнить их. 💡 Слово "**сервер**" чаще всего используется в двух контекстах: - удалённый или расположенный в "облаке" компьютер (физическая или виртуальная машина). - программа, запущенная на таком компьютере (например, Uvicorn). -Просто запомните, если Вам встретился термин "сервер", то обычно он подразумевает что-то из этих двух смыслов. +Просто запомните, если вам встретился термин "сервер", то обычно он подразумевает что-то из этих двух смыслов. -Когда имеют в виду именно удалённый компьютер, часто говорят просто **сервер**, но ещё его называют **машина**, **ВМ** (виртуальная машина), **нода**. Все эти термины обозначают одно и то же - удалённый компьютер, обычно под управлением Linux, на котором Вы запускаете программы. +Когда имеют в виду именно удалённый компьютер, часто говорят просто **сервер**, но ещё его называют **машина**, **ВМ** (виртуальная машина), **нода**. Все эти термины обозначают одно и то же - удалённый компьютер, обычно под управлением Linux, на котором вы запускаете программы. ## Установка программного сервера @@ -27,7 +27,7 @@ === "Uvicorn" - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, молниесный ASGI сервер, основанный на библиотеках uvloop и httptools. + * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools. <div class="termy"> @@ -40,7 +40,7 @@ </div> !!! tip "Подсказка" - С опцией `standard`, Uvicorn будет установливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. + С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. @@ -62,7 +62,7 @@ ## Запуск серверной программы -Затем запустите Ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: +Затем запустите ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: === "Uvicorn" @@ -103,11 +103,11 @@ Starlette и **FastAPI** основаны на <a href="https://anyio.readthedoc Тем не менее Uvicorn совместим только с asyncio и обычно используется совместно с <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a>, высокопроизводительной заменой `asyncio`. -Но если Вы хотите использовать **Trio** напрямую, то можете воспользоваться **Hypercorn**, так как они совместимы. ✨ +Но если вы хотите использовать **Trio** напрямую, то можете воспользоваться **Hypercorn**, так как они совместимы. ✨ ### Установка Hypercorn с Trio -Для начала, Вам нужно установить Hypercorn с поддержкой Trio: +Для начала, вам нужно установить Hypercorn с поддержкой Trio: <div class="termy"> @@ -130,15 +130,15 @@ $ hypercorn main:app --worker-class trio </div> -Hypercorn, в свою очередь, запустит Ваше приложение использующее Trio. +Hypercorn, в свою очередь, запустит ваше приложение использующее Trio. -Таким образом, Вы сможете использовать Trio в своём приложении. Но лучше использовать AnyIO, для сохранения совместимости и с Trio, и с asyncio. 🎉 +Таким образом, вы сможете использовать Trio в своём приложении. Но лучше использовать AnyIO, для сохранения совместимости и с Trio, и с asyncio. 🎉 ## Концепции развёртывания В вышеприведённых примерах серверные программы (например Uvicorn) запускали только **один процесс**, принимающий входящие запросы с любого IP (на это указывал аргумент `0.0.0.0`) на определённый порт (в примерах мы указывали порт `80`). -Это основная идея. Но возможно, Вы озаботитесь добавлением дополнительных возможностей, таких как: +Это основная идея. Но возможно, вы озаботитесь добавлением дополнительных возможностей, таких как: * Использование более безопасного протокола HTTPS * Настройки запуска приложения @@ -147,4 +147,4 @@ Hypercorn, в свою очередь, запустит Ваше приложе * Управление памятью * Использование перечисленных функций перед запуском приложения. -Я поведаю Вам больше о каждой из этих концепций в следующих главах, с конкретными примерами стратегий работы с ними. 🚀 +Я расскажу вам больше о каждой из этих концепций в следующих главах, с конкретными примерами стратегий работы с ними. 🚀 From 8dfdf69d6bfb4869fb50df1828e5ad98c6a5fa6e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 3 Apr 2024 16:23:13 +0000 Subject: [PATCH 387/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f3aff2ebd..433497827 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Russian translations for deployments docs. PR [#11271](https://github.com/tiangolo/fastapi/pull/11271) by [@Lufa1u](https://github.com/Lufa1u). * 🌐 Add Bengali translations for `docs/bn/docs/python-types.md`. PR [#11376](https://github.com/tiangolo/fastapi/pull/11376) by [@imtiaz101325](https://github.com/imtiaz101325). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#5744](https://github.com/tiangolo/fastapi/pull/5744) by [@KdHyeon0661](https://github.com/KdHyeon0661). * 🌐 Add Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#4139](https://github.com/tiangolo/fastapi/pull/4139) by [@kty4119](https://github.com/kty4119). From f810c65e7ce5cf26f238929798e17195a15533c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nazar=C3=A9=20da=20Piedade?= <31008635+nazarepiedady@users.noreply.github.com> Date: Thu, 4 Apr 2024 15:20:02 +0100 Subject: [PATCH 388/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lations=20for=20`learn/index.md`=20`resources/index.md`=20`help?= =?UTF-8?q?/index.md`=20`about/index.md`=20(#10807)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/about/index.md | 3 +++ docs/pt/docs/help/index.md | 3 +++ docs/pt/docs/learn/index.md | 5 +++++ docs/pt/docs/resources/index.md | 3 +++ 4 files changed, 14 insertions(+) create mode 100644 docs/pt/docs/about/index.md create mode 100644 docs/pt/docs/help/index.md create mode 100644 docs/pt/docs/learn/index.md create mode 100644 docs/pt/docs/resources/index.md diff --git a/docs/pt/docs/about/index.md b/docs/pt/docs/about/index.md new file mode 100644 index 000000000..1f42e8831 --- /dev/null +++ b/docs/pt/docs/about/index.md @@ -0,0 +1,3 @@ +# Sobre + +Sobre o FastAPI, seus padrões, inspirações e muito mais. 🤓 diff --git a/docs/pt/docs/help/index.md b/docs/pt/docs/help/index.md new file mode 100644 index 000000000..e254e10df --- /dev/null +++ b/docs/pt/docs/help/index.md @@ -0,0 +1,3 @@ +# Ajude + +Ajude e obtenha ajuda, contribua, participe. 🤝 diff --git a/docs/pt/docs/learn/index.md b/docs/pt/docs/learn/index.md new file mode 100644 index 000000000..b9a7f5972 --- /dev/null +++ b/docs/pt/docs/learn/index.md @@ -0,0 +1,5 @@ +# Aprender + +Nesta parte da documentação encontramos as seções introdutórias e os tutoriais para aprendermos como usar o **FastAPI**. + +Nós poderíamos considerar isto um **livro**, **curso**, a maneira **oficial** e recomendada de aprender o FastAPI. 😎 diff --git a/docs/pt/docs/resources/index.md b/docs/pt/docs/resources/index.md new file mode 100644 index 000000000..6eff8f9e7 --- /dev/null +++ b/docs/pt/docs/resources/index.md @@ -0,0 +1,3 @@ +# Recursos + +Material complementar, links externos, artigos e muito mais. ✈️ From 886dc33f85a061ebf869b9ac683cc93697bbfb87 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 4 Apr 2024 14:20:26 +0000 Subject: [PATCH 389/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 433497827..b0ad0b687 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translations for `learn/index.md` `resources/index.md` `help/index.md` `about/index.md`. PR [#10807](https://github.com/tiangolo/fastapi/pull/10807) by [@nazarepiedady](https://github.com/nazarepiedady). * 🌐 Update Russian translations for deployments docs. PR [#11271](https://github.com/tiangolo/fastapi/pull/11271) by [@Lufa1u](https://github.com/Lufa1u). * 🌐 Add Bengali translations for `docs/bn/docs/python-types.md`. PR [#11376](https://github.com/tiangolo/fastapi/pull/11376) by [@imtiaz101325](https://github.com/imtiaz101325). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#5744](https://github.com/tiangolo/fastapi/pull/5744) by [@KdHyeon0661](https://github.com/KdHyeon0661). From 9e074c2ed234aba3d93d915ade6adec1ca6bddb0 Mon Sep 17 00:00:00 2001 From: Fabian Falon <fabian.falon@gmail.com> Date: Thu, 4 Apr 2024 16:20:53 +0200 Subject: [PATCH 390/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20typo=20in=20`docs/?= =?UTF-8?q?es/docs/async.md`=20(#11400)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/async.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 0fdc30739..dcd6154be 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -190,7 +190,7 @@ Luego, el cajero / cocinero 👨🍳 finalmente regresa con tus hamburguesas <img src="https://fastapi.tiangolo.com/img/async/parallel-burgers/parallel-burgers-05.png" alt="illustration"> -Cojes tus hamburguesas 🍔 y vas a la mesa con esa persona 😍. +Coges tus hamburguesas 🍔 y vas a la mesa con esa persona 😍. Sólo las comes y listo 🍔 ⏹. From 7e161b3f9e7ae5b6a37ab8ea13b6dd2c1c11eff9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 4 Apr 2024 14:22:38 +0000 Subject: [PATCH 391/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b0ad0b687..1d63a25c7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix typo in `docs/es/docs/async.md`. PR [#11400](https://github.com/tiangolo/fastapi/pull/11400) by [@fabianfalon](https://github.com/fabianfalon). * 📝 Update OpenAPI client generation docs to use `@hey-api/openapi-ts`. PR [#11339](https://github.com/tiangolo/fastapi/pull/11339) by [@jordanshatford](https://github.com/jordanshatford). ### Translations From 91606c3c3875ec5cf5054cd1f8444f81befd55d4 Mon Sep 17 00:00:00 2001 From: Anton Yakovlev <44229180+anton2yakovlev@users.noreply.github.com> Date: Sat, 6 Apr 2024 18:43:55 +0300 Subject: [PATCH 392/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/dependencies/dependencies-in?= =?UTF-8?q?-path-operation-decorators.md`=20(#11411)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...pendencies-in-path-operation-decorators.md | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md 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 new file mode 100644 index 000000000..2bd096189 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,139 @@ +# Зависимости в декораторах операции пути + +В некоторых случаях, возвращаемое значение зависимости не используется внутри *функции операции пути*. + +Или же зависимость не возвращает никакого значения. + +Но вам всё-таки нужно, чтобы она выполнилась. + +Для таких ситуаций, вместо объявления *функции операции пути* с параметром `Depends`, вы можете добавить список зависимостей `dependencies` в *декоратор операции пути*. + +## Добавление `dependencies` в *декоратор операции пути* + +*Декоратор операции пути* получает необязательный аргумент `dependencies`. + +Это должен быть `list` состоящий из `Depends()`: + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 без Annotated" + + !!! Подсказка + Рекомендуется использовать версию с Annotated, если возможно. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. + +!!! Подсказка + Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. + + Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов. + + Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости. + +!!! Дополнительная информация + В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. + + Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}. + +## Исключения в dependencies и возвращаемые значения + +Вы можете использовать те же *функции* зависимостей, что и обычно. + +### Требования к зависимостям + +Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: + +=== "Python 3.9+" + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7 12" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 без Annotated" + + !!! Подсказка + Рекомендуется использовать версию с Annotated, если возможно. + + ```Python hl_lines="6 11" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### Вызов исключений + +Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 без Annotated" + + !!! Подсказка + Рекомендуется использовать версию с Annotated, если возможно. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### Возвращаемые значения + +И они могут возвращать значения или нет, эти значения использоваться не будут. + +Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: + +=== "Python 3.9+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 без Annotated" + + !!! Подсказка + Рекомендуется использовать версию с Annotated, если возможно. + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +## Dependencies для группы *операций путей* + +Позже, читая о том как структурировать большие приложения ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), возможно, многофайловые, вы узнаете как объявить единый параметр `dependencies` для всей группы *операций путей*. + +## Глобальный Dependencies + +Далее мы увидим, как можно добавить dependencies для всего `FastAPI` приложения, так чтобы они применялись к каждой *операции пути*. From 3425c834cc113060d00b8a295d3456eb306a109d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 6 Apr 2024 15:44:16 +0000 Subject: [PATCH 393/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1d63a25c7..5ae22dde3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#11411](https://github.com/tiangolo/fastapi/pull/11411) by [@anton2yakovlev](https://github.com/anton2yakovlev). * 🌐 Add Portuguese translations for `learn/index.md` `resources/index.md` `help/index.md` `about/index.md`. PR [#10807](https://github.com/tiangolo/fastapi/pull/10807) by [@nazarepiedady](https://github.com/nazarepiedady). * 🌐 Update Russian translations for deployments docs. PR [#11271](https://github.com/tiangolo/fastapi/pull/11271) by [@Lufa1u](https://github.com/Lufa1u). * 🌐 Add Bengali translations for `docs/bn/docs/python-types.md`. PR [#11376](https://github.com/tiangolo/fastapi/pull/11376) by [@imtiaz101325](https://github.com/imtiaz101325). From 27da0d02a786c7a3ad45610516063960806371f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 18 Apr 2024 14:40:57 -0500 Subject: [PATCH 394/846] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20Pydan?= =?UTF-8?q?tic's=202.7=20new=20deprecated=20Field=20parameter,=20remove=20?= =?UTF-8?q?URL=20from=20validation=20errors=20response=20(#11461)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test.yml | 4 +-- .../tutorial007.py | 2 +- fastapi/_compat.py | 8 +++-- fastapi/openapi/utils.py | 2 +- fastapi/param_functions.py | 14 ++++---- fastapi/params.py | 28 +++++++++------ fastapi/utils.py | 6 ---- tests/test_annotated.py | 3 -- tests/test_dependency_duplicates.py | 2 -- tests/test_dependency_overrides.py | 13 ------- tests/test_filter_pydantic_sub_model_pv2.py | 2 -- tests/test_multi_body_errors.py | 6 ---- tests/test_multi_query_errors.py | 3 -- tests/test_path.py | 35 ------------------- tests/test_query.py | 12 ------- tests/test_regex_deprecated_body.py | 2 -- tests/test_regex_deprecated_params.py | 2 -- tests/test_security_oauth2.py | 6 ---- tests/test_security_oauth2_optional.py | 6 ---- ...st_security_oauth2_optional_description.py | 6 ---- .../test_bigger_applications/test_main.py | 11 ------ .../test_bigger_applications/test_main_an.py | 11 ------ .../test_main_an_py39.py | 11 ------ .../test_body/test_tutorial001.py | 12 ------- .../test_body/test_tutorial001_py310.py | 10 ------ .../test_body_fields/test_tutorial001.py | 2 -- .../test_body_fields/test_tutorial001_an.py | 2 -- .../test_tutorial001_an_py310.py | 2 -- .../test_tutorial001_an_py39.py | 2 -- .../test_tutorial001_py310.py | 2 -- .../test_tutorial001.py | 2 -- .../test_tutorial001_an.py | 2 -- .../test_tutorial001_an_py310.py | 2 -- .../test_tutorial001_an_py39.py | 2 -- .../test_tutorial001_py310.py | 2 -- .../test_tutorial003.py | 7 ---- .../test_tutorial003_an.py | 7 ---- .../test_tutorial003_an_py310.py | 7 ---- .../test_tutorial003_an_py39.py | 7 ---- .../test_tutorial003_py310.py | 7 ---- .../test_tutorial009.py | 2 -- .../test_tutorial009_py39.py | 2 -- .../test_tutorial002.py | 2 -- .../test_dataclasses/test_tutorial001.py | 2 -- .../test_dependencies/test_tutorial006.py | 3 -- .../test_dependencies/test_tutorial006_an.py | 3 -- .../test_tutorial006_an_py39.py | 3 -- .../test_dependencies/test_tutorial012.py | 5 --- .../test_dependencies/test_tutorial012_an.py | 5 --- .../test_tutorial012_an_py39.py | 5 --- .../test_handling_errors/test_tutorial005.py | 2 -- .../test_handling_errors/test_tutorial006.py | 2 -- .../test_tutorial007.py | 2 -- .../test_query_params/test_tutorial005.py | 2 -- .../test_query_params/test_tutorial006.py | 4 --- .../test_tutorial006_py310.py | 4 --- .../test_tutorial010.py | 2 -- .../test_tutorial010_an.py | 2 -- .../test_tutorial010_an_py310.py | 2 -- .../test_tutorial010_an_py39.py | 2 -- .../test_tutorial010_py310.py | 2 -- .../test_request_files/test_tutorial001.py | 3 -- .../test_request_files/test_tutorial001_an.py | 3 -- .../test_tutorial001_an_py39.py | 3 -- .../test_request_files/test_tutorial002.py | 3 -- .../test_request_files/test_tutorial002_an.py | 3 -- .../test_tutorial002_an_py39.py | 3 -- .../test_tutorial002_py39.py | 3 -- .../test_request_forms/test_tutorial001.py | 7 ---- .../test_request_forms/test_tutorial001_an.py | 7 ---- .../test_tutorial001_an_py39.py | 7 ---- .../test_tutorial001.py | 11 ------ .../test_tutorial001_an.py | 11 ------ .../test_tutorial001_an_py39.py | 11 ------ 74 files changed, 33 insertions(+), 372 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 125265e53..fe1e419d6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -32,7 +32,7 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 + key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v08 - name: Install Dependencies if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-tests.txt @@ -70,7 +70,7 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 + key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v08 - name: Install Dependencies if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-tests.txt diff --git a/docs_src/path_operation_advanced_configuration/tutorial007.py b/docs_src/path_operation_advanced_configuration/tutorial007.py index 972ddbd2c..54e2e9399 100644 --- a/docs_src/path_operation_advanced_configuration/tutorial007.py +++ b/docs_src/path_operation_advanced_configuration/tutorial007.py @@ -30,5 +30,5 @@ async def create_item(request: Request): try: item = Item.model_validate(data) except ValidationError as e: - raise HTTPException(status_code=422, detail=e.errors()) + raise HTTPException(status_code=422, detail=e.errors(include_url=False)) return item diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 35d4a8723..06b847b4f 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -20,10 +20,12 @@ from typing import ( from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model -from pydantic.version import VERSION as PYDANTIC_VERSION +from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile 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.") @@ -127,7 +129,7 @@ if PYDANTIC_V2: ) except ValidationError as exc: return None, _regenerate_error_with_loc( - errors=exc.errors(), loc_prefix=loc + errors=exc.errors(include_url=False), loc_prefix=loc ) def serialize( @@ -266,7 +268,7 @@ if PYDANTIC_V2: def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] - ).errors()[0] + ).errors(include_url=False)[0] error["input"] = None return error # type: ignore[return-value] diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 5bfb5acef..79ad9f83f 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -123,7 +123,7 @@ def get_openapi_operation_parameters( elif field_info.example != Undefined: parameter["example"] = jsonable_encoder(field_info.example) if field_info.deprecated: - parameter["deprecated"] = field_info.deprecated + parameter["deprecated"] = True parameters.append(parameter) return parameters diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 6722a7d66..3b25d774a 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -240,7 +240,7 @@ def Path( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -565,7 +565,7 @@ def Query( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -880,7 +880,7 @@ def Header( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1185,7 +1185,7 @@ def Cookie( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1512,7 +1512,7 @@ def Body( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1827,7 +1827,7 @@ def Form( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -2141,7 +2141,7 @@ def File( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. diff --git a/fastapi/params.py b/fastapi/params.py index b40944dba..860146531 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -6,7 +6,7 @@ from fastapi.openapi.models import Example from pydantic.fields import FieldInfo from typing_extensions import Annotated, deprecated -from ._compat import PYDANTIC_V2, Undefined +from ._compat import PYDANTIC_V2, PYDANTIC_VERSION, Undefined _Unset: Any = Undefined @@ -63,12 +63,11 @@ class Param(FieldInfo): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): - self.deprecated = deprecated if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", @@ -106,6 +105,10 @@ class Param(FieldInfo): stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION < "2.7.0": + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { @@ -174,7 +177,7 @@ class Path(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -260,7 +263,7 @@ class Query(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -345,7 +348,7 @@ class Header(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -430,7 +433,7 @@ class Cookie(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -514,14 +517,13 @@ class Body(FieldInfo): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.embed = embed self.media_type = media_type - self.deprecated = deprecated if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", @@ -559,6 +561,10 @@ class Body(FieldInfo): stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION < "2.7.0": + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { @@ -627,7 +633,7 @@ class Form(Body): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -712,7 +718,7 @@ class File(Form): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, diff --git a/fastapi/utils.py b/fastapi/utils.py index 53b2fa0c3..dfda4e678 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -221,9 +221,3 @@ def get_value_or_default( if not isinstance(item, DefaultPlaceholder): return item return first_item - - -def match_pydantic_error_url(error_type: str) -> Any: - from dirty_equals import IsStr - - return IsStr(regex=rf"^https://errors\.pydantic\.dev/.*/v/{error_type}") diff --git a/tests/test_annotated.py b/tests/test_annotated.py index 2222be978..473d33e52 100644 --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import APIRouter, FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated app = FastAPI() @@ -38,7 +37,6 @@ foo_is_missing = { "msg": "Field required", "type": "missing", "input": None, - "url": match_pydantic_error_url("missing"), } ) # TODO: remove when deprecating Pydantic v1 @@ -60,7 +58,6 @@ foo_is_short = { "msg": "String should have at least 1 character", "type": "string_too_short", "input": "", - "url": match_pydantic_error_url("string_too_short"), } ) # TODO: remove when deprecating Pydantic v1 diff --git a/tests/test_dependency_duplicates.py b/tests/test_dependency_duplicates.py index 0882cc41d..8e8d07c2d 100644 --- a/tests/test_dependency_duplicates.py +++ b/tests/test_dependency_duplicates.py @@ -3,7 +3,6 @@ from typing import List from dirty_equals import IsDict from fastapi import Depends, FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -57,7 +56,6 @@ def test_no_duplicates_invalid(): "loc": ["body", "item2"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_dependency_overrides.py b/tests/test_dependency_overrides.py index 21cff998d..154937fa0 100644 --- a/tests/test_dependency_overrides.py +++ b/tests/test_dependency_overrides.py @@ -4,7 +4,6 @@ import pytest from dirty_equals import IsDict from fastapi import APIRouter, Depends, FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -63,7 +62,6 @@ def test_main_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -110,7 +108,6 @@ def test_decorator_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -151,7 +148,6 @@ def test_router_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -198,7 +194,6 @@ def test_router_decorator_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -285,7 +280,6 @@ def test_override_with_sub_main_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -316,7 +310,6 @@ def test_override_with_sub__main_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -355,7 +348,6 @@ def test_override_with_sub_decorator_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -386,7 +378,6 @@ def test_override_with_sub_decorator_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -425,7 +416,6 @@ def test_override_with_sub_router_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -456,7 +446,6 @@ def test_override_with_sub_router_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -495,7 +484,6 @@ def test_override_with_sub_router_decorator_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -526,7 +514,6 @@ def test_override_with_sub_router_decorator_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_filter_pydantic_sub_model_pv2.py b/tests/test_filter_pydantic_sub_model_pv2.py index 9097d2ce5..2e2c26ddc 100644 --- a/tests/test_filter_pydantic_sub_model_pv2.py +++ b/tests/test_filter_pydantic_sub_model_pv2.py @@ -5,7 +5,6 @@ from dirty_equals import HasRepr, IsDict, IsOneOf from fastapi import Depends, FastAPI from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .utils import needs_pydanticv2 @@ -67,7 +66,6 @@ def test_validator_is_cloned(client: TestClient): "msg": "Value error, name must end in A", "input": "modelX", "ctx": {"error": HasRepr("ValueError('name must end in A')")}, - "url": match_pydantic_error_url("value_error"), } ) | IsDict( diff --git a/tests/test_multi_body_errors.py b/tests/test_multi_body_errors.py index a51ca7253..0102f0f1a 100644 --- a/tests/test_multi_body_errors.py +++ b/tests/test_multi_body_errors.py @@ -4,7 +4,6 @@ from typing import List from dirty_equals import IsDict, IsOneOf from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel, condecimal app = FastAPI() @@ -52,7 +51,6 @@ def test_jsonable_encoder_requiring_error(): "msg": "Input should be greater than 0", "input": -1.0, "ctx": {"gt": 0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -82,28 +80,24 @@ def test_put_incorrect_body_multiple(): "loc": ["body", 0, "name"], "msg": "Field required", "input": {"age": "five"}, - "url": match_pydantic_error_url("missing"), }, { "type": "decimal_parsing", "loc": ["body", 0, "age"], "msg": "Input should be a valid decimal", "input": "five", - "url": match_pydantic_error_url("decimal_parsing"), }, { "type": "missing", "loc": ["body", 1, "name"], "msg": "Field required", "input": {"age": "six"}, - "url": match_pydantic_error_url("missing"), }, { "type": "decimal_parsing", "loc": ["body", 1, "age"], "msg": "Input should be a valid decimal", "input": "six", - "url": match_pydantic_error_url("decimal_parsing"), }, ] } diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py index 470a35808..8162d986c 100644 --- a/tests/test_multi_query_errors.py +++ b/tests/test_multi_query_errors.py @@ -3,7 +3,6 @@ from typing import List from dirty_equals import IsDict from fastapi import FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -33,14 +32,12 @@ def test_multi_query_incorrect(): "loc": ["query", "q", 0], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "five", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "q", 1], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "six", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_path.py b/tests/test_path.py index 848b245e2..09c1f13fb 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .main import app @@ -54,7 +53,6 @@ def test_path_int_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foobar", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -83,7 +81,6 @@ def test_path_int_True(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "True", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -118,7 +115,6 @@ def test_path_int_42_5(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "42.5", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -147,7 +143,6 @@ def test_path_float_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "foobar", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -176,7 +171,6 @@ def test_path_float_True(): "loc": ["path", "item_id"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "True", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -217,7 +211,6 @@ def test_path_bool_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "foobar", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -252,7 +245,6 @@ def test_path_bool_42(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "42", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -281,7 +273,6 @@ def test_path_bool_42_5(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "42.5", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -353,7 +344,6 @@ def test_path_param_minlength_fo(): "msg": "String should have at least 3 characters", "input": "fo", "ctx": {"min_length": 3}, - "url": match_pydantic_error_url("string_too_short"), } ] } @@ -390,7 +380,6 @@ def test_path_param_maxlength_foobar(): "msg": "String should have at most 3 characters", "input": "foobar", "ctx": {"max_length": 3}, - "url": match_pydantic_error_url("string_too_long"), } ] } @@ -427,7 +416,6 @@ def test_path_param_min_maxlength_foobar(): "msg": "String should have at most 3 characters", "input": "foobar", "ctx": {"max_length": 3}, - "url": match_pydantic_error_url("string_too_long"), } ] } @@ -458,7 +446,6 @@ def test_path_param_min_maxlength_f(): "msg": "String should have at least 2 characters", "input": "f", "ctx": {"min_length": 2}, - "url": match_pydantic_error_url("string_too_short"), } ] } @@ -494,7 +481,6 @@ def test_path_param_gt_2(): "msg": "Input should be greater than 3", "input": "2", "ctx": {"gt": 3.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -531,7 +517,6 @@ def test_path_param_gt0_0(): "msg": "Input should be greater than 0", "input": "0", "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -574,7 +559,6 @@ def test_path_param_ge_2(): "msg": "Input should be greater than or equal to 3", "input": "2", "ctx": {"ge": 3.0}, - "url": match_pydantic_error_url("greater_than_equal"), } ] } @@ -605,7 +589,6 @@ def test_path_param_lt_42(): "msg": "Input should be less than 3", "input": "42", "ctx": {"lt": 3.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -648,7 +631,6 @@ def test_path_param_lt0_0(): "msg": "Input should be less than 0", "input": "0", "ctx": {"lt": 0.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -679,7 +661,6 @@ def test_path_param_le_42(): "msg": "Input should be less than or equal to 3", "input": "42", "ctx": {"le": 3.0}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -728,7 +709,6 @@ def test_path_param_lt_gt_4(): "msg": "Input should be less than 3", "input": "4", "ctx": {"lt": 3.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -759,7 +739,6 @@ def test_path_param_lt_gt_0(): "msg": "Input should be greater than 1", "input": "0", "ctx": {"gt": 1.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -807,7 +786,6 @@ def test_path_param_le_ge_4(): "msg": "Input should be less than or equal to 3", "input": "4", "ctx": {"le": 3.0}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -844,7 +822,6 @@ def test_path_param_lt_int_42(): "msg": "Input should be less than 3", "input": "42", "ctx": {"lt": 3}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -874,7 +851,6 @@ def test_path_param_lt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -910,7 +886,6 @@ def test_path_param_gt_int_2(): "msg": "Input should be greater than 3", "input": "2", "ctx": {"gt": 3}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -940,7 +915,6 @@ def test_path_param_gt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -970,7 +944,6 @@ def test_path_param_le_int_42(): "msg": "Input should be less than or equal to 3", "input": "42", "ctx": {"le": 3}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -1012,7 +985,6 @@ def test_path_param_le_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1054,7 +1026,6 @@ def test_path_param_ge_int_2(): "msg": "Input should be greater than or equal to 3", "input": "2", "ctx": {"ge": 3}, - "url": match_pydantic_error_url("greater_than_equal"), } ] } @@ -1084,7 +1055,6 @@ def test_path_param_ge_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1120,7 +1090,6 @@ def test_path_param_lt_gt_int_4(): "msg": "Input should be less than 3", "input": "4", "ctx": {"lt": 3}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -1151,7 +1120,6 @@ def test_path_param_lt_gt_int_0(): "msg": "Input should be greater than 1", "input": "0", "ctx": {"gt": 1}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -1181,7 +1149,6 @@ def test_path_param_lt_gt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1229,7 +1196,6 @@ def test_path_param_le_ge_int_4(): "msg": "Input should be less than or equal to 3", "input": "4", "ctx": {"le": 3}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -1259,7 +1225,6 @@ def test_path_param_le_ge_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_query.py b/tests/test_query.py index 5bb9995d6..2ce4fcd0b 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .main import app @@ -18,7 +17,6 @@ def test_query(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -53,7 +51,6 @@ def test_query_not_declared_baz(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -100,7 +97,6 @@ def test_query_int(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -135,7 +131,6 @@ def test_query_int_query_42_5(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "42.5", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -164,7 +159,6 @@ def test_query_int_query_baz(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "baz", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -193,7 +187,6 @@ def test_query_int_not_declared_baz(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -234,7 +227,6 @@ def test_query_int_optional_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -275,7 +267,6 @@ def test_query_int_default_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -316,7 +307,6 @@ def test_query_param_required(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -351,7 +341,6 @@ def test_query_param_required_int(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -386,7 +375,6 @@ def test_query_param_required_int_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_regex_deprecated_body.py b/tests/test_regex_deprecated_body.py index 7afddd9ae..74654ff3c 100644 --- a/tests/test_regex_deprecated_body.py +++ b/tests/test_regex_deprecated_body.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI, Form from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated from .utils import needs_py310 @@ -55,7 +54,6 @@ def test_query_nonregexquery(): "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_regex_deprecated_params.py b/tests/test_regex_deprecated_params.py index 7190b543c..2ce64c686 100644 --- a/tests/test_regex_deprecated_params.py +++ b/tests/test_regex_deprecated_params.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated from .utils import needs_py310 @@ -55,7 +54,6 @@ def test_query_params_str_validations_item_query_nonregexquery(): "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py index e98f80ebf..7d914d034 100644 --- a/tests/test_security_oauth2.py +++ b/tests/test_security_oauth2.py @@ -2,7 +2,6 @@ from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -71,21 +70,18 @@ def test_strict_login_no_data(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -124,7 +120,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -157,7 +152,6 @@ def test_strict_login_incorrect_grant_type(): "msg": "String should match pattern 'password'", "input": "incorrect", "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py index d06c01bba..0da3b911e 100644 --- a/tests/test_security_oauth2_optional.py +++ b/tests/test_security_oauth2_optional.py @@ -4,7 +4,6 @@ from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -75,21 +74,18 @@ def test_strict_login_no_data(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,7 +124,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -161,7 +156,6 @@ def test_strict_login_incorrect_grant_type(): "msg": "String should match pattern 'password'", "input": "incorrect", "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_security_oauth2_optional_description.py b/tests/test_security_oauth2_optional_description.py index 9287e4366..85a9f9b39 100644 --- a/tests/test_security_oauth2_optional_description.py +++ b/tests/test_security_oauth2_optional_description.py @@ -4,7 +4,6 @@ from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -76,21 +75,18 @@ def test_strict_login_None(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -129,7 +125,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -162,7 +157,6 @@ def test_strict_login_incorrect_grant_type(): "msg": "String should match pattern 'password'", "input": "incorrect", "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py index 526e265a6..35fdfa4a6 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main.py +++ b/tests/test_tutorial/test_bigger_applications/test_main.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_users_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -64,7 +62,6 @@ def test_users_foo_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -99,7 +96,6 @@ def test_users_me_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -145,7 +141,6 @@ def test_items_with_no_token_jessica(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -192,7 +187,6 @@ def test_items_plumbus_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -233,7 +227,6 @@ def test_items_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -262,7 +255,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -297,7 +289,6 @@ def test_root_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -326,14 +317,12 @@ def test_put_no_header(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an.py b/tests/test_tutorial/test_bigger_applications/test_main_an.py index c0b77d4a7..4e2e3e74d 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main_an.py +++ b/tests/test_tutorial/test_bigger_applications/test_main_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_users_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -64,7 +62,6 @@ def test_users_foo_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -99,7 +96,6 @@ def test_users_me_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -145,7 +141,6 @@ def test_items_with_no_token_jessica(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -192,7 +187,6 @@ def test_items_plumbus_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -233,7 +227,6 @@ def test_items_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -262,7 +255,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -297,7 +289,6 @@ def test_root_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -326,14 +317,12 @@ def test_put_no_header(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py index 948331b5d..8c9e976df 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py +++ b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -33,7 +32,6 @@ def test_users_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -70,7 +68,6 @@ def test_users_foo_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -107,7 +104,6 @@ def test_users_me_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -156,7 +152,6 @@ def test_items_with_no_token_jessica(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -206,7 +201,6 @@ def test_items_plumbus_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -250,7 +244,6 @@ def test_items_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -280,7 +273,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -317,7 +309,6 @@ def test_root_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -347,14 +338,12 @@ def test_put_no_header(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py index 2476b773f..0d55d73eb 100644 --- a/tests/test_tutorial/test_body/test_tutorial001.py +++ b/tests/test_tutorial/test_body/test_tutorial001.py @@ -3,7 +3,6 @@ from unittest.mock import patch import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture @@ -74,7 +73,6 @@ def test_post_with_only_name(client: TestClient): "loc": ["body", "price"], "msg": "Field required", "input": {"name": "Foo"}, - "url": match_pydantic_error_url("missing"), } ] } @@ -103,7 +101,6 @@ def test_post_with_only_name_price(client: TestClient): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "twenty", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -132,14 +129,12 @@ def test_post_with_no_data(client: TestClient): "loc": ["body", "name"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, ] } @@ -173,7 +168,6 @@ def test_post_with_none(client: TestClient): "loc": ["body"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -244,7 +238,6 @@ def test_post_form_for_json(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": "name=Foo&price=50.5", - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -308,9 +301,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url( - "model_attributes_type" - ), # "https://errors.pydantic.dev/0.38.0/v/dict_attributes_type", } ] } @@ -339,7 +329,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -367,7 +356,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } diff --git a/tests/test_tutorial/test_body/test_tutorial001_py310.py b/tests/test_tutorial/test_body/test_tutorial001_py310.py index b64d86005..4b9c12806 100644 --- a/tests/test_tutorial/test_body/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body/test_tutorial001_py310.py @@ -3,7 +3,6 @@ from unittest.mock import patch import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -81,7 +80,6 @@ def test_post_with_only_name(client: TestClient): "loc": ["body", "price"], "msg": "Field required", "input": {"name": "Foo"}, - "url": match_pydantic_error_url("missing"), } ] } @@ -111,7 +109,6 @@ def test_post_with_only_name_price(client: TestClient): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "twenty", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -141,14 +138,12 @@ def test_post_with_no_data(client: TestClient): "loc": ["body", "name"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, ] } @@ -183,7 +178,6 @@ def test_post_with_none(client: TestClient): "loc": ["body"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -256,7 +250,6 @@ def test_post_form_for_json(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": "name=Foo&price=50.5", - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -324,7 +317,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -353,7 +345,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -381,7 +372,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py index 1ff2d9576..fd6139eb9 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -57,7 +56,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py index 907d6842a..72c18c1f7 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -57,7 +56,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py index 431d2d181..1bc62868f 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py index 8cef6c154..3c5557a1b 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py index b48cd9ec2..8c1386aa6 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py index e5dc13b26..6275ebe95 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -50,7 +49,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py index 51e8e3a4e..5cd3e2c4a 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -50,7 +49,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py index 8ac1f7261..0173ab21b 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py index 7ada42c52..cda19918a 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py index 0a832eaf6..663291933 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py index 2046579a9..c26f8b89b 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -46,21 +45,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -99,21 +95,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py index 1282483e0..62c7e2fad 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -46,21 +45,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -99,21 +95,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py index 577c079d0..f46430fb5 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py index 0ec04151c..29071cddc 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py index 9caf5fe6c..133afe9b5 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py index f4a76be44..762073aea 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -31,7 +30,6 @@ def test_post_invalid_body(client: TestClient): "loc": ["body", "foo", "[key]"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py index 8ab9bcac8..24623cecc 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -35,7 +34,6 @@ def test_post_invalid_body(client: TestClient): "loc": ["body", "foo", "[key]"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py index ad142ec88..6f7355aaa 100644 --- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py +++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.custom_request_and_route.tutorial002 import app @@ -23,7 +22,6 @@ def test_exception_handler_body_access(): "loc": ["body"], "msg": "Input should be a valid list", "input": {"numbers": [1, 2, 3]}, - "url": match_pydantic_error_url("list_type"), } ], "body": '{"numbers": [1, 2, 3]}', diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial001.py b/tests/test_tutorial/test_dataclasses/test_tutorial001.py index 9f1200f37..762654d29 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial001.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial001.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dataclasses.tutorial001 import app @@ -29,7 +28,6 @@ def test_post_invalid_item(): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "invalid price", - "url": match_pydantic_error_url("float_parsing"), } ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py index 704e389a5..5f14d9a3b 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial006 import app @@ -18,14 +17,12 @@ def test_get_no_headers(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py index 5034fceba..a307ff808 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial006_an import app @@ -18,14 +17,12 @@ def test_get_no_headers(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py index 3fc22dd3c..b41b1537e 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -26,14 +25,12 @@ def test_get_no_headers(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py index 753e62e43..6b53c83bb 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial012 import app @@ -18,14 +17,12 @@ def test_get_no_headers_items(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -59,14 +56,12 @@ def test_get_no_headers_users(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py index 4157d4612..75adb69fc 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial012_an import app @@ -18,14 +17,12 @@ def test_get_no_headers_items(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -59,14 +56,12 @@ def test_get_no_headers_users(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py index 9e46758cb..e0a3d1ec2 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -26,14 +25,12 @@ def test_get_no_headers_items(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -68,14 +65,12 @@ def test_get_no_headers_users(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py index 494c317ca..581b2e4c7 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial005 import app @@ -18,7 +17,6 @@ def test_post_validation_error(): "loc": ["body", "size"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "XL", - "url": match_pydantic_error_url("int_parsing"), } ], "body": {"title": "towel", "size": "XL"}, diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py index cc2b496a8..7d2f553aa 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial006 import app @@ -18,7 +17,6 @@ def test_get_validation_error(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py index 2d2802269..8240b60a6 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py @@ -1,6 +1,5 @@ import pytest from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_pydanticv2 @@ -64,7 +63,6 @@ def test_post_invalid(client: TestClient): "loc": ["tags", 3], "msg": "Input should be a valid string", "input": {"sneaky": "object"}, - "url": match_pydantic_error_url("string_type"), } ] } diff --git a/tests/test_tutorial/test_query_params/test_tutorial005.py b/tests/test_tutorial/test_query_params/test_tutorial005.py index 921586357..05ae85b45 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial005.py +++ b/tests/test_tutorial/test_query_params/test_tutorial005.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.query_params.tutorial005 import app @@ -24,7 +23,6 @@ def test_foo_no_needy(): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py index e07803d6c..dbd63da16 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -34,21 +33,18 @@ def test_foo_no_needy(client: TestClient): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "int_parsing", "loc": ["query", "skip"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "limit"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "b", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py index 6c4c0b4dc..5055e3805 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -38,21 +37,18 @@ def test_foo_no_needy(client: TestClient): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "int_parsing", "loc": ["query", "skip"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "limit"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "b", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py index 287c2e8f8..945cee3d2 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -45,7 +44,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py index 5b0515070..23951a9aa 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -45,7 +44,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py index d22b1ce20..2968af563 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py index 3e7d5d3ad..534ba8759 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py index 1c3a09d39..886bceca2 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py index 91cc2b636..f5817593b 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial001 import app @@ -29,7 +28,6 @@ def test_post_form_no_body(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -58,7 +56,6 @@ def test_post_body_json(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_an.py index 3021eb3c3..1c78e3679 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial001_an import app @@ -18,7 +17,6 @@ def test_post_form_no_body(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -47,7 +45,6 @@ def test_post_body_json(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py index 04f3a4693..843fcec28 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -26,7 +25,6 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -56,7 +54,6 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py index ed9680b62..db1552e5c 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial002 import app @@ -18,7 +17,6 @@ def test_post_form_no_body(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -47,7 +45,6 @@ def test_post_body_json(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an.py b/tests/test_tutorial/test_request_files/test_tutorial002_an.py index ea8c1216c..b16da1669 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial002_an import app @@ -18,7 +17,6 @@ def test_post_form_no_body(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -47,7 +45,6 @@ def test_post_body_json(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py index 6d5877836..e092a516d 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -32,7 +31,6 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -62,7 +60,6 @@ def test_post_body_json(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py index 2d0445421..341a9ac8e 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -43,7 +42,6 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -73,7 +71,6 @@ def test_post_body_json(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001.py b/tests/test_tutorial/test_request_forms/test_tutorial001.py index 805daeb10..cbef9d30f 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_post_body_form_no_password(client: TestClient): "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -58,7 +56,6 @@ def test_post_body_form_no_username(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -87,14 +84,12 @@ def test_post_body_form_no_data(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,14 +123,12 @@ def test_post_body_json(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py index c43a0b695..88b8452bc 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_post_body_form_no_password(client: TestClient): "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -58,7 +56,6 @@ def test_post_body_form_no_username(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -87,14 +84,12 @@ def test_post_body_form_no_data(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,14 +123,12 @@ def test_post_body_json(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py index 078b812aa..3229897c9 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -33,7 +32,6 @@ def test_post_body_form_no_password(client: TestClient): "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -63,7 +61,6 @@ def test_post_body_form_no_username(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -93,14 +90,12 @@ def test_post_body_form_no_data(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -135,14 +130,12 @@ def test_post_body_json(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py index cac58639f..1e1ad2a87 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="app") @@ -29,21 +28,18 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -82,14 +78,12 @@ def test_post_form_no_file(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -123,21 +117,18 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -181,14 +172,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI): "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py index 009568048..5daf4dbf4 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="app") @@ -29,21 +28,18 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -82,14 +78,12 @@ def test_post_form_no_file(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -123,21 +117,18 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -181,14 +172,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI): "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py index 3d007e90b..3f1204efa 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -32,21 +31,18 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -86,14 +82,12 @@ def test_post_form_no_file(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,21 +122,18 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -187,14 +178,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI): "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } From 3cc5efc5dee2bf31364d5820581f972197f94a83 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Apr 2024 19:41:22 +0000 Subject: [PATCH 395/846] =?UTF-8?q?=F0=9F=93=9D=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 5ae22dde3..836793d3b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ✨ Add support for Pydantic's 2.7 new deprecated Field parameter, remove URL from validation errors response. PR [#11461](https://github.com/tiangolo/fastapi/pull/11461) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Fix typo in `docs/es/docs/async.md`. PR [#11400](https://github.com/tiangolo/fastapi/pull/11400) by [@fabianfalon](https://github.com/fabianfalon). From ebc8ac72959bc76d05e3fd15c97d2ca7c3104234 Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Thu, 18 Apr 2024 21:53:19 +0200 Subject: [PATCH 396/846] =?UTF-8?q?=F0=9F=93=9D=20Tweak=20docs=20and=20tra?= =?UTF-8?q?nslations=20links,=20typos,=20format=20(#11389)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/az/docs/fastapi-people.md | 2 +- docs/em/docs/advanced/behind-a-proxy.md | 2 +- docs/em/docs/advanced/events.md | 2 +- .../path-operation-advanced-configuration.md | 4 +- docs/em/docs/advanced/sub-applications.md | 2 +- docs/em/docs/advanced/wsgi.md | 2 +- docs/em/docs/async.md | 8 +-- docs/em/docs/deployment/concepts.md | 8 +-- docs/em/docs/deployment/docker.md | 20 ++++---- docs/em/docs/deployment/server-workers.md | 6 +-- docs/em/docs/fastapi-people.md | 21 +++++--- docs/em/docs/features.md | 5 ++ docs/em/docs/help-fastapi.md | 12 ++--- .../docs/how-to/custom-request-and-route.md | 4 +- docs/em/docs/how-to/sql-databases-peewee.md | 2 +- docs/em/docs/index.md | 11 +++- docs/em/docs/python-types.md | 2 +- docs/em/docs/tutorial/bigger-applications.md | 2 +- docs/em/docs/tutorial/body-updates.md | 2 +- docs/em/docs/tutorial/body.md | 2 +- .../dependencies/dependencies-with-yield.md | 6 +-- docs/em/docs/tutorial/extra-models.md | 2 +- docs/em/docs/tutorial/first-steps.md | 2 +- docs/em/docs/tutorial/metadata.md | 2 +- docs/em/docs/tutorial/query-params.md | 2 +- .../docs/tutorial/security/simple-oauth2.md | 2 +- docs/em/docs/tutorial/sql-databases.md | 4 +- docs/em/docs/tutorial/testing.md | 2 +- docs/en/docs/advanced/behind-a-proxy.md | 2 +- docs/en/docs/advanced/custom-response.md | 4 +- docs/en/docs/advanced/dataclasses.md | 2 +- docs/en/docs/advanced/events.md | 2 +- docs/en/docs/advanced/generate-clients.md | 4 +- docs/en/docs/advanced/openapi-callbacks.md | 4 +- .../path-operation-advanced-configuration.md | 4 +- docs/en/docs/advanced/settings.md | 2 +- docs/en/docs/advanced/sub-applications.md | 2 +- docs/en/docs/advanced/wsgi.md | 2 +- docs/en/docs/alternatives.md | 6 +-- docs/en/docs/async.md | 6 +-- docs/en/docs/benchmarks.md | 2 +- docs/en/docs/deployment/concepts.md | 14 +++--- docs/en/docs/deployment/docker.md | 6 +-- docs/en/docs/deployment/server-workers.md | 6 +-- docs/en/docs/help-fastapi.md | 8 +-- .../docs/how-to/async-sql-encode-databases.md | 4 +- docs/en/docs/how-to/configure-swagger-ui.md | 2 +- docs/en/docs/python-types.md | 2 +- docs/en/docs/reference/apirouter.md | 3 +- docs/en/docs/reference/background.md | 4 +- docs/en/docs/reference/dependencies.md | 9 ++-- docs/en/docs/reference/exceptions.md | 4 +- docs/en/docs/reference/fastapi.md | 3 +- docs/en/docs/reference/httpconnection.md | 4 +- docs/en/docs/reference/middleware.md | 3 +- docs/en/docs/reference/parameters.md | 3 +- docs/en/docs/reference/request.md | 8 +-- docs/en/docs/reference/response.md | 6 +-- docs/en/docs/reference/responses.md | 6 +-- docs/en/docs/reference/security/index.md | 7 +-- docs/en/docs/reference/staticfiles.md | 3 +- docs/en/docs/reference/status.md | 7 +-- docs/en/docs/reference/templating.md | 3 +- docs/en/docs/reference/testclient.md | 3 +- docs/en/docs/reference/uploadfile.md | 3 +- docs/en/docs/reference/websockets.md | 10 ++-- docs/en/docs/tutorial/bigger-applications.md | 6 +-- docs/en/docs/tutorial/body-updates.md | 2 +- .../dependencies/classes-as-dependencies.md | 26 +++++----- docs/en/docs/tutorial/dependencies/index.md | 2 +- docs/en/docs/tutorial/extra-models.md | 2 +- docs/en/docs/tutorial/response-model.md | 2 +- docs/en/docs/tutorial/schema-extra-example.md | 2 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 2 +- .../docs/tutorial/security/simple-oauth2.md | 4 +- docs/en/docs/tutorial/sql-databases.md | 2 +- docs/en/docs/tutorial/testing.md | 2 +- docs/es/docs/async.md | 2 +- docs/es/docs/index.md | 9 ++++ docs/es/docs/tutorial/first-steps.md | 2 +- docs/es/docs/tutorial/index.md | 2 +- docs/es/docs/tutorial/query-params.md | 2 +- docs/fa/docs/advanced/sub-applications.md | 2 +- docs/fa/docs/index.md | 11 +++- docs/fr/docs/advanced/additional-responses.md | 14 +++--- .../docs/advanced/additional-status-codes.md | 2 +- docs/fr/docs/advanced/index.md | 2 +- .../path-operation-advanced-configuration.md | 14 +++--- docs/fr/docs/advanced/response-directly.md | 2 +- docs/fr/docs/fastapi-people.md | 21 +++++--- docs/fr/docs/features.md | 5 ++ docs/fr/docs/index.md | 9 ++++ docs/fr/docs/tutorial/path-params.md | 6 +-- docs/he/docs/index.md | 11 +++- docs/id/docs/tutorial/index.md | 2 +- docs/ja/docs/async.md | 4 +- docs/ja/docs/deployment/concepts.md | 8 +-- docs/ja/docs/deployment/docker.md | 8 +-- docs/ja/docs/deployment/server-workers.md | 6 +-- docs/ja/docs/fastapi-people.md | 17 ++++--- docs/ja/docs/features.md | 5 ++ docs/ja/docs/index.md | 11 +++- docs/ja/docs/tutorial/body-updates.md | 2 +- docs/ja/docs/tutorial/body.md | 2 +- .../dependencies/dependencies-with-yield.md | 6 +-- docs/ja/docs/tutorial/first-steps.md | 2 +- docs/ja/docs/tutorial/query-params.md | 2 +- docs/ja/docs/tutorial/security/first-steps.md | 2 +- docs/ko/docs/async.md | 8 +-- docs/ko/docs/deployment/docker.md | 8 +-- docs/ko/docs/deployment/server-workers.md | 8 +-- docs/ko/docs/features.md | 2 +- docs/ko/docs/index.md | 11 +++- docs/ko/docs/tutorial/body-fields.md | 2 +- docs/ko/docs/tutorial/body.md | 8 +-- docs/ko/docs/tutorial/dependencies/index.md | 4 +- docs/ko/docs/tutorial/first-steps.md | 2 +- docs/ko/docs/tutorial/query-params.md | 2 +- .../tutorial/security/get-current-user.md | 4 +- docs/pl/docs/features.md | 5 ++ docs/pl/docs/help-fastapi.md | 12 ++--- docs/pl/docs/index.md | 9 ++++ docs/pl/docs/tutorial/first-steps.md | 2 +- docs/pt/docs/advanced/events.md | 2 +- docs/pt/docs/async.md | 2 +- docs/pt/docs/deployment/docker.md | 16 +++--- docs/pt/docs/fastapi-people.md | 21 +++++--- docs/pt/docs/features.md | 5 ++ docs/pt/docs/help-fastapi.md | 10 ++-- docs/pt/docs/index.md | 9 ++++ docs/pt/docs/tutorial/body-multiple-params.md | 4 +- docs/pt/docs/tutorial/body-nested-models.md | 6 +-- docs/pt/docs/tutorial/body.md | 2 +- docs/pt/docs/tutorial/encoder.md | 2 +- docs/pt/docs/tutorial/first-steps.md | 6 +-- docs/pt/docs/tutorial/index.md | 2 +- docs/pt/docs/tutorial/path-params.md | 16 +++--- docs/pt/docs/tutorial/query-params.md | 2 +- docs/pt/docs/tutorial/security/first-steps.md | 14 +++--- docs/ru/docs/async.md | 4 +- docs/ru/docs/deployment/concepts.md | 8 +-- docs/ru/docs/deployment/docker.md | 12 ++--- docs/ru/docs/deployment/versions.md | 4 +- docs/ru/docs/fastapi-people.md | 20 +++++--- docs/ru/docs/features.md | 7 ++- docs/ru/docs/help-fastapi.md | 16 +++--- docs/ru/docs/index.md | 9 ++++ docs/ru/docs/tutorial/body-multiple-params.md | 22 ++++---- docs/ru/docs/tutorial/body.md | 2 +- docs/ru/docs/tutorial/debugging.md | 2 +- docs/ru/docs/tutorial/dependencies/index.md | 4 +- docs/ru/docs/tutorial/first-steps.md | 2 +- docs/ru/docs/tutorial/metadata.md | 2 +- .../path-params-numeric-validations.md | 2 +- docs/ru/docs/tutorial/query-params.md | 6 +-- docs/ru/docs/tutorial/static-files.md | 2 +- docs/ru/docs/tutorial/testing.md | 2 +- docs/tr/docs/async.md | 4 +- docs/tr/docs/features.md | 5 ++ docs/tr/docs/index.md | 9 ++++ docs/tr/docs/python-types.md | 4 +- docs/tr/docs/tutorial/query-params.md | 2 +- docs/uk/docs/alternatives.md | 50 +++++++++---------- docs/uk/docs/fastapi-people.md | 11 ++-- docs/uk/docs/python-types.md | 2 +- docs/uk/docs/tutorial/encoder.md | 2 +- docs/vi/docs/features.md | 5 ++ docs/vi/docs/index.md | 11 +++- docs/vi/docs/python-types.md | 2 +- docs/yo/docs/index.md | 11 +++- docs/zh/docs/advanced/behind-a-proxy.md | 2 +- docs/zh/docs/advanced/events.md | 2 +- docs/zh/docs/advanced/response-headers.md | 2 +- docs/zh/docs/advanced/sub-applications.md | 2 +- docs/zh/docs/advanced/wsgi.md | 2 +- docs/zh/docs/async.md | 6 +-- docs/zh/docs/deployment/concepts.md | 8 +-- docs/zh/docs/deployment/docker.md | 10 ++-- docs/zh/docs/deployment/server-workers.md | 6 +-- docs/zh/docs/fastapi-people.md | 21 +++++--- docs/zh/docs/features.md | 5 ++ docs/zh/docs/help-fastapi.md | 8 +-- docs/zh/docs/index.md | 9 ++++ docs/zh/docs/tutorial/bigger-applications.md | 2 +- docs/zh/docs/tutorial/body-updates.md | 2 +- docs/zh/docs/tutorial/body.md | 2 +- .../dependencies/dependencies-with-yield.md | 6 +-- docs/zh/docs/tutorial/metadata.md | 4 +- docs/zh/docs/tutorial/query-params.md | 3 +- .../docs/tutorial/security/simple-oauth2.md | 2 +- docs/zh/docs/tutorial/testing.md | 14 +++--- 191 files changed, 648 insertions(+), 479 deletions(-) diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md index 2ca8e109e..60494f191 100644 --- a/docs/az/docs/fastapi-people.md +++ b/docs/az/docs/fastapi-people.md @@ -119,7 +119,7 @@ Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun Bunlar **Sponsorlar**dır. 😎 -Onlar mənim **FastAPI** (və digər) işlərimi əsasən <a href="hhttps://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsorlar</a> vasitəsilə dəstəkləyirlər. +Onlar mənim **FastAPI** (və digər) işlərimi əsasən <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsorlar</a> vasitəsilə dəstəkləyirlər. {% if sponsors %} diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index 12afe638c..e3fd26735 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -341,6 +341,6 @@ $ uvicorn main:app --root-path /api/v1 ## 🗜 🎧-🈸 -🚥 👆 💪 🗻 🎧-🈸 (🔬 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}) ⏪ ⚙️ 🗳 ⏮️ `root_path`, 👆 💪 ⚫️ 🛎, 👆 🔜 ⌛. +🚥 👆 💪 🗻 🎧-🈸 (🔬 [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}) ⏪ ⚙️ 🗳 ⏮️ `root_path`, 👆 💪 ⚫️ 🛎, 👆 🔜 ⌛. FastAPI 🔜 🔘 ⚙️ `root_path` 🎆, ⚫️ 🔜 👷. 👶 diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 671e81b18..19421ff58 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -157,4 +157,4 @@ async with lifespan(app): ## 🎧 🈸 -👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}. +👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index ec7231870..3dc5ac536 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -59,7 +59,7 @@ 👆 💪 📣 🌖 📨 ⏮️ 👫 🏷, 👔 📟, ♒️. -📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}. +📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. ## 🗄 ➕ @@ -77,7 +77,7 @@ !!! tip 👉 🔅 🎚 ↔ ☝. - 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}. + 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. 👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`. diff --git a/docs/em/docs/advanced/sub-applications.md b/docs/em/docs/advanced/sub-applications.md index e0391453b..1e0931f95 100644 --- a/docs/em/docs/advanced/sub-applications.md +++ b/docs/em/docs/advanced/sub-applications.md @@ -70,4 +70,4 @@ $ uvicorn main:app --reload & 🎧-🈸 💪 ✔️ 🚮 👍 📌 🎧-🈸 & 🌐 🔜 👷 ☑, ↩️ FastAPI 🍵 🌐 👉 `root_path`Ⓜ 🔁. -👆 🔜 💡 🌅 🔃 `root_path` & ❔ ⚙️ ⚫️ 🎯 📄 🔃 [⛅ 🗳](./behind-a-proxy.md){.internal-link target=_blank}. +👆 🔜 💡 🌅 🔃 `root_path` & ❔ ⚙️ ⚫️ 🎯 📄 🔃 [⛅ 🗳](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md index 4d051807f..6a4ed073c 100644 --- a/docs/em/docs/advanced/wsgi.md +++ b/docs/em/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # ✅ 🇨🇻 - 🏺, ✳, 🎏 -👆 💪 🗻 🇨🇻 🈸 👆 👀 ⏮️ [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}, [⛅ 🗳](./behind-a-proxy.md){.internal-link target=_blank}. +👆 💪 🗻 🇨🇻 🈸 👆 👀 ⏮️ [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}, [⛅ 🗳](behind-a-proxy.md){.internal-link target=_blank}. 👈, 👆 💪 ⚙️ `WSGIMiddleware` & ⚙️ ⚫️ 🎁 👆 🇨🇻 🈸, 🖼, 🏺, ✳, ♒️. diff --git a/docs/em/docs/async.md b/docs/em/docs/async.md index bed31c3e7..0db497f40 100644 --- a/docs/em/docs/async.md +++ b/docs/em/docs/async.md @@ -405,15 +405,15 @@ async def read_burgers(): 🚥 👆 👟 ⚪️➡️ ➕1️⃣ 🔁 🛠️ 👈 🔨 🚫 👷 🌌 🔬 🔛 & 👆 ⚙️ ⚖ 🙃 📊-🕴 *➡ 🛠️ 🔢* ⏮️ ✅ `def` 🤪 🎭 📈 (🔃 1️⃣0️⃣0️⃣ 💓), 🙏 🗒 👈 **FastAPI** ⭐ 🔜 🔄. 👫 💼, ⚫️ 👻 ⚙️ `async def` 🚥 👆 *➡ 🛠️ 🔢* ⚙️ 📟 👈 🎭 🚧 <abbr title="Input/Output: disk reading or writing, network communications.">👤/🅾</abbr>. -, 👯♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](index.md#performance){.internal-link target=_blank} 🌘 (⚖️ 🌘 ⭐) 👆 ⏮️ 🛠️. +, 👯♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](index.md#_15){.internal-link target=_blank} 🌘 (⚖️ 🌘 ⭐) 👆 ⏮️ 🛠️. ### 🔗 -🎏 ✔ [🔗](./tutorial/dependencies/index.md){.internal-link target=_blank}. 🚥 🔗 🐩 `def` 🔢 ↩️ `async def`, ⚫️ 🏃 🔢 🧵. +🎏 ✔ [🔗](tutorial/dependencies/index.md){.internal-link target=_blank}. 🚥 🔗 🐩 `def` 🔢 ↩️ `async def`, ⚫️ 🏃 🔢 🧵. ### 🎧-🔗 -👆 💪 ✔️ 💗 🔗 & [🎧-🔗](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} 🚫 🔠 🎏 (🔢 🔢 🔑), 👫 💪 ✍ ⏮️ `async def` & ⏮️ 😐 `def`. ⚫️ 🔜 👷, & 🕐 ✍ ⏮️ 😐 `def` 🔜 🤙 🔛 🔢 🧵 (⚪️➡️ 🧵) ↩️ ➖ "⌛". +👆 💪 ✔️ 💗 🔗 & [🎧-🔗](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} 🚫 🔠 🎏 (🔢 🔢 🔑), 👫 💪 ✍ ⏮️ `async def` & ⏮️ 😐 `def`. ⚫️ 🔜 👷, & 🕐 ✍ ⏮️ 😐 `def` 🔜 🤙 🔛 🔢 🧵 (⚪️➡️ 🧵) ↩️ ➖ "⌛". ### 🎏 🚙 🔢 @@ -427,4 +427,4 @@ async def read_burgers(): 🔄, 👉 📶 📡 ℹ 👈 🔜 🎲 ⚠ 🚥 👆 👟 🔎 👫. -⏪, 👆 🔜 👍 ⏮️ 📄 ⚪️➡️ 📄 🔛: <a href="#in-a-hurry">🏃 ❓</a>. +⏪, 👆 🔜 👍 ⏮️ 📄 ⚪️➡️ 📄 🔛: <a href="#_2">🏃 ❓</a>. diff --git a/docs/em/docs/deployment/concepts.md b/docs/em/docs/deployment/concepts.md index 162b68615..b0f86cb5e 100644 --- a/docs/em/docs/deployment/concepts.md +++ b/docs/em/docs/deployment/concepts.md @@ -25,7 +25,7 @@ ## 💂♂ - 🇺🇸🔍 -[⏮️ 📃 🔃 🇺🇸🔍](./https.md){.internal-link target=_blank} 👥 🇭🇲 🔃 ❔ 🇺🇸🔍 🚚 🔐 👆 🛠️. +[⏮️ 📃 🔃 🇺🇸🔍](https.md){.internal-link target=_blank} 👥 🇭🇲 🔃 ❔ 🇺🇸🔍 🚚 🔐 👆 🛠️. 👥 👀 👈 🇺🇸🔍 🛎 🚚 🦲 **🔢** 👆 🈸 💽, **🤝 ❎ 🗳**. @@ -187,7 +187,7 @@ ### 👨🏭 🛠️ & ⛴ -💭 ⚪️➡️ 🩺 [🔃 🇺🇸🔍](./https.md){.internal-link target=_blank} 👈 🕴 1️⃣ 🛠️ 💪 👂 🔛 1️⃣ 🌀 ⛴ & 📢 📢 💽 ❓ +💭 ⚪️➡️ 🩺 [🔃 🇺🇸🔍](https.md){.internal-link target=_blank} 👈 🕴 1️⃣ 🛠️ 💪 👂 🔛 1️⃣ 🌀 ⛴ & 📢 📢 💽 ❓ 👉 ☑. @@ -241,7 +241,7 @@ !!! tip 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. - 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. + 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. ## ⏮️ 🔁 ⏭ ▶️ @@ -273,7 +273,7 @@ * 👆 🔜 💪 🌌 ▶️/⏏ *👈* 🎉 ✍, 🔍 ❌, ♒️. !!! tip - 👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. + 👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. ## ℹ 🛠️ diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md index f28735ed7..091eb3bab 100644 --- a/docs/em/docs/deployment/docker.md +++ b/docs/em/docs/deployment/docker.md @@ -5,7 +5,7 @@ ⚙️ 💾 📦 ✔️ 📚 📈 ✅ **💂♂**, **🔬**, **🦁**, & 🎏. !!! tip - 🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#build-a-docker-image-for-fastapi). + 🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi). <details> <summary>📁 🎮 👶</summary> @@ -108,7 +108,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 🌅 ⚠ 🌌 ⚫️ ✔️ 📁 `requirements.txt` ⏮️ 📦 📛 & 👫 ⏬, 1️⃣ 📍 ⏸. -👆 🔜 ↗️ ⚙️ 🎏 💭 👆 ✍ [🔃 FastAPI ⏬](./versions.md){.internal-link target=_blank} ⚒ ↔ ⏬. +👆 🔜 ↗️ ⚙️ 🎏 💭 👆 ✍ [🔃 FastAPI ⏬](versions.md){.internal-link target=_blank} ⚒ ↔ ⏬. 🖼, 👆 `requirements.txt` 💪 👀 💖: @@ -373,7 +373,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 🛠️ 🔧 -➡️ 💬 🔄 🔃 🎏 [🛠️ 🔧](./concepts.md){.internal-link target=_blank} ⚖ 📦. +➡️ 💬 🔄 🔃 🎏 [🛠️ 🔧](concepts.md){.internal-link target=_blank} ⚖ 📦. 📦 ✴️ 🧰 📉 🛠️ **🏗 & 🛠️** 🈸, ✋️ 👫 🚫 🛠️ 🎯 🎯 🍵 👉 **🛠️ 🔧**, & 📤 📚 💪 🎛. @@ -415,7 +415,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 1️⃣ 📚 📎 📦 🧾 ⚙️ 💖 Kubernetes 🛎 ✔️ 🛠️ 🌌 🚚 **🧬 📦** ⏪ 🔗 **📐 ⚖** 📨 📨. 🌐 **🌑 🎚**. -📚 💼, 👆 🔜 🎲 💚 🏗 **☁ 🖼 ⚪️➡️ 🖌** [🔬 🔛](#dockerfile), ❎ 👆 🔗, & 🏃♂ **👁 Uvicorn 🛠️** ↩️ 🏃♂ 🕳 💖 🐁 ⏮️ Uvicorn 👨🏭. +📚 💼, 👆 🔜 🎲 💚 🏗 **☁ 🖼 ⚪️➡️ 🖌** [🔬 🔛](#_6), ❎ 👆 🔗, & 🏃♂ **👁 Uvicorn 🛠️** ↩️ 🏃♂ 🕳 💖 🐁 ⏮️ Uvicorn 👨🏭. ### 📐 ⚙ @@ -450,7 +450,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ↗️, 📤 **🎁 💼** 🌐❔ 👆 💪 💚 ✔️ **📦** ⏮️ **🐁 🛠️ 👨💼** ▶️ 📚 **Uvicorn 👨🏭 🛠️** 🔘. -📚 💼, 👆 💪 ⚙️ **🛂 ☁ 🖼** 👈 🔌 **🐁** 🛠️ 👨💼 🏃♂ 💗 **Uvicorn 👨🏭 🛠️**, & 🔢 ⚒ 🔆 🔢 👨🏭 ⚓️ 🔛 ⏮️ 💽 🐚 🔁. 👤 🔜 💬 👆 🌅 🔃 ⚫️ 🔛 [🛂 ☁ 🖼 ⏮️ 🐁 - Uvicorn](#official-docker-image-with-gunicorn-uvicorn). +📚 💼, 👆 💪 ⚙️ **🛂 ☁ 🖼** 👈 🔌 **🐁** 🛠️ 👨💼 🏃♂ 💗 **Uvicorn 👨🏭 🛠️**, & 🔢 ⚒ 🔆 🔢 👨🏭 ⚓️ 🔛 ⏮️ 💽 🐚 🔁. 👤 🔜 💬 👆 🌅 🔃 ⚫️ 🔛 [🛂 ☁ 🖼 ⏮️ 🐁 - Uvicorn](#-uvicorn). 📥 🖼 🕐❔ 👈 💪 ⚒ 🔑: @@ -514,14 +514,14 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 🛂 ☁ 🖼 ⏮️ 🐁 - Uvicorn -📤 🛂 ☁ 🖼 👈 🔌 🐁 🏃♂ ⏮️ Uvicorn 👨🏭, ℹ ⏮️ 📃: [💽 👨🏭 - 🐁 ⏮️ Uvicorn](./server-workers.md){.internal-link target=_blank}. +📤 🛂 ☁ 🖼 👈 🔌 🐁 🏃♂ ⏮️ Uvicorn 👨🏭, ℹ ⏮️ 📃: [💽 👨🏭 - 🐁 ⏮️ Uvicorn](server-workers.md){.internal-link target=_blank}. -👉 🖼 🔜 ⚠ ✴️ ⚠ 🔬 🔛: [📦 ⏮️ 💗 🛠️ & 🎁 💼](#containers-with-multiple-processes-and-special-cases). +👉 🖼 🔜 ⚠ ✴️ ⚠ 🔬 🔛: [📦 ⏮️ 💗 🛠️ & 🎁 💼](#_18). * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-🐁-fastapi</a>. !!! warning - 📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#build-a-docker-image-for-fastapi). + 📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi). 👉 🖼 ✔️ **🚘-📳** 🛠️ 🔌 ⚒ **🔢 👨🏭 🛠️** ⚓️ 🔛 💽 🐚 💪. @@ -574,9 +574,9 @@ COPY ./app /app/app ### 🕐❔ ⚙️ -👆 🔜 🎲 **🚫** ⚙️ 👉 🛂 🧢 🖼 (⚖️ 🙆 🎏 🎏 1️⃣) 🚥 👆 ⚙️ **Kubernetes** (⚖️ 🎏) & 👆 ⏪ ⚒ **🧬** 🌑 🎚, ⏮️ 💗 **📦**. 📚 💼, 👆 👍 📆 **🏗 🖼 ⚪️➡️ 🖌** 🔬 🔛: [🏗 ☁ 🖼 FastAPI](#build-a-docker-image-for-fastapi). +👆 🔜 🎲 **🚫** ⚙️ 👉 🛂 🧢 🖼 (⚖️ 🙆 🎏 🎏 1️⃣) 🚥 👆 ⚙️ **Kubernetes** (⚖️ 🎏) & 👆 ⏪ ⚒ **🧬** 🌑 🎚, ⏮️ 💗 **📦**. 📚 💼, 👆 👍 📆 **🏗 🖼 ⚪️➡️ 🖌** 🔬 🔛: [🏗 ☁ 🖼 FastAPI](#fastapi). -👉 🖼 🔜 ⚠ ✴️ 🎁 💼 🔬 🔛 [📦 ⏮️ 💗 🛠️ & 🎁 💼](#containers-with-multiple-processes-and-special-cases). 🖼, 🚥 👆 🈸 **🙅 🥃** 👈 ⚒ 🔢 🔢 🛠️ ⚓️ 🔛 💽 👷 👍, 👆 🚫 💚 😥 ⏮️ ❎ 🛠️ 🧬 🌑 🎚, & 👆 🚫 🏃 🌅 🌘 1️⃣ 📦 ⏮️ 👆 📱. ⚖️ 🚥 👆 🛠️ ⏮️ **☁ ✍**, 🏃 🔛 👁 💽, ♒️. +👉 🖼 🔜 ⚠ ✴️ 🎁 💼 🔬 🔛 [📦 ⏮️ 💗 🛠️ & 🎁 💼](#_18). 🖼, 🚥 👆 🈸 **🙅 🥃** 👈 ⚒ 🔢 🔢 🛠️ ⚓️ 🔛 💽 👷 👍, 👆 🚫 💚 😥 ⏮️ ❎ 🛠️ 🧬 🌑 🎚, & 👆 🚫 🏃 🌅 🌘 1️⃣ 📦 ⏮️ 👆 📱. ⚖️ 🚥 👆 🛠️ ⏮️ **☁ ✍**, 🏃 🔛 👁 💽, ♒️. ## 🛠️ 📦 🖼 diff --git a/docs/em/docs/deployment/server-workers.md b/docs/em/docs/deployment/server-workers.md index b7e58c4f4..43998bc49 100644 --- a/docs/em/docs/deployment/server-workers.md +++ b/docs/em/docs/deployment/server-workers.md @@ -13,12 +13,12 @@ 🕐❔ 🛠️ 🈸 👆 🔜 🎲 💚 ✔️ **🧬 🛠️** ✊ 📈 **💗 🐚** & 💪 🍵 🌅 📨. -👆 👀 ⏮️ 📃 🔃 [🛠️ 🔧](./concepts.md){.internal-link target=_blank}, 📤 💗 🎛 👆 💪 ⚙️. +👆 👀 ⏮️ 📃 🔃 [🛠️ 🔧](concepts.md){.internal-link target=_blank}, 📤 💗 🎛 👆 💪 ⚙️. 📥 👤 🔜 🎦 👆 ❔ ⚙️ <a href="https://gunicorn.org/" class="external-link" target="_blank">**🐁**</a> ⏮️ **Uvicorn 👨🏭 🛠️**. !!! info - 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. + 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. 🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. @@ -163,7 +163,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 📦 & ☁ -⏭ 📃 🔃 [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank} 👤 🔜 💬 🎛 👆 💪 ⚙️ 🍵 🎏 **🛠️ 🔧**. +⏭ 📃 🔃 [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank} 👤 🔜 💬 🎛 👆 💪 ⚙️ 🍵 🎏 **🛠️ 🔧**. 👤 🔜 🎦 👆 **🛂 ☁ 🖼** 👈 🔌 **🐁 ⏮️ Uvicorn 👨🏭** & 🔢 📳 👈 💪 ⚠ 🙅 💼. diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md index ec1d4c47c..d3c7d2038 100644 --- a/docs/em/docs/fastapi-people.md +++ b/docs/em/docs/fastapi-people.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # FastAPI 👫👫 FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. @@ -18,7 +23,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. </div> {% endif %} -👤 👼 & 🐛 **FastAPI**. 👆 💪 ✍ 🌅 🔃 👈 [ℹ FastAPI - 🤚 ℹ - 🔗 ⏮️ 📕](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +👤 👼 & 🐛 **FastAPI**. 👆 💪 ✍ 🌅 🔃 👈 [ℹ FastAPI - 🤚 ℹ - 🔗 ⏮️ 📕](help-fastapi.md#_3){.internal-link target=_blank}. ...✋️ 📥 👤 💚 🎦 👆 👪. @@ -28,15 +33,15 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. 👫 👫👫 👈: -* [ℹ 🎏 ⏮️ ❔ 📂](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [✍ 🚲 📨](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* 📄 🚲 📨, [✴️ ⚠ ✍](contributing.md#translations){.internal-link target=_blank}. +* [ℹ 🎏 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank}. +* [✍ 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank}. +* 📄 🚲 📨, [✴️ ⚠ ✍](contributing.md#_9){.internal-link target=_blank}. 👏 👫. 👶 👶 ## 🌅 🦁 👩💻 🏁 🗓️ -👫 👩💻 👈 ✔️ [🤝 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ⏮️ 🏁 🗓️. 👶 +👫 👩💻 👈 ✔️ [🤝 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} ⏮️ 🏁 🗓️. 👶 {% if people %} <div class="user-list user-list-center"> @@ -52,7 +57,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. 📥 **FastAPI 🕴**. 👶 -👫 👩💻 👈 ✔️ [ℹ 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} 🔘 *🌐 🕰*. +👫 👩💻 👈 ✔️ [ℹ 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} 🔘 *🌐 🕰*. 👫 ✔️ 🎦 🕴 🤝 📚 🎏. 👶 @@ -70,7 +75,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. 📥 **🔝 👨🔬**. 👶 -👉 👩💻 ✔️ [✍ 🏆 🚲 📨](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} 👈 ✔️ *🔗*. +👉 👩💻 ✔️ [✍ 🏆 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank} 👈 ✔️ *🔗*. 👫 ✔️ 📉 ℹ 📟, 🧾, ✍, ♒️. 👶 @@ -92,7 +97,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. ### 📄 ✍ -👤 🕴 💬 👩❤👨 🇪🇸 (& 🚫 📶 👍 👶). , 👨🔬 🕐 👈 ✔️ [**🏋️ ✔ ✍**](contributing.md#translations){.internal-link target=_blank} 🧾. 🍵 👫, 📤 🚫🔜 🧾 📚 🎏 🇪🇸. +👤 🕴 💬 👩❤👨 🇪🇸 (& 🚫 📶 👍 👶). , 👨🔬 🕐 👈 ✔️ [**🏋️ ✔ ✍**](contributing.md#_9){.internal-link target=_blank} 🧾. 🍵 👫, 📤 🚫🔜 🧾 📚 🎏 🇪🇸. --- diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index 3693f4c54..6ef7c5ccc 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # ⚒ ## FastAPI ⚒ diff --git a/docs/em/docs/help-fastapi.md b/docs/em/docs/help-fastapi.md index da452abf4..fbb9ca9a9 100644 --- a/docs/em/docs/help-fastapi.md +++ b/docs/em/docs/help-fastapi.md @@ -78,7 +78,7 @@ 📚 💼 👆 5️⃣📆 ⏪ 💭 ❔ 📚 ❔. 👶 -🚥 👆 🤝 📚 👫👫 ⏮️ 👫 ❔, 👆 🔜 ▶️️ 🛂 [FastAPI 🕴](fastapi-people.md#experts){.internal-link target=_blank}. 👶 +🚥 👆 🤝 📚 👫👫 ⏮️ 👫 ❔, 👆 🔜 ▶️️ 🛂 [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. 👶 💭, 🏆 ⚠ ☝: 🔄 😇. 👫👫 👟 ⏮️ 👫 😩 & 📚 💼 🚫 💭 🏆 🌌, ✋️ 🔄 🏆 👆 💪 😇. 👶 @@ -198,7 +198,7 @@ * 🔧 🤭 👆 🔎 🔛 🧾. * 💰 📄, 📹, ⚖️ 📻 👆 ✍ ⚖️ 🔎 🔃 FastAPI <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">✍ 👉 📁</a>. * ⚒ 💭 👆 🚮 👆 🔗 ▶️ 🔗 📄. -* ℹ [💬 🧾](contributing.md#translations){.internal-link target=_blank} 👆 🇪🇸. +* ℹ [💬 🧾](contributing.md#_9){.internal-link target=_blank} 👆 🇪🇸. * 👆 💪 ℹ 📄 ✍ ✍ 🎏. * 🛠️ 🆕 🧾 📄. * 🔧 ♻ ❔/🐛. @@ -215,8 +215,8 @@ 👑 📋 👈 👆 💪 ▶️️ 🔜: -* [ℹ 🎏 ⏮️ ❔ 📂](#help-others-with-questions-in-github){.internal-link target=_blank} (👀 📄 🔛). -* [📄 🚲 📨](#review-pull-requests){.internal-link target=_blank} (👀 📄 🔛). +* [ℹ 🎏 ⏮️ ❔ 📂](#i){.internal-link target=_blank} (👀 📄 🔛). +* [📄 🚲 📨](#i){.internal-link target=_blank} (👀 📄 🔛). 👈 2️⃣ 📋 ⚫️❔ **🍴 🕰 🏆**. 👈 👑 👷 🏆 FastAPI. @@ -227,7 +227,7 @@ 🛑 👶 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">😧 💬 💽</a> 👶 & 🤙 👅 ⏮️ 🎏 FastAPI 👪. !!! tip - ❔, 💭 👫 <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#experts){.internal-link target=_blank}. + ❔, 💭 👫 <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. ⚙️ 💬 🕴 🎏 🏢 💬. @@ -237,7 +237,7 @@ 📂, 📄 🔜 🦮 👆 ✍ ▶️️ ❔ 👈 👆 💪 🌖 💪 🤚 👍 ❔, ⚖️ ❎ ⚠ 👆 ⏭ 💬. & 📂 👤 💪 ⚒ 💭 👤 🕧 ❔ 🌐, 🚥 ⚫️ ✊ 🕰. 👤 💪 🚫 🤙 👈 ⏮️ 💬 ⚙️. 👶 -💬 💬 ⚙️ 🚫 💪 📇 📂, ❔ & ❔ 5️⃣📆 🤚 💸 💬. & 🕴 🕐 📂 💯 ▶️️ [FastAPI 🕴](fastapi-people.md#experts){.internal-link target=_blank}, 👆 🔜 🌅 🎲 📨 🌅 🙋 📂. +💬 💬 ⚙️ 🚫 💪 📇 📂, ❔ & ❔ 5️⃣📆 🤚 💸 💬. & 🕴 🕐 📂 💯 ▶️️ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}, 👆 🔜 🌅 🎲 📨 🌅 🙋 📂. 🔛 🎏 🚄, 📤 💯 👩💻 💬 ⚙️, 📤 ↕ 🤞 👆 🔜 🔎 👱 💬 📤, 🌖 🌐 🕰. 👶 diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index d6fafa2ea..2d33d4feb 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -28,7 +28,7 @@ ### ✍ 🛃 `GzipRequest` 🎓 !!! tip - 👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}. + 👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. 🥇, 👥 ✍ `GzipRequest` 🎓, ❔ 🔜 📁 `Request.body()` 👩🔬 🗜 💪 🔍 ☑ 🎚. @@ -76,7 +76,7 @@ ## 🔐 📨 💪 ⚠ 🐕🦺 !!! tip - ❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + ❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}). ✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲. diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md index 62619fc2c..8d633d7f6 100644 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ b/docs/em/docs/how-to/sql-databases-peewee.md @@ -86,7 +86,7 @@ connect_args={"check_same_thread": False} !!! info "📡 ℹ" - ⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#note){.internal-link target=_blank} ✔. + ⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔. ### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState` diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index a0ccfafb8..cf4fa0def 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> @@ -31,7 +40,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ 🔑 ⚒: -* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#performance). +* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#_15). * **⏩ 📟**: 📈 🚅 🛠️ ⚒ 🔃 2️⃣0️⃣0️⃣ 💯 3️⃣0️⃣0️⃣ 💯. * * **👩❤👨 🐛**: 📉 🔃 4️⃣0️⃣ 💯 🗿 (👩💻) 📉 ❌. * * **🏋️**: 👑 👨🎨 🐕🦺. <abbr title="also known as auto-complete, autocompletion, IntelliSense">🛠️</abbr> 🌐. 🌘 🕰 🛠️. diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index b8f61a113..b3026917a 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -168,7 +168,7 @@ John Doe ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): - ``` Python hl_lines="1" + ```Python hl_lines="1" {!> ../../../docs_src/python_types/tutorial006.py!} ``` diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index c30bba106..fc9076aa8 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -119,7 +119,7 @@ !!! tip 👥 ⚙️ 💭 🎚 📉 👉 🖼. - ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](./security/index.md){.internal-link target=_blank}. + ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}. ## ➕1️⃣ 🕹 ⏮️ `APIRouter` diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 98058ab52..89bb615f6 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -48,7 +48,7 @@ 👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣. -!!! Note +!!! note `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index db850162a..12f5a6315 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -210,4 +210,4 @@ ## 🍵 Pydantic -🚥 👆 🚫 💚 ⚙️ Pydantic 🏷, 👆 💪 ⚙️ **💪** 🔢. 👀 🩺 [💪 - 💗 🔢: ⭐ 💲 💪](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +🚥 👆 🚫 💚 ⚙️ Pydantic 🏷, 👆 💪 ⚙️ **💪** 🔢. 👀 🩺 [💪 - 💗 🔢: ⭐ 💲 💪](body-multiple-params.md#_2){.internal-link target=_blank}. diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 9617667f4..3ed5aeba5 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -99,7 +99,7 @@ FastAPI 🐕🦺 🔗 👈 <abbr title='sometimes also called "exit", "cleanu ⚫️ 5️⃣📆 😋 🤚 `HTTPException` ⚖️ 🎏 🚪 📟, ⏮️ `yield`. ✋️ **⚫️ 🏆 🚫 👷**. -🚪 📟 🔗 ⏮️ `yield` 🛠️ *⏮️* 📨 📨, [⚠ 🐕🦺](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 🔜 ✔️ ⏪ 🏃. 📤 🕳 😽 ⚠ 🚮 👆 🔗 🚪 📟 (⏮️ `yield`). +🚪 📟 🔗 ⏮️ `yield` 🛠️ *⏮️* 📨 📨, [⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank} 🔜 ✔️ ⏪ 🏃. 📤 🕳 😽 ⚠ 🚮 👆 🔗 🚪 📟 (⏮️ `yield`). , 🚥 👆 🤚 `HTTPException` ⏮️ `yield`, 🔢 (⚖️ 🙆 🛃) ⚠ 🐕🦺 👈 ✊ `HTTPException`Ⓜ & 📨 🇺🇸🔍 4️⃣0️⃣0️⃣ 📨 🏆 🚫 📤 ✊ 👈 ⚠ 🚫🔜. @@ -111,7 +111,7 @@ FastAPI 🐕🦺 🔗 👈 <abbr title='sometimes also called "exit", "cleanu 🚥 👆 ✔️ 📟 👈 👆 💭 💪 🤚 ⚠, 🏆 😐/"🙃" 👜 & 🚮 `try` 🍫 👈 📄 📟. -🚥 👆 ✔️ 🛃 ⚠ 👈 👆 🔜 💖 🍵 *⏭* 🛬 📨 & 🎲 ❎ 📨, 🎲 🙋♀ `HTTPException`, ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. +🚥 👆 ✔️ 🛃 ⚠ 👈 👆 🔜 💖 🍵 *⏭* 🛬 📨 & 🎲 ❎ 📨, 🎲 🙋♀ `HTTPException`, ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}. !!! tip 👆 💪 🤚 ⚠ 🔌 `HTTPException` *⏭* `yield`. ✋️ 🚫 ⏮️. @@ -164,7 +164,7 @@ participant tasks as Background tasks ⏮️ 1️⃣ 📚 📨 📨, 🙅♂ 🎏 📨 💪 📨. !!! tip - 👉 📊 🎦 `HTTPException`, ✋️ 👆 💪 🤚 🙆 🎏 ⚠ ❔ 👆 ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + 👉 📊 🎦 `HTTPException`, ✋️ 👆 💪 🤚 🙆 🎏 ⚠ ❔ 👆 ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}. 🚥 👆 🤚 🙆 ⚠, ⚫️ 🔜 🚶♀️ 🔗 ⏮️ 🌾, 🔌 `HTTPException`, & ⤴️ **🔄** ⚠ 🐕🦺. 🚥 📤 🙅♂ ⚠ 🐕🦺 👈 ⚠, ⚫️ 🔜 ⤴️ 🍵 🔢 🔗 `ServerErrorMiddleware`, 🛬 5️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟, ➡️ 👩💻 💭 👈 📤 ❌ 💽. diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 7cb54a963..82f974d9f 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -11,7 +11,7 @@ !!! danger 🙅 🏪 👩💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. - 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂♂ 📃](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}. ## 💗 🏷 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index 252e769f4..b8d3f6b56 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -310,7 +310,7 @@ https://example.com/items/foo ``` !!! note - 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#in-a-hurry){.internal-link target=_blank}. + 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}. ### 🔁 5️⃣: 📨 🎚 diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 75508af4d..97d345fa2 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -66,7 +66,7 @@ ``` !!! info - ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#tags){.internal-link target=_blank}. + ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}. ### ✅ 🩺 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index ccb235c15..746b0af9e 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -222,4 +222,4 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `limit`, 📦 `int`. !!! tip - 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#predefined-values){.internal-link target=_blank}. + 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}. diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 765d94039..b9e3deb3c 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -163,7 +163,7 @@ UserInDB( ``` !!! info - 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}. ## 📨 🤝 diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index ef08fcf4b..4c8740984 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -534,7 +534,7 @@ current_user.items 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](./dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} + ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} & ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. @@ -620,7 +620,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): 🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. !!! note "📶 📡 ℹ" - 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#very-technical-details){.internal-link target=_blank} 🩺. + 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. ## 🛠️ diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 999d67cd3..3ae51e298 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -50,7 +50,7 @@ ### **FastAPI** 📱 📁 -➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](./bigger-applications.md){.internal-link target=_blank}: +➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](bigger-applications.md){.internal-link target=_blank}: ``` . diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 4da2ddefc..b25c11b17 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -345,6 +345,6 @@ and then it won't include it in the OpenAPI schema. ## Mounting a sub-application -If you need to mount a sub-application (as described in [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect. +If you need to mount a sub-application (as described in [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect. FastAPI will internally use the `root_path` smartly, so it will just work. ✨ diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 827776f5e..45c7c7bd5 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -23,7 +23,7 @@ Import the `Response` class (sub-class) you want to use and declare it in the *p For large responses, returning a `Response` directly is much faster than returning a dictionary. -This is because by default, FastAPI will inspect every item inside and make sure it is serializable with JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models. +This is because by default, FastAPI will inspect every item inside and make sure it is serializable as JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models. 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. @@ -73,7 +73,7 @@ The same example from above, returning an `HTMLResponse`, could look like: A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. !!! info - Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object your returned. + Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned. ### Document in OpenAPI and override `Response` diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 481bf5e69..286e8f93f 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -77,7 +77,7 @@ In that case, you can simply swap the standard `dataclasses` with `pydantic.data As always, in FastAPI you can combine `def` and `async def` as needed. - If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank" class="internal-link">`async` and `await`</a>. + If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about [`async` and `await`](../async.md#in-a-hurry){.internal-link target=_blank}. 9. This *path operation function* is not returning dataclasses (although it could), but a list of dictionaries with internal data. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index ca9d86ae4..703fcb7ae 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -159,4 +159,4 @@ Underneath, in the ASGI technical specification, this is part of the <a href="ht ## Sub Applications -🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}. +🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index c333ddf85..fd9a73618 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -237,7 +237,7 @@ We could download the OpenAPI JSON to a file `openapi.json` and then we could ** === "Node.js" - ```Python + ```Javascript {!> ../../../docs_src/generate_clients/tutorial004.js!} ``` @@ -271,7 +271,7 @@ After generating the new client, you would now have **clean method names**, with ## Benefits -When using the automatically generated clients you would **autocompletion** for: +When using the automatically generated clients you would get **autocompletion** for: * Methods. * Request payloads in the body, query parameters, etc. diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index fb7a6d917..2785ee140 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -131,7 +131,7 @@ with a JSON body of: } ``` -Then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*): +then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*): ``` https://www.external.org/events/invoices/2expen51ve @@ -174,6 +174,6 @@ Now use the parameter `callbacks` in *your API's path operation decorator* to pa Now you can start your app with Uvicorn and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. -You will see your docs including a "Callback" section for your *path operation* that shows how the *external API* should look like: +You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look like: <img src="/img/tutorial/openapi-callbacks/image01.png"> diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 8b79bfe22..c5544a78b 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -59,7 +59,7 @@ That defines the metadata about the main response of a *path operation*. You can also declare additional responses with their models, status codes, etc. -There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}. +There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. ## OpenAPI Extra @@ -77,7 +77,7 @@ This *path operation*-specific OpenAPI schema is normally generated automaticall !!! tip This is a low level extension point. - If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}. + If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`. diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index f6db8d2b1..8f72bf63a 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -232,7 +232,7 @@ And then use it in a file `main.py`: ``` !!! tip - You would also need a file `__init__.py` as you saw on [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. + You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. ## Settings in a dependency diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index a089632ac..8c52e091f 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -70,4 +70,4 @@ That way, the sub-application will know to use that path prefix for the docs UI. And the sub-application could also have its own mounted sub-applications and everything would work correctly, because FastAPI handles all these `root_path`s automatically. -You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}. +You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index cfe3c78c1..852e25019 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # Including WSGI - Flask, Django, others -You can mount WSGI applications as you saw with [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}. +You can mount WSGI applications as you saw with [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}. For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc. diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index d351c4e0b..9a101a8a1 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -1,6 +1,6 @@ # Alternatives, Inspiration and Comparisons -What inspired **FastAPI**, how it compares to other alternatives and what it learned from them. +What inspired **FastAPI**, how it compares to alternatives and what it learned from them. ## Intro @@ -117,7 +117,7 @@ That's why when talking about version 2.0 it's common to say "Swagger", and for * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> - These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional alternative user interfaces for OpenAPI (that you can use with **FastAPI**). + These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**). ### Flask REST frameworks @@ -291,7 +291,7 @@ As it is based on the previous standard for synchronous Python web frameworks (W !!! info Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files. -!!! check "Ideas inspired in **FastAPI**" +!!! check "Ideas inspiring **FastAPI**" Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index ff322635a..a0c00933a 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -397,7 +397,7 @@ All that is what powers FastAPI (through Starlette) and what makes it have such These are very technical details of how **FastAPI** works underneath. - If you have quite some technical knowledge (co-routines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. + If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. ### Path operation functions @@ -409,11 +409,11 @@ Still, in both situations, chances are that **FastAPI** will [still be faster](i ### Dependencies -The same applies for [dependencies](./tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. +The same applies for [dependencies](tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. ### Sub-dependencies -You can have multiple dependencies and [sub-dependencies](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". +You can have multiple dependencies and [sub-dependencies](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". ### Other utility functions diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md index d746b6d7c..62266c449 100644 --- a/docs/en/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -1,6 +1,6 @@ # Benchmarks -Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) +Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). But when checking benchmarks and comparisons you should keep the following in mind. diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index cc01fb24e..b771ae663 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -25,7 +25,7 @@ But for now, let's check these important **conceptual ideas**. These concepts al ## Security - HTTPS -In the [previous chapter about HTTPS](./https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API. +In the [previous chapter about HTTPS](https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API. We also saw that HTTPS is normally provided by a component **external** to your application server, a **TLS Termination Proxy**. @@ -187,7 +187,7 @@ When you run **multiple processes** of the same API program, they are commonly c ### Worker Processes and Ports -Remember from the docs [About HTTPS](./https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server? +Remember from the docs [About HTTPS](https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server? This is still true. @@ -230,18 +230,18 @@ The main constraint to consider is that there has to be a **single** component h Here are some possible combinations and strategies: * **Gunicorn** managing **Uvicorn workers** - * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes** + * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes**. * **Uvicorn** managing **Uvicorn workers** - * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes** + * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**. * **Kubernetes** and other distributed **container systems** - * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running + * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running. * **Cloud services** that handle this for you * The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it. !!! tip Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. - I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. + I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. ## Previous Steps Before Starting @@ -273,7 +273,7 @@ Here are some possible ideas: * You would still need a way to start/restart *that* bash script, detect errors, etc. !!! tip - I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. + I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. ## Resource Utilization diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 8a542622e..467ba72de 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -108,7 +108,7 @@ It would depend mainly on the tool you use to **install** those requirements. The most common way to do it is to have a file `requirements.txt` with the package names and their versions, one per line. -You would of course use the same ideas you read in [About FastAPI versions](./versions.md){.internal-link target=_blank} to set the ranges of versions. +You would of course use the same ideas you read in [About FastAPI versions](versions.md){.internal-link target=_blank} to set the ranges of versions. For example, your `requirements.txt` could look like: @@ -373,7 +373,7 @@ Then adjust the Uvicorn command to use the new module `main` instead of `app.mai ## Deployment Concepts -Let's talk again about some of the same [Deployment Concepts](./concepts.md){.internal-link target=_blank} in terms of containers. +Let's talk again about some of the same [Deployment Concepts](concepts.md){.internal-link target=_blank} in terms of containers. Containers are mainly a tool to simplify the process of **building and deploying** an application, but they don't enforce a particular approach to handle these **deployment concepts**, and there are several possible strategies. @@ -514,7 +514,7 @@ If you have a simple setup, with a **single container** that then starts multipl ## Official Docker Image with Gunicorn - Uvicorn -There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](./server-workers.md){.internal-link target=_blank}. +There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](server-workers.md){.internal-link target=_blank}. This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 2df9f3d43..5fe2309a9 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -13,12 +13,12 @@ Up to this point, with all the tutorials in the docs, you have probably been run When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests. -As you saw in the previous chapter about [Deployment Concepts](./concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. +As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. Here I'll show you how to use <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> with **Uvicorn worker processes**. !!! info - If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. + If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. @@ -165,7 +165,7 @@ From the list of deployment concepts from above, using workers would mainly help ## Containers and Docker -In the next chapter about [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. +In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 1d76aca5e..121447739 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -51,7 +51,7 @@ You can: * Tell me how you use FastAPI (I love to hear that). * Hear when I make announcements or release new tools. * You can also <a href="https://twitter.com/fastapi" class="external-link" target="_blank">follow @fastapi on Twitter</a> (a separate account). -* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">Follow me on **Linkedin**</a>. +* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">Follow me on **LinkedIn**</a>. * Hear when I make announcements or release new tools (although I use Twitter more often 🤷♂). * Read what I write (or follow me) on <a href="https://dev.to/tiangolo" class="external-link" target="_blank">**Dev.to**</a> or <a href="https://medium.com/@tiangolo" class="external-link" target="_blank">**Medium**</a>. * Read other ideas, articles, and read about tools I have created. @@ -78,7 +78,7 @@ You can try and help others with their questions in: In many cases you might already know the answer for those questions. 🤓 -If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉 Just remember, the most important point is: try to be kind. People come with their frustrations and in many cases don't ask in the best way, but try as best as you can to be kind. 🤗 @@ -227,7 +227,7 @@ If you can help me with that, **you are helping me maintain FastAPI** and making Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord chat server</a> 👥 and hang out with others in the FastAPI community. !!! tip - For questions, ask them in <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}. + For questions, ask them in <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. Use the chat only for other general conversations. @@ -237,7 +237,7 @@ Keep in mind that as chats allow more "free conversation", it's easy to ask ques In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅 -Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub. +Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub. On the other side, there are thousands of users in the chat systems, so there's a high chance you'll find someone to talk to there, almost all the time. 😄 diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md index c7b340d67..4d53f53a7 100644 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -100,7 +100,7 @@ Create the *path operation function* to read notes: {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! Note +!!! note Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. ### Notice the `response_model=List[Note]` @@ -122,7 +122,7 @@ Create the *path operation function* to create notes: The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. -!!! Note +!!! note Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. ### About `{**note.dict(), "id": last_record_id}` diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index f36ba5ba8..108afb929 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -45,7 +45,7 @@ FastAPI includes some default configuration parameters appropriate for most of t It includes these default configurations: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-13]!} +{!../../../fastapi/openapi/docs.py[ln:7-23]!} ``` You can override any of them by setting a different value in the argument `swagger_ui_parameters`. diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 51db744ff..3e8267aea 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -186,7 +186,7 @@ For example, let's define a variable to be a `list` of `str`. From `typing`, import `List` (with a capital `L`): - ``` Python hl_lines="1" + ```Python hl_lines="1" {!> ../../../docs_src/python_types/tutorial006.py!} ``` diff --git a/docs/en/docs/reference/apirouter.md b/docs/en/docs/reference/apirouter.md index b779ad291..d77364e45 100644 --- a/docs/en/docs/reference/apirouter.md +++ b/docs/en/docs/reference/apirouter.md @@ -1,7 +1,6 @@ # `APIRouter` class -Here's the reference information for the `APIRouter` class, with all its parameters, -attributes and methods. +Here's the reference information for the `APIRouter` class, with all its parameters, attributes and methods. You can import the `APIRouter` class directly from `fastapi`: diff --git a/docs/en/docs/reference/background.md b/docs/en/docs/reference/background.md index e0c0be899..f65619590 100644 --- a/docs/en/docs/reference/background.md +++ b/docs/en/docs/reference/background.md @@ -1,8 +1,6 @@ # Background Tasks - `BackgroundTasks` -You can declare a parameter in a *path operation function* or dependency function -with the type `BackgroundTasks`, and then you can use it to schedule the execution -of background tasks after the response is sent. +You can declare a parameter in a *path operation function* or dependency function with the type `BackgroundTasks`, and then you can use it to schedule the execution of background tasks after the response is sent. You can import it directly from `fastapi`: diff --git a/docs/en/docs/reference/dependencies.md b/docs/en/docs/reference/dependencies.md index 099968267..2959a21da 100644 --- a/docs/en/docs/reference/dependencies.md +++ b/docs/en/docs/reference/dependencies.md @@ -2,8 +2,7 @@ ## `Depends()` -Dependencies are handled mainly with the special function `Depends()` that takes a -callable. +Dependencies are handled mainly with the special function `Depends()` that takes a callable. Here is the reference for it and its parameters. @@ -17,11 +16,9 @@ from fastapi import Depends ## `Security()` -For many scenarios, you can handle security (authorization, authentication, etc.) with -dependencies, using `Depends()`. +For many scenarios, you can handle security (authorization, authentication, etc.) with dependencies, using `Depends()`. -But when you want to also declare OAuth2 scopes, you can use `Security()` instead of -`Depends()`. +But when you want to also declare OAuth2 scopes, you can use `Security()` instead of `Depends()`. You can import `Security()` directly from `fastapi`: diff --git a/docs/en/docs/reference/exceptions.md b/docs/en/docs/reference/exceptions.md index 7c4808349..1392d2a80 100644 --- a/docs/en/docs/reference/exceptions.md +++ b/docs/en/docs/reference/exceptions.md @@ -2,9 +2,7 @@ These are the exceptions that you can raise to show errors to the client. -When you raise an exception, as would happen with normal Python, the rest of the -execution is aborted. This way you can raise these exceptions from anywhere in the -code to abort a request and show the error to the client. +When you raise an exception, as would happen with normal Python, the rest of the execution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client. You can use: diff --git a/docs/en/docs/reference/fastapi.md b/docs/en/docs/reference/fastapi.md index 8b87664cb..d5367ff34 100644 --- a/docs/en/docs/reference/fastapi.md +++ b/docs/en/docs/reference/fastapi.md @@ -1,7 +1,6 @@ # `FastAPI` class -Here's the reference information for the `FastAPI` class, with all its parameters, -attributes and methods. +Here's the reference information for the `FastAPI` class, with all its parameters, attributes and methods. You can import the `FastAPI` class directly from `fastapi`: diff --git a/docs/en/docs/reference/httpconnection.md b/docs/en/docs/reference/httpconnection.md index 43dfc46f9..b7b87871a 100644 --- a/docs/en/docs/reference/httpconnection.md +++ b/docs/en/docs/reference/httpconnection.md @@ -1,8 +1,6 @@ # `HTTPConnection` class -When you want to define dependencies that should be compatible with both HTTP and -WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a -`Request` or a `WebSocket`. +When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. You can import it from `fastapi.requests`: diff --git a/docs/en/docs/reference/middleware.md b/docs/en/docs/reference/middleware.md index 89704d3c8..3c666ccda 100644 --- a/docs/en/docs/reference/middleware.md +++ b/docs/en/docs/reference/middleware.md @@ -2,8 +2,7 @@ There are several middlewares available provided by Starlette directly. -Read more about them in the -[FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/). +Read more about them in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/). ::: fastapi.middleware.cors.CORSMiddleware diff --git a/docs/en/docs/reference/parameters.md b/docs/en/docs/reference/parameters.md index 8f77f0161..d304c013c 100644 --- a/docs/en/docs/reference/parameters.md +++ b/docs/en/docs/reference/parameters.md @@ -2,8 +2,7 @@ Here's the reference information for the request parameters. -These are the special functions that you can put in *path operation function* -parameters or dependency functions with `Annotated` to get data from the request. +These are the special functions that you can put in *path operation function* parameters or dependency functions with `Annotated` to get data from the request. It includes: diff --git a/docs/en/docs/reference/request.md b/docs/en/docs/reference/request.md index 91ec7d37b..0326f3fc7 100644 --- a/docs/en/docs/reference/request.md +++ b/docs/en/docs/reference/request.md @@ -1,8 +1,6 @@ # `Request` class -You can declare a parameter in a *path operation function* or dependency to be of type -`Request` and then you can access the raw request object directly, without any -validation, etc. +You can declare a parameter in a *path operation function* or dependency to be of type `Request` and then you can access the raw request object directly, without any validation, etc. You can import it directly from `fastapi`: @@ -11,8 +9,6 @@ from fastapi import Request ``` !!! tip - When you want to define dependencies that should be compatible with both HTTP and - WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a - `Request` or a `WebSocket`. + When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. ::: fastapi.Request diff --git a/docs/en/docs/reference/response.md b/docs/en/docs/reference/response.md index 916254583..00cf2c499 100644 --- a/docs/en/docs/reference/response.md +++ b/docs/en/docs/reference/response.md @@ -1,10 +1,8 @@ # `Response` class -You can declare a parameter in a *path operation function* or dependency to be of type -`Response` and then you can set data for the response like headers or cookies. +You can declare a parameter in a *path operation function* or dependency to be of type `Response` and then you can set data for the response like headers or cookies. -You can also use it directly to create an instance of it and return it from your *path -operations*. +You can also use it directly to create an instance of it and return it from your *path operations*. You can import it directly from `fastapi`: diff --git a/docs/en/docs/reference/responses.md b/docs/en/docs/reference/responses.md index 2cbbd8963..46f014fcc 100644 --- a/docs/en/docs/reference/responses.md +++ b/docs/en/docs/reference/responses.md @@ -1,10 +1,8 @@ # Custom Response Classes - File, HTML, Redirect, Streaming, etc. -There are several custom response classes you can use to create an instance and return -them directly from your *path operations*. +There are several custom response classes you can use to create an instance and return them directly from your *path operations*. -Read more about it in the -[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). +Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). You can import them directly from `fastapi.responses`: diff --git a/docs/en/docs/reference/security/index.md b/docs/en/docs/reference/security/index.md index ff86e9e30..9a5c5e15f 100644 --- a/docs/en/docs/reference/security/index.md +++ b/docs/en/docs/reference/security/index.md @@ -2,12 +2,9 @@ When you need to declare dependencies with OAuth2 scopes you use `Security()`. -But you still need to define what is the dependable, the callable that you pass as -a parameter to `Depends()` or `Security()`. +But you still need to define what is the dependable, the callable that you pass as a parameter to `Depends()` or `Security()`. -There are multiple tools that you can use to create those dependables, and they get -integrated into OpenAPI so they are shown in the automatic docs UI, they can be used -by automatically generated clients and SDKs, etc. +There are multiple tools that you can use to create those dependables, and they get integrated into OpenAPI so they are shown in the automatic docs UI, they can be used by automatically generated clients and SDKs, etc. You can import them from `fastapi.security`: diff --git a/docs/en/docs/reference/staticfiles.md b/docs/en/docs/reference/staticfiles.md index ce66f17b3..271231078 100644 --- a/docs/en/docs/reference/staticfiles.md +++ b/docs/en/docs/reference/staticfiles.md @@ -2,8 +2,7 @@ You can use the `StaticFiles` class to serve static files, like JavaScript, CSS, images, etc. -Read more about it in the -[FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/). +Read more about it in the [FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/). You can import it directly from `fastapi.staticfiles`: diff --git a/docs/en/docs/reference/status.md b/docs/en/docs/reference/status.md index a23800792..6e0e816d3 100644 --- a/docs/en/docs/reference/status.md +++ b/docs/en/docs/reference/status.md @@ -16,12 +16,9 @@ For example: * 403: `status.HTTP_403_FORBIDDEN` * etc. -It can be convenient to quickly access HTTP (and WebSocket) status codes in your app, -using autocompletion for the name without having to remember the integer status codes -by memory. +It can be convenient to quickly access HTTP (and WebSocket) status codes in your app, using autocompletion for the name without having to remember the integer status codes by memory. -Read more about it in the -[FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). +Read more about it in the [FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). ## Example diff --git a/docs/en/docs/reference/templating.md b/docs/en/docs/reference/templating.md index c865badfc..eedfe44d5 100644 --- a/docs/en/docs/reference/templating.md +++ b/docs/en/docs/reference/templating.md @@ -2,8 +2,7 @@ You can use the `Jinja2Templates` class to render Jinja templates. -Read more about it in the -[FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/). +Read more about it in the [FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/). You can import it directly from `fastapi.templating`: diff --git a/docs/en/docs/reference/testclient.md b/docs/en/docs/reference/testclient.md index e391d964a..2966ed792 100644 --- a/docs/en/docs/reference/testclient.md +++ b/docs/en/docs/reference/testclient.md @@ -2,8 +2,7 @@ You can use the `TestClient` class to test FastAPI applications without creating an actual HTTP and socket connection, just communicating directly with the FastAPI code. -Read more about it in the -[FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/). +Read more about it in the [FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/). You can import it directly from `fastapi.testclient`: diff --git a/docs/en/docs/reference/uploadfile.md b/docs/en/docs/reference/uploadfile.md index 45c644b18..43a753730 100644 --- a/docs/en/docs/reference/uploadfile.md +++ b/docs/en/docs/reference/uploadfile.md @@ -1,7 +1,6 @@ # `UploadFile` class -You can define *path operation function* parameters to be of the type `UploadFile` -to receive files from the request. +You can define *path operation function* parameters to be of the type `UploadFile` to receive files from the request. You can import it directly from `fastapi`: diff --git a/docs/en/docs/reference/websockets.md b/docs/en/docs/reference/websockets.md index 2a0469467..d21e81a07 100644 --- a/docs/en/docs/reference/websockets.md +++ b/docs/en/docs/reference/websockets.md @@ -1,7 +1,6 @@ # WebSockets -When defining WebSockets, you normally declare a parameter of type `WebSocket` and -with it you can read data from the client and send data to it. +When defining WebSockets, you normally declare a parameter of type `WebSocket` and with it you can read data from the client and send data to it. It is provided directly by Starlette, but you can import it from `fastapi`: @@ -10,9 +9,7 @@ from fastapi import WebSocket ``` !!! tip - When you want to define dependencies that should be compatible with both HTTP and - WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a - `Request` or a `WebSocket`. + When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. ::: fastapi.WebSocket options: @@ -44,8 +41,7 @@ from fastapi import WebSocket - send_json - close -When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch -it. +When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch it. You can import it directly form `fastapi`: diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index b2d928405..eccdd8aeb 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -136,7 +136,7 @@ We will now use a simple dependency to read a custom `X-Token` header: !!! tip We are using an invented header to simplify this example. - But in real cases you will get better results using the integrated [Security utilities](./security/index.md){.internal-link target=_blank}. + But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}. ## Another module with `APIRouter` @@ -329,7 +329,7 @@ The section: from .routers import items, users ``` -Means: +means: * Starting in the same package that this module (the file `app/main.py`) lives in (the directory `app/`)... * look for the subpackage `routers` (the directory at `app/routers/`)... @@ -373,7 +373,7 @@ from .routers.items import router from .routers.users import router ``` -The `router` from `users` would overwrite the one from `items` and we wouldn't be able to use them at the same time. +the `router` from `users` would overwrite the one from `items` and we wouldn't be able to use them at the same time. So, to be able to use both of them in the same file, we import the submodules directly: diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 39d133c55..3ba2632d8 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -48,7 +48,7 @@ You can also use the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/ This means that you can send only the data that you want to update, leaving the rest intact. -!!! Note +!!! note `PATCH` is less commonly used and known than `PUT`. And many teams use only `PUT`, even for partial updates. diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index 842f2adf6..4b958a665 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -271,6 +271,12 @@ Now you can declare your dependency using this class. Notice how we write `CommonQueryParams` twice in the above code: +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + === "Python 3.8+ non-Annotated" !!! tip @@ -280,12 +286,6 @@ Notice how we write `CommonQueryParams` twice in the above code: commons: CommonQueryParams = Depends(CommonQueryParams) ``` -=== "Python 3.8+" - - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` - The last `CommonQueryParams`, in: ```Python @@ -334,7 +334,7 @@ You could actually write just: commons = Depends(CommonQueryParams) ``` -..as in: +...as in: === "Python 3.10+" @@ -380,6 +380,12 @@ But declaring the type is encouraged as that way your editor will know what will But you see that we are having some code repetition here, writing `CommonQueryParams` twice: +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + === "Python 3.8+ non-Annotated" !!! tip @@ -389,12 +395,6 @@ But you see that we are having some code repetition here, writing `CommonQueryPa commons: CommonQueryParams = Depends(CommonQueryParams) ``` -=== "Python 3.8+" - - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` - **FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will "call" to create an instance of the class itself. For those specific cases, you can do the following: diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index 608ced407..e05d40685 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -257,7 +257,7 @@ And you can declare dependencies with `async def` inside of normal `def` *path o It doesn't matter. **FastAPI** will know what to do. !!! note - If you don't know, check the [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} section about `async` and `await` in the docs. + If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} section about `async` and `await` in the docs. ## Integrated with OpenAPI diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 49b00c730..cc0680cfd 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -83,7 +83,7 @@ So, continuing with the `user_dict` from above, writing: UserInDB(**user_dict) ``` -Would result in something equivalent to: +would result in something equivalent to: ```Python UserInDB( diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 0e6292629..75d5df106 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -338,7 +338,7 @@ Your response model could have default values, like: * `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`. -* `tags: List[str] = []` as a default of an empty list: `[]`. +* `tags: List[str] = []` has a default of an empty list: `[]`. but you might want to omit them from the result if they were not actually stored. diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 9bb9ba4e3..40231dc0b 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -305,7 +305,7 @@ This new `examples` field in JSON Schema is **just a `list`** of examples, not a ### Pydantic and FastAPI `examples` -When you add `examples` inside of a Pydantic model, using `schema_extra` or `Field(examples=["something"])` that example is added to the **JSON Schema** for that Pydantic model. +When you add `examples` inside a Pydantic model, using `schema_extra` or `Field(examples=["something"])` that example is added to the **JSON Schema** for that Pydantic model. And that **JSON Schema** of the Pydantic model is included in the **OpenAPI** of your API, and then it's used in the docs UI. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 1c792e3d9..b02d00c3f 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -260,7 +260,7 @@ If the token is invalid, return an HTTP error right away. Create a `timedelta` with the expiration time of the token. -Create a real JWT access token and return it +Create a real JWT access token and return it. === "Python 3.10+" diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index 88edc9eab..6f40531d7 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -118,7 +118,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe Now, get the user data from the (fake) database, using the `username` from the form field. -If there is no such user, we return an error saying "incorrect username or password". +If there is no such user, we return an error saying "Incorrect username or password". For the error, we use the exception `HTTPException`: @@ -416,7 +416,7 @@ Password: `secret2` And try to use the operation `GET` with the path `/users/me`. -You will get an "inactive user" error, like: +You will get an "Inactive user" error, like: ```JSON { diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 1a2000f02..0b4d06b99 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -546,7 +546,7 @@ Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. - But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](./dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} + But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} And then, when using the dependency in a *path operation function*, we declare it with the type `Session` we imported directly from SQLAlchemy. diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 3f8dd69a1..8d199a4c7 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -50,7 +50,7 @@ And your **FastAPI** application might also be composed of several files/modules ### **FastAPI** app file -Let's say you have a file structure as described in [Bigger Applications](./bigger-applications.md){.internal-link target=_blank}: +Let's say you have a file structure as described in [Bigger Applications](bigger-applications.md){.internal-link target=_blank}: ``` . diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index dcd6154be..18159775d 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -400,7 +400,7 @@ Cuando declaras una *path operation function* con `def` normal en lugar de `asyn Si vienes de otro framework asíncrono que no funciona de la manera descrita anteriormente y estás acostumbrado a definir *path operation functions* del tipo sólo cálculo con `def` simple para una pequeña ganancia de rendimiento (aproximadamente 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen un código que realice el bloqueo <abbr title="Input/Output: disk reading or writing, network communications.">I/O</abbr>. -Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](index.md#performance){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior. +Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](index.md#rendimiento){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior. ### Dependencias diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index b3d9c8bf2..776d98ce5 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 2cb7e6308..c37ce00fb 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -310,7 +310,7 @@ También podrías definirla como una función estándar en lugar de `async def`: ``` !!! note "Nota" - Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. ### Paso 5: devuelve el contenido diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index f0dff02b4..f11820ef2 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. -!!! nota +!!! note "Nota" También puedes instalarlo parte por parte. Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 482af8dc0..76dc331a9 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -194,4 +194,4 @@ En este caso hay 3 parámetros de query: * `limit`, un `int` opcional. !!! tip "Consejo" - También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#predefined-values){.internal-link target=_blank}. + También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. diff --git a/docs/fa/docs/advanced/sub-applications.md b/docs/fa/docs/advanced/sub-applications.md index f3a948414..6f2359b94 100644 --- a/docs/fa/docs/advanced/sub-applications.md +++ b/docs/fa/docs/advanced/sub-applications.md @@ -69,4 +69,4 @@ $ uvicorn main:app --reload و زیر برنامه ها نیز می تواند زیر برنامه های متصل شده خود را داشته باشد و همه چیز به درستی کار کند، زیرا FastAPI تمام این مسیرهای `root_path` را به طور خودکار مدیریت می کند. -در بخش [پشت پراکسی](./behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت. +در بخش [پشت پراکسی](behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت. diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index e5231ec8d..71c23b7f7 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> @@ -30,7 +39,7 @@ FastAPI یک وب فریمورک مدرن و سریع (با کارایی با ویژگیهای کلیدی این فریمورک عبارتند از: -* **<abbr title="Fast">سرعت</abbr>**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance). +* **<abbr title="Fast">سرعت</abbr>**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#_10). * **<abbr title="Fast to code">کدنویسی سریع</abbr>**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه قابلیتهای جدید. * * **<abbr title="Fewer bugs">باگ کمتر</abbr>**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). * diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md index 35b57594d..685a054ad 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 -!!! Attention +!!! warning "Attention" Ceci concerne un sujet plutôt avancé. Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. @@ -27,10 +27,10 @@ Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un mod {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! Remarque +!!! note "Remarque" Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. -!!! Info +!!! info La clé `model` ne fait pas partie d'OpenAPI. **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. @@ -172,10 +172,10 @@ Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! Remarque +!!! note "Remarque" Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. -!!! Info +!!! info À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. @@ -206,7 +206,7 @@ Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` : -``` Python +```Python old_dict = { "old key": "old value", "second old key": "second old value", @@ -216,7 +216,7 @@ new_dict = {**old_dict, "new key": "new value"} Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la nouvelle paire clé-valeur : -``` Python +```Python { "old key": "old value", "second old key": "second old value", diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md index e7b003707..51f0db737 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!} ``` -!!! Attention +!!! warning "Attention" Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. Elle ne sera pas sérialisée avec un modèle. diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md index aa37f1806..4599bcb6f 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 +!!! note "Remarque" Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index 7ded97ce1..77f551aea 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 -!!! Attention +!!! warning "Attention" Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`. @@ -23,10 +23,10 @@ Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! Astuce +!!! tip "Astuce" Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. -!!! Attention +!!! warning "Attention" Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. Même s'ils se trouvent dans des modules différents (fichiers Python). @@ -59,7 +59,7 @@ Cela définit les métadonnées sur la réponse principale d'une *opération de Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc. -Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}. +Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. ## OpenAPI supplémentaire @@ -74,8 +74,8 @@ 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. -!!! Astuce - Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}. +!!! tip "Astuce" + Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`. @@ -162,7 +162,7 @@ Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le {!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` -!!! Astuce +!!! tip "Astuce" Ici, nous réutilisons le même modèle Pydantic. Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 1c923fb82..ed29446d4 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 +!!! note "Remarque" `JSONResponse` est elle-même une sous-classe de `Response`. Et quand vous retournez une `Response`, **FastAPI** la transmet directement. diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md index 275a9bd37..d99dcd9c2 100644 --- a/docs/fr/docs/fastapi-people.md +++ b/docs/fr/docs/fastapi-people.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # La communauté FastAPI FastAPI a une communauté extraordinaire qui accueille des personnes de tous horizons. @@ -18,7 +23,7 @@ C'est moi : </div> {% endif %} -Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus à ce sujet dans [Aide FastAPI - Obtenir de l'aide - Se rapprocher de l'auteur](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus à ce sujet dans [Aide FastAPI - Obtenir de l'aide - Se rapprocher de l'auteur](help-fastapi.md#se-rapprocher-de-lauteur){.internal-link target=_blank}. ...Mais ici, je veux vous montrer la communauté. @@ -28,15 +33,15 @@ Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus Ce sont ces personnes qui : -* [Aident les autres à résoudre des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Créent des Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Review les Pull Requests, [particulièrement important pour les traductions](contributing.md#translations){.internal-link target=_blank}. +* [Aident les autres à résoudre des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank}. +* [Créent des Pull Requests](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank}. +* Review les Pull Requests, [particulièrement important pour les traductions](contributing.md#traductions){.internal-link target=_blank}. Une salve d'applaudissements pour eux. 👏 🙇 ## Utilisateurs les plus actifs le mois dernier -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} au cours du dernier mois. ☕ +Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} au cours du dernier mois. ☕ {% if people %} <div class="user-list user-list-center"> @@ -52,7 +57,7 @@ Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes ( Voici les **Experts FastAPI**. 🤓 -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} depuis *toujours*. +Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} depuis *toujours*. Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personnes. ✨ @@ -70,7 +75,7 @@ Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personne Ces utilisateurs sont les **Principaux contributeurs**. 👷 -Ces utilisateurs ont [créé le plus grand nombre de demandes Pull Request](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} qui ont été *merged*. +Ces utilisateurs ont [créé le plus grand nombre de demandes Pull Request](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank} qui ont été *merged*. Ils ont contribué au code source, à la documentation, aux traductions, etc. 📦 @@ -92,7 +97,7 @@ Ces utilisateurs sont les **Principaux Reviewers**. 🕵️ ### Reviewers des traductions -Je ne parle que quelques langues (et pas très bien 😅). Ainsi, les reviewers sont ceux qui ont le [**pouvoir d'approuver les traductions**](contributing.md#translations){.internal-link target=_blank} de la documentation. Sans eux, il n'y aurait pas de documentation dans plusieurs autres langues. +Je ne parle que quelques langues (et pas très bien 😅). Ainsi, les reviewers sont ceux qui ont le [**pouvoir d'approuver les traductions**](contributing.md#traductions){.internal-link target=_blank} de la documentation. Sans eux, il n'y aurait pas de documentation dans plusieurs autres langues. --- diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index 1457df2a5..da1c70df9 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Fonctionnalités ## Fonctionnalités de FastAPI diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index bc3ae3c06..eb02e2a0c 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 817545c1c..523e2c8c2 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -28,7 +28,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`. -!!! hint "Astuce" +!!! 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. @@ -40,7 +40,7 @@ Si vous exécutez cet exemple et allez sur <a href="http://127.0.0.1:8000/items/ {"item_id":3} ``` -!!! hint "Astuce" +!!! check "vérifier" Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`, en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`. @@ -72,7 +72,7 @@ La même erreur se produira si vous passez un nombre flottant (`float`) et non u <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>. -!!! hint "Astuce" +!!! check "vérifier" Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 335a22743..8f1f2a124 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> @@ -31,7 +40,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג תכונות המפתח הן: -- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance). +- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#_14). - **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \* - **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \* diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md index b8ed96ae1..6b6de24f0 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. -!!! catatan +!!! note "Catatan" Kamu juga dapat meng-installnya bagian demi bagian. Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index 934cea0ef..5e38d1cec 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -368,7 +368,7 @@ async def read_burgers(): 上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキング<abbr title="入力/出力: ディスクの読み取りまたは書き込み、ネットワーク通信。">I/O</abbr>を実行しないのであれば、`async def` の使用をお勧めします。 -それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#performance){.internal-link target=_blank}可能性があります。 +それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#_10){.internal-link target=_blank}可能性があります。 ### 依存関係 @@ -390,4 +390,4 @@ async def read_burgers(): 繰り返しになりますが、これらは非常に技術的な詳細であり、検索して辿り着いた場合は役立つでしょう。 -それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: <a href="#in-a-hurry">急いでいますか?</a>。 +それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: <a href="#_1">急いでいますか?</a>。 diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md index 38cbca219..abe4f2c66 100644 --- a/docs/ja/docs/deployment/concepts.md +++ b/docs/ja/docs/deployment/concepts.md @@ -30,7 +30,7 @@ ## セキュリティ - HTTPS <!-- NOTE: https.md written in Japanese does not exist, so it redirects to English one --> -[前チャプターのHTTPSについて](./https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 +[前チャプターのHTTPSについて](https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 通常、アプリケーションサーバにとって**外部の**コンポーネントである**TLS Termination Proxy**によって提供されることが一般的です。このプロキシは通信の暗号化を担当します。 @@ -188,7 +188,7 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ ### ワーカー・プロセス と ポート <!-- NOTE: https.md written in Japanese does not exist, so it redirects to English one --> -[HTTPSについて](./https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか? +[HTTPSについて](https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか? これはいまだに同じです。 @@ -247,7 +247,7 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 <!-- NOTE: the current version of docker.md is outdated compared to English one. --> - コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. + コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. ## 開始前の事前のステップ @@ -282,7 +282,7 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ !!! tip <!-- NOTE: the current version of docker.md is outdated compared to English one. --> - コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. + コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. ## リソースの利用 diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index ca9dedc3c..0c9df648d 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -117,7 +117,7 @@ FastAPI用の**Dockerイメージ**を、**公式Python**イメージに基づ 最も一般的な方法は、`requirements.txt` ファイルにパッケージ名とそのバージョンを 1 行ずつ書くことです。 -もちろん、[FastAPI バージョンについて](./versions.md){.internal-link target=_blank}で読んだのと同じアイデアを使用して、バージョンの範囲を設定します。 +もちろん、[FastAPI バージョンについて](versions.md){.internal-link target=_blank}で読んだのと同じアイデアを使用して、バージョンの範囲を設定します。 例えば、`requirements.txt` は次のようになります: @@ -384,7 +384,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## デプロイメントのコンセプト -コンテナという観点から、[デプロイのコンセプト](./concepts.md){.internal-link target=_blank}に共通するいくつかについて、もう一度説明しましょう。 +コンテナという観点から、[デプロイのコンセプト](concepts.md){.internal-link target=_blank}に共通するいくつかについて、もう一度説明しましょう。 コンテナは主に、アプリケーションの**ビルドとデプロイ**のプロセスを簡素化するためのツールですが、これらの**デプロイのコンセプト**を扱うための特定のアプローチを強制するものではないです。 @@ -461,7 +461,7 @@ Kubernetesのような分散コンテナ管理システムの1つは通常、入 もちろん、**特殊なケース**として、**Gunicornプロセスマネージャ**を持つ**コンテナ**内で複数の**Uvicornワーカープロセス**を起動させたい場合があります。 -このような場合、**公式のDockerイメージ**を使用することができます。このイメージには、複数の**Uvicornワーカープロセス**を実行するプロセスマネージャとして**Gunicorn**が含まれており、現在のCPUコアに基づいてワーカーの数を自動的に調整するためのデフォルト設定がいくつか含まれています。詳しくは後述の[Gunicornによる公式Dockerイメージ - Uvicorn](#gunicornによる公式dockerイメージ---Uvicorn)で説明します。 +このような場合、**公式のDockerイメージ**を使用することができます。このイメージには、複数の**Uvicornワーカープロセス**を実行するプロセスマネージャとして**Gunicorn**が含まれており、現在のCPUコアに基づいてワーカーの数を自動的に調整するためのデフォルト設定がいくつか含まれています。詳しくは後述の[Gunicornによる公式Dockerイメージ - Uvicorn](#gunicorndocker-uvicorn)で説明します。 以下は、それが理にかなっている場合の例です: @@ -531,7 +531,7 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ ## Gunicornによる公式Dockerイメージ - Uvicorn -前の章で詳しく説明したように、Uvicornワーカーで動作するGunicornを含む公式のDockerイメージがあります: [Server Workers - Gunicorn と Uvicorn](./server-workers.md){.internal-link target=_blank}で詳しく説明しています。 +前の章で詳しく説明したように、Uvicornワーカーで動作するGunicornを含む公式のDockerイメージがあります: [Server Workers - Gunicorn と Uvicorn](server-workers.md){.internal-link target=_blank}で詳しく説明しています。 このイメージは、主に上記で説明した状況で役に立つでしょう: [複数のプロセスと特殊なケースを持つコンテナ(Containers with Multiple Processes and Special Cases)](#containers-with-multiple-processes-and-special-cases) diff --git a/docs/ja/docs/deployment/server-workers.md b/docs/ja/docs/deployment/server-workers.md index e1ea165a2..51d0bc2d4 100644 --- a/docs/ja/docs/deployment/server-workers.md +++ b/docs/ja/docs/deployment/server-workers.md @@ -13,13 +13,13 @@ アプリケーションをデプロイする際には、**複数のコア**を利用し、そしてより多くのリクエストを処理できるようにするために、プロセスの**レプリケーション**を持つことを望むでしょう。 -前のチャプターである[デプロイメントのコンセプト](./concepts.md){.internal-link target=_blank}にて見てきたように、有効な戦略がいくつかあります。 +前のチャプターである[デプロイメントのコンセプト](concepts.md){.internal-link target=_blank}にて見てきたように、有効な戦略がいくつかあります。 ここでは<a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a>が**Uvicornのワーカー・プロセス**を管理する場合の使い方について紹介していきます。 !!! info <!-- NOTE: the current version of docker.md is outdated compared to English one. --> - DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank} + DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank} 特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 @@ -167,7 +167,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## コンテナとDocker <!-- NOTE: the current version of docker.md is outdated compared to English one. --> -次章の[コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}では、その他の**デプロイのコンセプト**を扱うために実施するであろう戦略をいくつか紹介します。 +次章の[コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}では、その他の**デプロイのコンセプト**を扱うために実施するであろう戦略をいくつか紹介します。 また、**GunicornとUvicornワーカー**を含む**公式Dockerイメージ**と、簡単なケースに役立ついくつかのデフォルト設定も紹介します。 diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md index ff75dcbce..d92a7bf46 100644 --- a/docs/ja/docs/fastapi-people.md +++ b/docs/ja/docs/fastapi-people.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # FastAPI People FastAPIには、様々なバックグラウンドの人々を歓迎する素晴らしいコミュニティがあります。 @@ -19,7 +24,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 {% endif %} -私は **FastAPI** の作成者および Maintainer です。詳しくは [FastAPIを応援 - ヘルプの入手 - 開発者とつながる](help-fastapi.md#開発者とつながる){.internal-link target=_blank} に記載しています。 +私は **FastAPI** の作成者および Maintainer です。詳しくは [FastAPIを応援 - ヘルプの入手 - 開発者とつながる](help-fastapi.md#_1){.internal-link target=_blank} に記載しています。 ...ところで、ここではコミュニティを紹介したいと思います。 @@ -29,15 +34,15 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 紹介するのは次のような人々です: -* [GitHub issuesで他の人を助ける](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 +* [GitHub issuesで他の人を助ける](help-fastapi.md#github-issues){.internal-link target=_blank}。 * [プルリクエストをする](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* プルリクエストのレビューをする ([特に翻訳に重要](contributing.md#translations){.internal-link target=_blank})。 +* プルリクエストのレビューをする ([特に翻訳に重要](contributing.md#_8){.internal-link target=_blank})。 彼らに大きな拍手を。👏 🙇 ## 先月最もアクティブだったユーザー -彼らは、先月の[GitHub issuesで最も多くの人を助けた](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}ユーザーです。☕ +彼らは、先月の[GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。☕ {% if people %} <div class="user-list user-list-center"> @@ -53,7 +58,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 **FastAPI experts** を紹介します。🤓 -彼らは、*これまでに* [GitHub issuesで最も多くの人を助けた](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}ユーザーです。 +彼らは、*これまでに* [GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。 多くの人を助けることでexpertsであると示されています。✨ @@ -93,7 +98,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 ### 翻訳のレビュー -私は少しの言語しか話せません (もしくはあまり上手ではありません😅)。したがって、reviewers は、ドキュメントの[**翻訳を承認する権限**](contributing.md#translations){.internal-link target=_blank}を持っています。それらがなければ、いくつかの言語のドキュメントはなかったでしょう。 +私は少しの言語しか話せません (もしくはあまり上手ではありません😅)。したがって、reviewers は、ドキュメントの[**翻訳を承認する権限**](contributing.md#_8){.internal-link target=_blank}を持っています。それらがなければ、いくつかの言語のドキュメントはなかったでしょう。 --- diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 98c59e7c4..64d8758a5 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # 機能 ## FastAPIの機能 diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 4f66b1a40..37cddae5e 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> @@ -28,7 +37,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 主な特徴: -- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#performance). +- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#_10). - **高速なコーディング**: 開発速度を約 200%~300%向上させます。 \* - **少ないバグ**: 開発者起因のヒューマンエラーを約 40%削減します。 \* diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index 7a56ef2b9..95d328ec5 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`よりもあまり使われておらず、知られていません。 また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 12332991d..ccce9484d 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -162,4 +162,4 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ ## Pydanticを使わない方法 -もしPydanticモデルを使用したくない場合は、**Body**パラメータが利用できます。[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}を確認してください。 +もしPydanticモデルを使用したくない場合は、**Body**パラメータが利用できます。[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#_2){.internal-link target=_blank}を確認してください。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 2a89e51d2..c0642efd4 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -108,7 +108,7 @@ FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown" `yield`の後の終了コードで`HTTPException`などを発生させたくなるかもしれません。しかし**それはうまくいきません** -`yield`を持つ依存関係の終了コードは[例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}の*後に*実行されます。依存関係によって投げられた例外を終了コード(`yield`の後)でキャッチするものはなにもありません。 +`yield`を持つ依存関係の終了コードは[例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}の*後に*実行されます。依存関係によって投げられた例外を終了コード(`yield`の後)でキャッチするものはなにもありません。 つまり、`yield`の後に`HTTPException`を発生させた場合、`HTTTPException`をキャッチしてHTTP 400のレスポンスを返すデフォルトの(あるいは任意のカスタムの)例外ハンドラは、その例外をキャッチすることができなくなります。 @@ -120,7 +120,7 @@ FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown" 例外が発生する可能性があるコードがある場合は、最も普通の「Python流」なことをして、コードのその部分に`try`ブロックを追加してください。 -レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成してください。 +レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成してください。 !!! tip "豆知識" `HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。 @@ -171,7 +171,7 @@ participant tasks as Background tasks いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。 !!! tip "豆知識" - この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。 + この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。 しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。 diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index c696f7d48..f79ed94a4 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -308,7 +308,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを ``` !!! note "備考" - 違いが分からない場合は、[Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}を確認してください。 + 違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。 ### Step 5: コンテンツの返信 diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 957726b9f..5c4cfc5fc 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -191,4 +191,4 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy !!! tip "豆知識" - [パスパラメータ](path-params.md#predefined-values){.internal-link target=_blank}と同様に `Enum` を使用できます。 + [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index f1c43b7b4..dc3267e62 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -125,7 +125,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。 - 相対 URL を使うことは、[プロキシと接続](./.../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 + 相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。 diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index 9bcebd367..65ee124ec 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -2,7 +2,7 @@ *경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경 -## <a name="in-a-hurry"></a>바쁘신 경우 +## 바쁘신 경우 <strong>요약</strong> @@ -263,7 +263,7 @@ CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필 파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다. -배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](/ko/deployment){.internal-link target=_blank}문서를 참고하십시오. +배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](deployment/index.md){.internal-link target=_blank}문서를 참고하십시오. ## `async`와 `await` @@ -379,7 +379,7 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 <a href="https://anyi 만약 상기에 묘사된대로 동작하지 않는 비동기 프로그램을 사용해왔고 약간의 성능 향상 (약 100 나노초)을 위해 `def`를 사용해서 계산만을 위한 사소한 *경로 작동 함수*를 정의해왔다면, **FastAPI**는 이와는 반대라는 것에 주의하십시오. 이러한 경우에, *경로 작동 함수*가 블로킹 <abbr title="Input/Output: 디스크 읽기 또는 쓰기, 네트워크 통신.">I/O</abbr>를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다. -하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. +하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#_11){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. ### 의존성 @@ -401,4 +401,4 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 <a href="https://anyi 다시 말하지만, 이것은 당신이 이것에 대해 찾고있던 경우에 한해 유용할 매우 세부적인 기술사항입니다. -그렇지 않은 경우, 상기의 가이드라인만으로도 충분할 것입니다: [바쁘신 경우](#in-a-hurry). +그렇지 않은 경우, 상기의 가이드라인만으로도 충분할 것입니다: [바쁘신 경우](#_1). diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md index 1c7bced2c..0e8f85cae 100644 --- a/docs/ko/docs/deployment/docker.md +++ b/docs/ko/docs/deployment/docker.md @@ -108,7 +108,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 가장 일반적인 방법은 패키지 이름과 버전이 줄 별로 기록된 `requirements.txt` 파일을 만드는 것입니다. -버전의 범위를 설정하기 위해서는 [FastAPI 버전들에 대하여](./versions.md){.internal-link target=_blank}에 쓰여진 것과 같은 아이디어를 사용합니다. +버전의 범위를 설정하기 위해서는 [FastAPI 버전들에 대하여](versions.md){.internal-link target=_blank}에 쓰여진 것과 같은 아이디어를 사용합니다. 예를 들어, `requirements.txt` 파일은 다음과 같을 수 있습니다: @@ -199,7 +199,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 옵션은 `pip`에게 다운로드한 패키지들을 로컬 환경에 저장하지 않도록 전달합니다. 이는 마치 같은 패키지를 설치하기 위해 오직 `pip`만 다시 실행하면 될 것 같지만, 컨테이너로 작업하는 경우 그렇지는 않습니다. - !!! 노트 + !!! note "노트" `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. `--upgrade` 옵션은 `pip`에게 설치된 패키지들을 업데이트하도록 합니다. @@ -373,7 +373,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 배포 개념 -이제 컨테이너의 측면에서 [배포 개념](./concepts.md){.internal-link target=_blank}에서 다루었던 것과 같은 배포 개념에 대해 이야기해 보겠습니다. +이제 컨테이너의 측면에서 [배포 개념](concepts.md){.internal-link target=_blank}에서 다루었던 것과 같은 배포 개념에 대해 이야기해 보겠습니다. 컨테이너는 주로 어플리케이션을 빌드하고 배포하기 위한 과정을 단순화하는 도구이지만, **배포 개념**에 대한 특정한 접근법을 강요하지 않기 때문에 가능한 배포 전략에는 여러가지가 있습니다. @@ -514,7 +514,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn -앞 챕터에서 자세하게 설명된 것 처럼, Uvicorn 워커와 같이 실행되는 Gunicorn을 포함하는 공식 도커 이미지가 있습니다: [서버 워커 - Uvicorn과 함께하는 Gunicorn](./server-workers.md){.internal-link target=_blank}. +앞 챕터에서 자세하게 설명된 것 처럼, Uvicorn 워커와 같이 실행되는 Gunicorn을 포함하는 공식 도커 이미지가 있습니다: [서버 워커 - Uvicorn과 함께하는 Gunicorn](server-workers.md){.internal-link target=_blank}. 이 이미지는 주로 위에서 설명된 상황에서 유용할 것입니다: [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases). diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md index 5653c55e3..f7ef96094 100644 --- a/docs/ko/docs/deployment/server-workers.md +++ b/docs/ko/docs/deployment/server-workers.md @@ -13,12 +13,12 @@ 애플리케이션을 배포할 때 **다중 코어**를 활용하고 더 많은 요청을 처리할 수 있도록 **프로세스 복제본**이 필요합니다. -전 과정이었던 [배포 개념들](./concepts.md){.internal-link target=_blank}에서 본 것처럼 여러가지 방법이 존재합니다. +전 과정이었던 [배포 개념들](concepts.md){.internal-link target=_blank}에서 본 것처럼 여러가지 방법이 존재합니다. 지금부터 <a href="https://gunicorn.org/" class="external-link" target="_blank">**구니콘**</a>을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. -!!! 정보 - 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. +!!! info "정보" + 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. 특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. @@ -165,7 +165,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 컨테이너와 도커 -다음 장인 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다. +다음 장인 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다. 또한 간단한 케이스에서 사용할 수 있는, **구니콘과 유비콘 워커**가 포함돼 있는 **공식 도커 이미지**와 함께 몇 가지 기본 구성을 보여드리겠습니다. diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index 54479165e..f7b35557c 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -68,7 +68,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! 정보 +!!! info "정보" `**second_user_data`가 뜻하는 것: `second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index eeadc0363..85482718e 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> @@ -28,7 +37,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 주요 특징으로: -* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#performance). +* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#_11). * **빠른 코드 작성**: 약 200%에서 300%까지 기능 개발 속도 증가. * * **적은 버그**: 사람(개발자)에 의한 에러 약 40% 감소. * diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index fc7209726..c91d6130b 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -26,7 +26,7 @@ === "Python 3.10+ Annotated가 없는 경우" - !!! 팁 + !!! tip "팁" 가능하다면 `Annotated`가 달린 버전을 권장합니다. ```Python hl_lines="2" diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 8b98284bb..0ab8b7162 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -8,7 +8,7 @@ **요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 모델을 사용합니다. -!!! 정보 +!!! info "정보" 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. `GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. @@ -134,7 +134,7 @@ <img src="/img/tutorial/body/image05.png"> -!!! 팁 +!!! tip "팁" 만약 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>를 편집기로 사용한다면, <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>을 사용할 수 있습니다. 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: @@ -203,11 +203,11 @@ * 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. * 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. -!!! 참고 +!!! note "참고" FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. ## Pydantic없이 -만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank} 문서를 확인하세요. +만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#_2){.internal-link target=_blank} 문서를 확인하세요. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index c56dddae3..d06864ab8 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -85,12 +85,12 @@ 그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. -!!! 정보 +!!! info "정보" FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. - `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}를 확실하게 하세요. + `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요. ### `Depends` 불러오기 diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index e3b42bce7..bdec3a377 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -310,7 +310,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa ``` !!! note "참고" - 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요. + 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. ### 5 단계: 콘텐츠 반환 diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index 8c7f9167b..43a6c1a36 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -195,4 +195,4 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `limit`, 선택적인 `int`. !!! tip "팁" - [경로 매개변수](path-params.md#predefined-values){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. + [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index 5bc2cee7a..f4b6f9471 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -86,12 +86,12 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다. -!!! 팁 +!!! tip "팁" 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. -!!! 확인 +!!! check "확인" 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index a6435977c..7c2013799 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Cechy ## Cechy FastAPI diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index 54c172664..fdc3b0bf9 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -78,7 +78,7 @@ Możesz spróbować pomóc innym, odpowiadając w: W wielu przypadkach możesz już znać odpowiedź na te pytania. 🤓 -Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉 Pamiętaj tylko o najważniejszym: bądź życzliwy. Ludzie przychodzą sfrustrowani i w wielu przypadkach nie zadają pytań w najlepszy sposób, ale mimo to postaraj się być dla nich jak najbardziej życzliwy. 🤗 @@ -215,8 +215,8 @@ Jest wiele pracy do zrobienia, a w większości przypadków **TY** możesz to zr Główne zadania, które możesz wykonać teraz to: -* [Pomóc innym z pytaniami na GitHubie](#help-others-with-questions-in-github){.internal-link target=_blank} (zobacz sekcję powyżej). -* [Oceniać Pull Requesty](#review-pull-requests){.internal-link target=_blank} (zobacz sekcję powyżej). +* [Pomóc innym z pytaniami na GitHubie](#pomagaj-innym-odpowiadajac-na-ich-pytania-na-githubie){.internal-link target=_blank} (zobacz sekcję powyżej). +* [Oceniać Pull Requesty](#przegladaj-pull-requesty){.internal-link target=_blank} (zobacz sekcję powyżej). Te dwie czynności **zajmują najwięcej czasu**. To główna praca związana z utrzymaniem FastAPI. @@ -226,8 +226,8 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz Dołącz do 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">serwera czatu na Discordzie</a> 👥 i spędzaj czas z innymi w społeczności FastAPI. -!!! wskazówka - Jeśli masz pytania, zadaj je w <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. +!!! tip "Wskazówka" + Jeśli masz pytania, zadaj je w <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. Używaj czatu tylko do innych ogólnych rozmów. @@ -237,7 +237,7 @@ Miej na uwadze, że ponieważ czaty pozwalają na bardziej "swobodną rozmowę", Na GitHubie szablon poprowadzi Cię do napisania odpowiedniego pytania, dzięki czemu łatwiej uzyskasz dobrą odpowiedź, a nawet rozwiążesz problem samodzielnie, zanim zapytasz. Ponadto na GitHubie mogę się upewnić, że zawsze odpowiadam na wszystko, nawet jeśli zajmuje to trochę czasu. Osobiście nie mogę tego zrobić z systemami czatu. 😅 -Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie. +Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie. Z drugiej strony w systemach czatu są tysiące użytkowników, więc jest duża szansa, że znajdziesz tam kogoś do rozmowy, prawie w każdej chwili. 😄 diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index ab33bfb9c..b168b9e5e 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 9406d703d..ce71f8b83 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -311,7 +311,7 @@ Możesz również zdefiniować to jako normalną funkcję zamiast `async def`: ``` !!! note - Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}. + Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. ### Krok 5: zwróć zawartość diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 7f6cb6f5d..12aa93f29 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -160,4 +160,4 @@ Por baixo, na especificação técnica ASGI, essa é a parte do <a href="https:/ ## Sub Aplicações -🚨 Tenha em mente que esses eventos de lifespan (de inicialização e desligamento) irão somente ser executados para a aplicação principal, não para [Sub Aplicações - Montagem](./sub-applications.md){.internal-link target=_blank}. +🚨 Tenha em mente que esses eventos de lifespan (de inicialização e desligamento) irão somente ser executados para a aplicação principal, não para [Sub Aplicações - Montagem](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md index fe2363386..1ec8f07c6 100644 --- a/docs/pt/docs/async.md +++ b/docs/pt/docs/async.md @@ -261,7 +261,7 @@ Mas você também pode explorar os benefícios do paralelismo e multiprocessamen Isso, mais o simples fato que Python é a principal linguagem para **Data Science**, Machine Learning e especialmente Deep Learning, faz do FastAPI uma ótima escolha para APIs web e aplicações com Data Science / Machine Learning (entre muitas outras). -Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment.md){.internal-link target=_blank}. +Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment/index.md){.internal-link target=_blank}. ## `async` e `await` diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index 42c31db29..9ab8d38f0 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -4,8 +4,8 @@ Ao fazer o deploy de aplicações FastAPI uma abordagem comum é construir uma * Usando contêineres Linux você tem diversas vantagens incluindo **segurança**, **replicabilidade**, **simplicidade**, entre outras. -!!! Dica - Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#build-a-docker-image-for-fastapi). +!!! tip "Dica" + Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). <details> @@ -109,7 +109,7 @@ Isso pode depender principalmente da ferramenta que você usa para **instalar** O caminho mais comum de fazer isso é ter um arquivo `requirements.txt` com os nomes dos pacotes e suas versões, um por linha. -Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](./versions.md){.internal-link target=_blank} para definir os intervalos de versões. +Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](versions.md){.internal-link target=_blank} para definir os intervalos de versões. Por exemplo, seu `requirements.txt` poderia parecer com: @@ -374,7 +374,7 @@ Então ajuste o comando Uvicorn para usar o novo módulo `main` em vez de `app.m ## Conceitos de Implantação -Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](./concepts.md){.internal-link target=_blank} em termos de contêineres. +Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](concepts.md){.internal-link target=_blank} em termos de contêineres. Contêineres são principalmente uma ferramenta para simplificar o processo de **construção e implantação** de um aplicativo, mas eles não impõem uma abordagem particular para lidar com esses **conceitos de implantação** e existem várias estratégias possíveis. @@ -515,14 +515,14 @@ Se você tiver uma configuração simples, com um **único contêiner** que ent ## Imagem Oficial do Docker com Gunicorn - Uvicorn -Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](./server-workers.md){.internal-link target=_blank}. +Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](server-workers.md){.internal-link target=_blank}. -Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais). +Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais). * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. !!! warning - Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construa-uma-imagem-docker-para-o-fastapi). + Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi). Essa imagem tem um mecanismo de **auto-ajuste** incluído para definir o **número de processos trabalhadores** com base nos núcleos de CPU disponíveis. @@ -579,7 +579,7 @@ COPY ./app /app/app Você provavelmente **não** deve usar essa imagem base oficial (ou qualquer outra semelhante) se estiver usando **Kubernetes** (ou outros) e já estiver definindo **replicação** no nível do cluster, com vários **contêineres**. Nesses casos, é melhor **construir uma imagem do zero** conforme descrito acima: [Construindo uma Imagem Docker para FastAPI](#construindo-uma-imagem-docker-para-fastapi). -Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc. +Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc. ## Deploy da Imagem do Contêiner diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md index 20061bfd9..93c3479f2 100644 --- a/docs/pt/docs/fastapi-people.md +++ b/docs/pt/docs/fastapi-people.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Pessoas do FastAPI FastAPI possue uma comunidade incrível que recebe pessoas de todos os níveis. @@ -18,7 +23,7 @@ Este sou eu: </div> {% endif %} -Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#conect-se-com-o-autor){.internal-link target=_blank}. ...Mas aqui eu quero mostrar a você a comunidade. @@ -28,15 +33,15 @@ Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em Estas são as pessoas que: -* [Help others with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Revisar Pull Requests, [especially important for translations](contributing.md#translations){.internal-link target=_blank}. +* [Help others with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank}. +* [Create Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank}. +* Revisar Pull Requests, [especially important for translations](contributing.md#traducoes){.internal-link target=_blank}. Uma salva de palmas para eles. 👏 🙇 ## Usuários mais ativos do ultimo mês -Estes são os usuários que estão [helping others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} durante o ultimo mês. ☕ +Estes são os usuários que estão [helping others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} durante o ultimo mês. ☕ {% if people %} <div class="user-list user-list-center"> @@ -53,7 +58,7 @@ Estes são os usuários que estão [helping others the most with issues (questio Aqui está os **Especialistas do FastAPI**. 🤓 -Estes são os usuários que [helped others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} em *todo o tempo*. +Estes são os usuários que [helped others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} em *todo o tempo*. Eles provaram ser especialistas ajudando muitos outros. ✨ @@ -71,7 +76,7 @@ Eles provaram ser especialistas ajudando muitos outros. ✨ Aqui está os **Top Contribuidores**. 👷 -Esses usuários têm [created the most Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} que tem sido *mergeado*. +Esses usuários têm [created the most Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank} que tem sido *mergeado*. Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 @@ -93,7 +98,7 @@ Esses usuários são os **Top Revisores**. 🕵️ ### Revisões para Traduções -Eu só falo algumas línguas (e não muito bem 😅). Então, os revisores são aqueles que têm o [**poder de aprovar traduções**](contributing.md#translations){.internal-link target=_blank} da documentação. Sem eles, não haveria documentação em vários outros idiomas. +Eu só falo algumas línguas (e não muito bem 😅). Então, os revisores são aqueles que têm o [**poder de aprovar traduções**](contributing.md#traducoes){.internal-link target=_blank} da documentação. Sem eles, não haveria documentação em vários outros idiomas. --- diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index 64efeeae1..c514fc8e3 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Recursos ## Recursos do FastAPI diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index 06a4db1e0..babb404f9 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -72,7 +72,7 @@ Adoro ouvir sobre como o **FastAPI** é usado, o que você gosta nele, em qual p Você pode acompanhar as <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">perguntas existentes</a> e tentar ajudar outros, . 🤓 -Ajudando a responder as questões de varias pessoas, você pode se tornar um [Expert em FastAPI](fastapi-people.md#experts){.internal-link target=_blank} oficial. 🎉 +Ajudando a responder as questões de varias pessoas, você pode se tornar um [Expert em FastAPI](fastapi-people.md#especialistas){.internal-link target=_blank} oficial. 🎉 ## Acompanhe o repositório do GitHub @@ -98,7 +98,7 @@ Assim podendo tentar ajudar a resolver essas questões. * Para corrigir um erro de digitação que você encontrou na documentação. * Para compartilhar um artigo, video, ou podcast criados por você sobre o FastAPI <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">editando este arquivo</a>. * Não se esqueça de adicionar o link no começo da seção correspondente. -* Para ajudar [traduzir a documentação](contributing.md#translations){.internal-link target=_blank} para sua lingua. +* Para ajudar [traduzir a documentação](contributing.md#traducoes){.internal-link target=_blank} para sua lingua. * Também é possivel revisar as traduções já existentes. * Para propor novas seções na documentação. * Para corrigir um bug/questão. @@ -109,8 +109,8 @@ Assim podendo tentar ajudar a resolver essas questões. Entre no 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">server de conversa do Discord</a> 👥 e conheça novas pessoas da comunidade do FastAPI. -!!! dica - Para perguntas, pergunte nas <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}. +!!! tip "Dica" + Para perguntas, pergunte nas <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. Use o chat apenas para outro tipo de assunto. @@ -120,7 +120,7 @@ Tenha em mente que os chats permitem uma "conversa mais livre", dessa forma é m Nas questões do GitHub o template irá te guiar para que você faça a sua pergunta de um jeito mais correto, fazendo com que você receba respostas mais completas, e até mesmo que você mesmo resolva o problema antes de perguntar. E no GitHub eu garanto que sempre irei responder todas as perguntas, mesmo que leve um tempo. Eu pessoalmente não consigo fazer isso via chat. 😅 -Conversas no chat não são tão fáceis de serem encontrados quanto no GitHub, então questões e respostas podem se perder dentro da conversa. E apenas as que estão nas questões do GitHub contam para você se tornar um [Expert em FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, então você receberá mais atenção nas questões do GitHub. +Conversas no chat não são tão fáceis de serem encontrados quanto no GitHub, então questões e respostas podem se perder dentro da conversa. E apenas as que estão nas questões do GitHub contam para você se tornar um [Expert em FastAPI](fastapi-people.md#especialistas){.internal-link target=_blank}, então você receberá mais atenção nas questões do GitHub. Por outro lado, existem milhares de usuários no chat, então tem uma grande chance de você encontrar alguém para trocar uma idéia por lá em qualquer horário. 😄 diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 05786a0aa..1a29a9bea 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 0eaa9664c..7d0435a6b 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -20,7 +20,7 @@ E você também pode declarar parâmetros de corpo como opcionais, definindo o v {!> ../../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! 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. ## Múltiplos parâmetros de corpo @@ -69,7 +69,7 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo } ``` -!!! 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`. diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index e039b09b2..c9d0b8bb6 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: } ``` -!!! Informação +!!! info "informação" Note como o campo `images` agora tem uma lista de objetos de image. ## Modelos profundamente aninhados @@ -176,7 +176,7 @@ Você pode definir modelos profundamente aninhados de forma arbitrária: {!../../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! Informação +!!! info "informação" Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s ## Corpos de listas puras @@ -226,7 +226,7 @@ Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com va {!../../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! Dica +!!! tip "Dica" Leve em condideração que o JSON só suporta `str` como chaves. Mas o Pydantic tem conversão automática de dados. diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 5901b8414..713bea2d1 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -162,4 +162,4 @@ Os parâmetros da função serão reconhecidos conforme abaixo: ## Sem o Pydantic -Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#valores-singulares-no-corpo){.internal-link target=_blank}. diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index b9bfbf63b..7a8d20515 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -38,5 +38,5 @@ O resultado de chamar a função é algo que pode ser codificado com o padrão d A função não retorna um grande `str` contendo os dados no formato JSON (como uma string). Mas sim, retorna uma estrutura de dados padrão do Python (por exemplo, um `dict`) com valores e subvalores compatíveis com JSON. -!!! nota +!!! note "Nota" `jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários. diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index 9fcdaf91f..619a68601 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload </div> -!!! nota +!!! note "Nota" O comando `uvicorn main:app` se refere a: * `main`: o arquivo `main.py` (o "módulo" Python). @@ -136,7 +136,7 @@ Você também pode usá-lo para gerar código automaticamente para clientes que `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. -!!! nota "Detalhes técnicos" +!!! note "Detalhes técnicos" `FastAPI` é uma classe que herda diretamente de `Starlette`. Você pode usar todas as funcionalidades do <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> com `FastAPI` também. @@ -309,7 +309,7 @@ Você também pode defini-la como uma função normal em vez de `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! nota +!!! note "Nota" Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}. ### Passo 5: retorne o conteúdo diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md index 5fc0485a0..60fc26ae0 100644 --- a/docs/pt/docs/tutorial/index.md +++ b/docs/pt/docs/tutorial/index.md @@ -52,7 +52,7 @@ $ pip install "fastapi[all]" ...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código. -!!! nota +!!! note "Nota" Você também pode instalar parte por parte. Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção: diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index be2b7f7a4..27aa9dfcf 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" Isso vai dar à você suporte do seu editor dentro das funções, com verificações de erros, autocompletar, etc. ## Conversão de <abbr title="também conhecido como: serialização, parsing, marshalling">dados</abbr> @@ -35,7 +35,7 @@ Se você rodar esse exemplo e abrir o seu navegador em <a href="http://127.0.0.1 {"item_id":3} ``` -!!! Verifique +!!! check "Verifique" Observe que o valor recebido pela função (e também retornado por ela) é `3`, como um Python `int`, não como uma string `"3"`. Então, com essa declaração de tipo, o **FastAPI** dá pra você um <abbr title="convertendo a string que veio do request HTTP em um dado Python">"parsing"</abbr> automático no request . @@ -63,7 +63,7 @@ devido ao parâmetro da rota `item_id` ter um valor `"foo"`, que não é um `int O mesmo erro apareceria se você tivesse fornecido um `float` ao invés de um `int`, como em: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! Verifique +!!! check "Verifique" Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados. Observe que o erro também mostra claramente o ponto exato onde a validação não passou. @@ -76,7 +76,7 @@ Quando você abrir o seu navegador em <a href="http://127.0.0.1:8000/docs" class <img src="/img/tutorial/path-params/image01.png"> -!!! check +!!! check "Verifique" Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI). Veja que o parâmetro de rota está declarado como sendo um inteiro (int). @@ -131,10 +131,10 @@ Assim, crie atributos de classe com valores fixos, que serão os valores válido {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! informação +!!! info "informação" <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (ou enums) estão disponíveis no Python</a> desde a versão 3.4. -!!! dica +!!! tip "Dica" Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de <abbr title="técnicamente, modelos de arquitetura de Deep Learning">modelos</abbr> de Machine Learning (aprendizado de máquina). ### Declare um *parâmetro de rota* @@ -171,7 +171,7 @@ Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_na {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! conselho +!!! tip "Dica" Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value` #### Retorne *membros de enumeration* @@ -225,7 +225,7 @@ Então, você poderia usar ele com: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! dica +!!! tip "Dica" Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`). Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`. diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 08bb99dbc..ff6f38fe5 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -222,4 +222,4 @@ Nesse caso, existem 3 parâmetros de consulta: * `limit`, um `int` opcional. !!! tip "Dica" - Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. + 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/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 395621d3b..4331a0bc3 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 -!!! informação +!!! info "informação" Primeiro, instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Ex: `pip install python-multipart`. @@ -52,7 +52,7 @@ Você verá algo deste tipo: <img src="/img/tutorial/security/image01.png"> -!!! marque o "botão de Autorizar!" +!!! check "Botão de Autorizar!" Você já tem um novo "botão de autorizar!". E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar. @@ -61,7 +61,7 @@ E se você clicar, você terá um pequeno formulário de autorização para digi <img src="/img/tutorial/security/image02.png"> -!!! nota +!!! note "Nota" Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá. Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API. @@ -104,7 +104,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`. -!!! informação +!!! info "informação" Um token "bearer" não é a única opção. Mas é a melhor no nosso caso. @@ -119,7 +119,7 @@ Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passam {!../../../docs_src/security/tutorial001.py!} ``` -!!! dica +!!! tip "Dica" Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`. Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`. @@ -130,7 +130,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. -!!! informação +!!! info "informação" Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`. Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso. @@ -157,7 +157,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). -!!! informação "Detalhes técnicos" +!!! info "Detalhes técnicos" **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`. Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI. diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md index 4d3ce2adf..20dbb108b 100644 --- a/docs/ru/docs/async.md +++ b/docs/ru/docs/async.md @@ -468,7 +468,7 @@ Starlette (и **FastAPI**) основаны на <a href="https://anyio.readthed <!--Уточнить: Не использовать async def, если код приводит к блокировке IO?--> <!--http://new.gramota.ru/spravka/punctum?layout=item&id=58_285--> -Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](index.md#performance){.internal-link target=_blank} +Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](index.md#_11){.internal-link target=_blank} другого фреймворка (или хотя бы на уровне с ним). ### Зависимости @@ -502,4 +502,4 @@ Starlette (и **FastAPI**) основаны на <a href="https://anyio.readthed <!--http://new.gramota.ru/spravka/buro/search-answer?s=299749--> Ещё раз повторим, что все эти технические подробности полезны, только если вы специально их искали. -В противном случае просто ознакомьтесь с основными принципами в разделе выше: <a href="#in-a-hurry">Нет времени?</a>. +В противном случае просто ознакомьтесь с основными принципами в разделе выше: <a href="#_1">Нет времени?</a>. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index 771f4bf68..26db356c1 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -25,7 +25,7 @@ ## Использование более безопасного протокола HTTPS -В [предыдущей главе об HTTPS](./https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для вашего API. +В [предыдущей главе об HTTPS](https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для вашего API. Также мы заметили, что обычно для работы с HTTPS вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**. @@ -187,7 +187,7 @@ ### Процессы и порты́ -Помните ли Вы, как на странице [Об HTTPS](./https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта? +Помните ли Вы, как на странице [Об HTTPS](https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта? С тех пор ничего не изменилось. @@ -241,7 +241,7 @@ !!! tip "Заметка" Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. - Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](./docker.md){.internal-link target=_blank}. + Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. ## Шаги, предшествующие запуску @@ -273,7 +273,7 @@ * При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п. !!! tip "Заметка" - Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](./docker.md){.internal-link target=_blank}. + Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [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 78d3ec1b4..ce4972c4f 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -110,7 +110,7 @@ Docker является одним оз основных инструменто Чаще всего это простой файл `requirements.txt` с построчным перечислением библиотек и их версий. -При этом Вы, для выбора версий, будете использовать те же идеи, что упомянуты на странице [О версиях FastAPI](./versions.md){.internal-link target=_blank}. +При этом Вы, для выбора версий, будете использовать те же идеи, что упомянуты на странице [О версиях FastAPI](versions.md){.internal-link target=_blank}. Ваш файл `requirements.txt` может выглядеть как-то так: @@ -374,7 +374,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Концепции развёртывания -Давайте вспомним о [Концепциях развёртывания](./concepts.md){.internal-link target=_blank} и применим их к контейнерам. +Давайте вспомним о [Концепциях развёртывания](concepts.md){.internal-link target=_blank} и применим их к контейнерам. Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязывают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. @@ -447,7 +447,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Использование менеджера процессов (Gunicorn или Uvicorn) внутри контейнера только добавляет **излишнее усложнение**, так как управление следует осуществлять системой оркестрации. -### <a name="special-cases"></a>Множество процессов внутри контейнера для особых случаев</a> +### Множество процессов внутри контейнера для особых случаев Безусловно, бывают **особые случаи**, когда может понадобиться внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. @@ -515,9 +515,9 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Официальный Docker-образ с Gunicorn и Uvicorn -Я подготовил для вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](./server-workers.md){.internal-link target=_blank}. +Я подготовил для вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](server-workers.md){.internal-link target=_blank}. -Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#special-cases). +Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#_11). * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. @@ -578,7 +578,7 @@ COPY ./app /app/app Если вы используете **Kubernetes** (или что-то вроде того), скорее всего вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). -Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#special-cases). Например, если ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д +Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#_11). Например, если ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д ## Развёртывание образа контейнера diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md index 91b9038e9..f410e3936 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 "Подсказка" "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. Итак, вы можете закрепить версию следующим образом: @@ -53,7 +53,7 @@ fastapi>=0.45.0,<0.46.0 Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии. -!!! Подсказка +!!! tip "Подсказка" "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. ## Обновление версий FastAPI diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md index 0e42aab69..fa70d168e 100644 --- a/docs/ru/docs/fastapi-people.md +++ b/docs/ru/docs/fastapi-people.md @@ -1,3 +1,7 @@ +--- +hide: + - navigation +--- # Люди, поддерживающие FastAPI @@ -19,7 +23,7 @@ </div> {% endif %} -Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#_2){.internal-link target=_blank}. ... но на этой странице я хочу показать вам наше сообщество. @@ -29,15 +33,15 @@ Это люди, которые: -* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Создают пул-реквесты](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#translations){.internal-link target=_blank}. +* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank}. +* [Создают пул-реквесты](help-fastapi.md#-_1){.internal-link target=_blank}. +* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#_8){.internal-link target=_blank}. Поаплодируем им! 👏 🙇 ## Самые активные участники за прошедший месяц -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} в течение последнего месяца. ☕ +Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} в течение последнего месяца. ☕ {% if people %} <div class="user-list user-list-center"> @@ -53,7 +57,7 @@ Здесь представлены **Эксперты FastAPI**. 🤓 -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} за *всё время*. +Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} за *всё время*. Оказывая помощь многим другим, они подтвердили свой уровень знаний. ✨ @@ -71,7 +75,7 @@ Здесь представлен **Рейтинг участников, внёсших вклад в код**. 👷 -Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, *включённых в основной код*. +Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#-_1){.internal-link target=_blank}, *включённых в основной код*. Они сделали наибольший вклад в исходный код, документацию, переводы и т.п. 📦 @@ -94,7 +98,7 @@ ### Проверки переводов на другие языки Я знаю не очень много языков (и не очень хорошо 😅). -Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#translations){.internal-link target=_blank}. Без них не было бы документации на многих языках. +Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#_8){.internal-link target=_blank}. Без них не было бы документации на многих языках. --- diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index 110c7d31e..59860e12b 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Основные свойства ## Основные свойства FastAPI @@ -66,7 +71,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! Информация +!!! info "Информация" `**second_user_data` означает: Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index 3ad3e6fd4..d53f501f5 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -73,7 +73,7 @@ Вы можете посмотреть, какие <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">проблемы</a> испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓 -Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. 🎉 Только помните, самое важное при этом - доброта. Столкнувшись с проблемой, люди расстраиваются и часто задают вопросы не лучшим образом, но постарайтесь быть максимально доброжелательным. 🤗 @@ -162,7 +162,7 @@ * Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код. -!!! Информация +!!! info "Информация" К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 @@ -190,7 +190,7 @@ * Исправить опечатку, которую Вы нашли в документации. * Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">изменив этот файл</a>. * Убедитесь, что Вы добавили свою ссылку в начало соответствующего раздела. -* Помочь с [переводом документации](contributing.md#translations){.internal-link target=_blank} на Ваш язык. +* Помочь с [переводом документации](contributing.md#_8){.internal-link target=_blank} на Ваш язык. * Вы также можете проверять переводы сделанные другими. * Предложить новые разделы документации. * Исправить существующуе проблемы/баги. @@ -207,8 +207,8 @@ Основные задачи, которые Вы можете выполнить прямо сейчас: -* [Помочь другим с их проблемами на GitHub](#help-others-with-issues-in-github){.internal-link target=_blank} (смотрите вышестоящую секцию). -* [Проверить пул-реквесты](#review-pull-requests){.internal-link target=_blank} (смотрите вышестоящую секцию). +* [Помочь другим с их проблемами на GitHub](#github_1){.internal-link target=_blank} (смотрите вышестоящую секцию). +* [Проверить пул-реквесты](#-){.internal-link target=_blank} (смотрите вышестоящую секцию). Эти две задачи **отнимают больше всего времени**. Это основная работа по поддержке FastAPI. @@ -218,8 +218,8 @@ Подключайтесь к 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank"> чату в Discord</a> 👥 и общайтесь с другими участниками сообщества FastAPI. -!!! Подсказка - Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. +!!! tip "Подсказка" + Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. Используйте этот чат только для бесед на отвлечённые темы. @@ -229,7 +229,7 @@ В разделе "проблемы" на GitHub, есть шаблон, который поможет Вам написать вопрос правильно, чтобы Вам было легче получить хороший ответ или даже решить проблему самостоятельно, прежде чем Вы зададите вопрос. В GitHub я могу быть уверен, что всегда отвечаю на всё, даже если это займет какое-то время. И я не могу сделать то же самое в чатах. 😅 -Кроме того, общение в чатах не так легкодоступно для поиска, как в GitHub, потому вопросы и ответы могут потеряться среди другого общения. И только проблемы решаемые на GitHub учитываются в получении лычки [Эксперт FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, так что весьма вероятно, что Вы получите больше внимания на GitHub. +Кроме того, общение в чатах не так легкодоступно для поиска, как в GitHub, потому вопросы и ответы могут потеряться среди другого общения. И только проблемы решаемые на GitHub учитываются в получении лычки [Эксперт FastAPI](fastapi-people.md#_3){.internal-link target=_blank}, так что весьма вероятно, что Вы получите больше внимания на GitHub. С другой стороны, в чатах тысячи пользователей, а значит есть большие шансы в любое время найти там кого-то, с кем можно поговорить. 😄 diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 477567af6..e9ecfa520 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index e52ef6f6f..ffba1d0f4 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -28,7 +28,7 @@ === "Python 3.10+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать `Annotated` версию, если это возможно. ```Python hl_lines="17-19" @@ -37,14 +37,14 @@ === "Python 3.8+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать версию с `Annotated`, если это возможно. ```Python hl_lines="19-21" {!> ../../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! Заметка +!!! note "Заметка" Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. ## Несколько параметров тела запроса @@ -93,7 +93,7 @@ } ``` -!!! Внимание +!!! note "Внимание" Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. @@ -131,7 +131,7 @@ === "Python 3.10+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать `Annotated` версию, если это возможно. ```Python hl_lines="20" @@ -140,7 +140,7 @@ === "Python 3.8+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать `Annotated` версию, если это возможно. ```Python hl_lines="22" @@ -205,7 +205,7 @@ q: str | None = None === "Python 3.10+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать `Annotated` версию, если это возможно. ```Python hl_lines="25" @@ -214,14 +214,14 @@ q: str | None = None === "Python 3.8+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать `Annotated` версию, если это возможно. ```Python hl_lines="27" {!> ../../../docs_src/body_multiple_params/tutorial004.py!} ``` -!!! Информация +!!! info "Информация" `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. ## Добавление одного body-параметра @@ -258,7 +258,7 @@ item: Item = Body(embed=True) === "Python 3.10+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать `Annotated` версию, если это возможно. ```Python hl_lines="15" @@ -267,7 +267,7 @@ item: Item = Body(embed=True) === "Python 3.8+ non-Annotated" - !!! Заметка + !!! tip "Заметка" Рекомендуется использовать `Annotated` версию, если это возможно. ```Python hl_lines="17" diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 96f80af06..5d0e033fd 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -162,4 +162,4 @@ ## Без Pydantic -Если вы не хотите использовать модели Pydantic, вы все еще можете использовать параметры **тела запроса**. Читайте в документации раздел [Тело - Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +Если вы не хотите использовать модели Pydantic, вы все еще можете использовать параметры **тела запроса**. Читайте в документации раздел [Тело - Несколько параметров: Единичные значения в теле](body-multiple-params.md#_2){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 38709e56d..5fc6a2c1f 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -74,7 +74,7 @@ from myapp import app не будет выполнена. -!!! Информация +!!! info "Информация" Для получения дополнительной информации, ознакомьтесь с <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">официальной документацией Python</a>. ## Запуск вашего кода с помощью отладчика diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index ad6e835e5..9fce46b97 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -84,13 +84,13 @@ И в конце она возвращает `dict`, содержащий эти значения. -!!! Информация +!!! info "Информация" **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. - Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. + Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. ### Import `Depends` diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index b46f235bc..8a0876bb4 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -310,7 +310,7 @@ https://example.com/items/foo ``` !!! note "Технические детали" - Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. ### Шаг 5: верните результат diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 468e08917..0c6940d0e 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -65,7 +65,7 @@ ``` !!! info "Дополнительная информация" - Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#tags){.internal-link target=_blank}. + Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. ### Проверьте документацию diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index bd2c29d0a..0baf51fa9 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -47,7 +47,7 @@ Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. - Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. + Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. ## Определите метаданные diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 6e885cb65..f6e18f971 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -77,7 +77,7 @@ http://127.0.0.1:8000/items/?skip=20 В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. -!!! Важно +!!! check "Важно" Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. ## Преобразование типа параметра запроса @@ -221,5 +221,5 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, типа `int` и со значением по умолчанию `0`. * `limit`, необязательный `int`. -!!! подсказка - Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#predefined-values){.internal-link target=_blank}. +!!! tip "Подсказка" + Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index ec09eb5a3..afe2075d9 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 "Технические детали" Вы также можете использовать `from starlette.staticfiles import StaticFiles`. **FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index ca47a6f51..4772660df 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -50,7 +50,7 @@ ### Файл приложения **FastAPI** -Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](./bigger-applications.md){.internal-link target=_blank}: +Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](bigger-applications.md){.internal-link target=_blank}: ``` . diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md index aab939189..c7bedffd1 100644 --- a/docs/tr/docs/async.md +++ b/docs/tr/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -!!! not +!!! note "Not" Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. --- @@ -376,7 +376,7 @@ FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir p Yukarıda açıklanan şekilde çalışmayan başka bir asenkron framework'den geliyorsanız ve küçük bir performans kazancı (yaklaşık 100 nanosaniye) için "def" ile *path fonksiyonu* tanımlamaya alışkınsanız, **FastAPI**'de tam tersi olacağını unutmayın. Bu durumlarda, *path fonksiyonu* <abbr title="Input/Output: disk okuma veya yazma, ağ iletişimleri.">G/Ç</abbr> engelleyen durum oluşturmadıkça "async def" kullanmak daha iyidir. -Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](index.md#performance){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. +Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](index.md#performans){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. ### Bagımlılıklar diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index 1cda8c7fb..b964aba4d 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Özelikler ## FastAPI özellikleri diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index afbb27f7d..1c72595c5 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index a0d32c86e..ac3111136 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. -!!! not +!!! note "Not" Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. ## Motivasyon @@ -172,7 +172,7 @@ Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli para {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! ipucu +!!! tip "Ipucu" Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. Bu durumda `str`, `List`e iletilen tür parametresidir. diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md index aa3915557..682f8332c 100644 --- a/docs/tr/docs/tutorial/query-params.md +++ b/docs/tr/docs/tutorial/query-params.md @@ -224,4 +224,4 @@ Bu durumda, 3 tane sorgu parametresi var olacaktır: * `limit`, isteğe bağlı bir `int`. !!! tip "İpucu" - Ayrıca, [Yol Parametrelerinde](path-params.md#predefined-values){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. + 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/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index bdb62513e..16cc0d875 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -30,11 +30,11 @@ Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. -!!! Примітка +!!! note "Примітка" Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Мати автоматичний веб-інтерфейс документації API. ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> @@ -51,7 +51,7 @@ Flask — це «мікрофреймворк», він не включає ін Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. -!!! Переглянте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. Мати просту та легку у використанні систему маршрутизації. @@ -91,7 +91,7 @@ def read_url(): Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" * Майте простий та інтуїтивно зрозумілий API. * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. * Розумні параметри за замовчуванням, але потужні налаштування. @@ -109,7 +109,7 @@ def read_url(): Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. Інтегрувати інструменти інтерфейсу на основі стандартів: @@ -135,7 +135,7 @@ Marshmallow створено для забезпечення цих функці Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну <abbr title="визначення того, як дані повинні бути сформовані">схему</abbr>, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -148,10 +148,10 @@ Webargs — це інструмент, створений, щоб забезпе Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. -!!! Інформація +!!! info "Інформація" Webargs був створений тими ж розробниками Marshmallow. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Мати автоматичну перевірку даних вхідного запиту. ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -172,11 +172,11 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. -!!! Інформація +!!! info "Інформація" APISpec був створений тими ж розробниками Marshmallow. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Підтримувати відкритий стандарт API, OpenAPI. ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -199,10 +199,10 @@ Marshmallow і Webargs забезпечують перевірку, аналіз І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. -!!! Інформація +!!! info "Інформація" Flask-apispec був створений тими ж розробниками Marshmallow. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (та <a href="https://angular.io/ " class="external-link" target="_blank">Angular</a>) @@ -219,7 +219,7 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Використовувати типи Python, щоб мати чудову підтримку редактора. Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. @@ -228,12 +228,12 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. -!!! Примітка "Технічні деталі" +!!! note "Технічні деталі" Він використовував <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Знайти спосіб отримати божевільну продуктивність. Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). @@ -246,7 +246,7 @@ Falcon — ще один високопродуктивний фреймворк Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Знайти способи отримати чудову продуктивність. Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. @@ -269,7 +269,7 @@ Falcon — ще один високопродуктивний фреймворк Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). @@ -288,10 +288,10 @@ Hug був одним із перших фреймворків, який реа Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. -!!! Інформація +!!! info "Інформація" Hug створив Тімоті Крослі, той самий творець <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, чудовий інструмент для автоматичного сортування імпорту у файлах Python. -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. @@ -322,14 +322,14 @@ Hug був одним із перших фреймворків, який реа Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. -!!! Інформація +!!! info "Інформація" APIStar створив Том Крісті. Той самий хлопець, який створив: * Django REST Framework * Starlette (на якому базується **FastAPI**) * Uvicorn (використовується Starlette і **FastAPI**) -!!! Перегляньте "Надихнуло **FastAPI** на" +!!! check "Надихнуло **FastAPI** на" Існувати. Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. @@ -348,7 +348,7 @@ Pydantic — це бібліотека для визначення переві Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. -!!! Перегляньте "**FastAPI** використовує його для" +!!! check "**FastAPI** використовує його для" Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. @@ -380,12 +380,12 @@ Starlette надає всі основні функції веб-мікрофр Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. -!!! Примітка "Технічні деталі" +!!! note "Технічні деталі" ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. -!!! Перегляньте "**FastAPI** використовує його для" +!!! check "**FastAPI** використовує його для" Керування всіма основними веб-частинами. Додавання функцій зверху. Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. @@ -400,7 +400,7 @@ Uvicorn — це блискавичний сервер ASGI, побудован Це рекомендований сервер для Starlette і **FastAPI**. -!!! Перегляньте "**FastAPI** рекомендує це як" +!!! check "**FastAPI** рекомендує це як" Основний веб-сервер для запуску програм **FastAPI**. Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md index f7d0220b5..152a7b098 100644 --- a/docs/uk/docs/fastapi-people.md +++ b/docs/uk/docs/fastapi-people.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Люди FastAPI FastAPI має дивовижну спільноту, яка вітає людей різного походження. @@ -28,7 +33,7 @@ FastAPI має дивовижну спільноту, яка вітає люде Це люди, які: -* [Допомагають іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. +* [Допомагають іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. * [Створюють пул реквести](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. * Переглядають пул реквести, [особливо важливо для перекладів](contributing.md#translations){.internal-link target=_blank}. @@ -36,7 +41,7 @@ FastAPI має дивовижну спільноту, яка вітає люде ## Найбільш активні користувачі минулого місяця -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} протягом минулого місяця. ☕ +Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом минулого місяця. ☕ {% if people %} <div class="user-list user-list-center"> @@ -52,7 +57,7 @@ FastAPI має дивовижну спільноту, яка вітає люде Ось **експерти FastAPI**. 🤓 -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} протягом *всього часу*. +Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом *всього часу*. Вони зарекомендували себе як експерти, допомагаючи багатьом іншим. ✨ diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index e767db2fb..d0adadff3 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -168,7 +168,7 @@ John Doe З модуля `typing`, імпортуємо `List` (з великої літери `L`): - ``` Python hl_lines="1" + ```Python hl_lines="1" {!> ../../../docs_src/python_types/tutorial006.py!} ``` diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index b6583341f..49321ff11 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -38,5 +38,5 @@ Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. -!!! Примітка +!!! note "Примітка" `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md index 9edb1c8fa..fe75591dc 100644 --- a/docs/vi/docs/features.md +++ b/docs/vi/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # Tính năng ## Tính năng của FastAPI diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 3ade853e2..eb078bc4a 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> @@ -31,7 +40,7 @@ FastAPI là một web framework hiện đại, hiệu năng cao để xây dựn Những tính năng như: -* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#performance). +* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#hieu-nang). * **Code nhanh**: Tăng tốc độ phát triển tính năng từ 200% tới 300%. * * **Ít lỗi hơn**: Giảm khoảng 40% những lỗi phát sinh bởi con người (nhà phát triển). * * **Trực giác tốt hơn**: Được các trình soạn thảo hỗ tuyệt vời. <abbr title="như auto-complete, autocompletion, IntelliSense">Completion</abbr> mọi nơi. Ít thời gian gỡ lỗi. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index b2a399aa5..84d14de55 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -186,7 +186,7 @@ Ví dụ, hãy định nghĩa một biến là `list` các `str`. Từ `typing`, import `List` (với chữ cái `L` viết hoa): - ``` Python hl_lines="1" + ```Python hl_lines="1" {!> ../../../docs_src/python_types/tutorial006.py!} ``` diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 5684f0a6a..c3c709350 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> @@ -31,7 +40,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b Àwọn ẹya pàtàkì ni: -* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#performance). +* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#isesi). * **Ó yára láti kóòdù**: O mu iyara pọ si láti kọ àwọn ẹya tuntun kóòdù nipasẹ "Igba ìdá ọgọ́rùn-ún" (i.e. 200%) si "ọ̀ọ́dúrún ìdá ọgọ́rùn-ún" (i.e. 300%). * **Àìtọ́ kékeré**: O n din aṣiṣe ku bi ọgbon ìdá ọgọ́rùn-ún (i.e. 40%) ti eda eniyan (oṣiṣẹ kóòdù) fa. * * **Ọgbọ́n àti ìmọ̀**: Atilẹyin olootu nla. <abbr title="a tun le pe ni olùrànlọ́wọ́ alaifiọwọkan alaifọwọyi, olùpari iṣẹ-ṣiṣe, Oloye">Ìparí</abbr> nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà. diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 738bd7119..17fc2830a 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -346,6 +346,6 @@ $ uvicorn main:app --root-path /api/v1 ## 挂载子应用 -如需挂载子应用(详见 [子应用 - 挂载](./sub-applications.md){.internal-link target=_blank}),也要通过 `root_path` 使用代理,这与正常应用一样,别无二致。 +如需挂载子应用(详见 [子应用 - 挂载](sub-applications.md){.internal-link target=_blank}),也要通过 `root_path` 使用代理,这与正常应用一样,别无二致。 FastAPI 在内部使用 `root_path`,因此子应用也可以正常运行。✨ diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index 6017b8ef0..8e5fa7d12 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -6,7 +6,7 @@ !!! warning "警告" - **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](./sub-applications.md){.internal-link target=_blank}中的事件处理器。 + **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 ## `startup` 事件 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index 85dab15ac..229efffcb 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -25,7 +25,7 @@ ``` -!!! 注意 "技术细节" +!!! note "技术细节" 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md index 55651def5..a26301b50 100644 --- a/docs/zh/docs/advanced/sub-applications.md +++ b/docs/zh/docs/advanced/sub-applications.md @@ -70,4 +70,4 @@ $ uvicorn main:app --reload 并且子应用还可以再挂载子应用,一切都会正常运行,FastAPI 可以自动处理所有 `root_path`。 -关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](./behind-a-proxy.md){.internal-link target=_blank}一章。 +关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](behind-a-proxy.md){.internal-link target=_blank}一章。 diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index ad71280fc..179ec88aa 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # 包含 WSGI - Flask,Django,其它 -您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。 +您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。 为此, 您可以使用 `WSGIMiddleware` 来包装你的 WSGI 应用,如:Flask,Django,等等。 diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index ed0e6e497..b34ef63e0 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -405,15 +405,15 @@ Starlette (和 **FastAPI**) 是基于 <a href="https://anyio.readthedocs.io/ 如果您使用过另一个不以上述方式工作的异步框架,并且您习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 <abbr title="输入/输出:磁盘读写,网络通讯.">I/O</abbr> 的代码。 -在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](index.md#performance){.internal-link target=_blank}。 +在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](index.md#_11){.internal-link target=_blank}。 ### 依赖 -这同样适用于[依赖](./tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。 +这同样适用于[依赖](tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。 ### 子依赖 -你可以拥有多个相互依赖的依赖以及[子依赖](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。 +你可以拥有多个相互依赖的依赖以及[子依赖](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。 ### 其他函数 diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md index 9c4aaa64b..86d995b75 100644 --- a/docs/zh/docs/deployment/concepts.md +++ b/docs/zh/docs/deployment/concepts.md @@ -25,7 +25,7 @@ ## 安全性 - HTTPS -在[上一章有关 HTTPS](./https.md){.internal-link target=_blank} 中,我们了解了 HTTPS 如何为您的 API 提供加密。 +在[上一章有关 HTTPS](https.md){.internal-link target=_blank} 中,我们了解了 HTTPS 如何为您的 API 提供加密。 我们还看到,HTTPS 通常由应用程序服务器的**外部**组件(**TLS 终止代理**)提供。 @@ -191,7 +191,7 @@ ### 工作进程和端口 -还记得文档 [About HTTPS](./https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗? +还记得文档 [About HTTPS](https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗? 现在仍然是对的。 @@ -249,7 +249,7 @@ 如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 - 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 ## 启动之前的步骤 @@ -284,7 +284,7 @@ !!! tip - 我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + 我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 ## 资源利用率 diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md index 0f8906704..782c6d578 100644 --- a/docs/zh/docs/deployment/docker.md +++ b/docs/zh/docs/deployment/docker.md @@ -5,7 +5,7 @@ 使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。 !!! tip - 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#为-fastapi-构建-docker-镜像)。 + 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。 <details> @@ -114,7 +114,7 @@ Docker 一直是创建和管理**容器镜像**和**容器**的主要工具之 最常见的方法是创建一个`requirements.txt`文件,其中每行包含一个包名称和它的版本。 -你当然也可以使用在[关于 FastAPI 版本](./versions.md){.internal-link target=_blank} 中讲到的方法来设置版本范围。 +你当然也可以使用在[关于 FastAPI 版本](versions.md){.internal-link target=_blank} 中讲到的方法来设置版本范围。 例如,你的`requirements.txt`可能如下所示: @@ -208,7 +208,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 选项告诉 `pip` 不要在本地保存下载的包,因为只有当 `pip` 再次运行以安装相同的包时才会这样,但在与容器一起工作时情况并非如此。 - !!! 笔记 + !!! note "笔记" `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 `--upgrade` 选项告诉 `pip` 升级软件包(如果已经安装)。 @@ -387,7 +387,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 部署概念 -我们再谈谈容器方面的一些相同的[部署概念](./concepts.md){.internal-link target=_blank}。 +我们再谈谈容器方面的一些相同的[部署概念](concepts.md){.internal-link target=_blank}。 容器主要是一种简化**构建和部署**应用程序的过程的工具,但它们并不强制执行特定的方法来处理这些**部署概念**,并且有几种可能的策略。 @@ -537,7 +537,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 带有 Gunicorn 的官方 Docker 镜像 - Uvicorn -有一个官方 Docker 镜像,其中包含与 Uvicorn worker一起运行的 Gunicorn,如上一章所述:[服务器工作线程 - Gunicorn 与 Uvicorn](./server-workers.md){.internal-link target=_blank}。 +有一个官方 Docker 镜像,其中包含与 Uvicorn worker一起运行的 Gunicorn,如上一章所述:[服务器工作线程 - Gunicorn 与 Uvicorn](server-workers.md){.internal-link target=_blank}。 该镜像主要在上述情况下有用:[具有多个进程和特殊情况的容器](#containers-with-multiple-processes-and-special-cases)。 diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md index ee3de9b5d..330ddb3d7 100644 --- a/docs/zh/docs/deployment/server-workers.md +++ b/docs/zh/docs/deployment/server-workers.md @@ -13,12 +13,12 @@ 部署应用程序时,您可能希望进行一些**进程复制**,以利用**多核**并能够处理更多请求。 -正如您在上一章有关[部署概念](./concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 +正如您在上一章有关[部署概念](concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 在这里我将向您展示如何将 <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> 与 **Uvicorn worker 进程** 一起使用。 !!! info - 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 @@ -169,7 +169,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 容器和 Docker -在关于 [容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 +在关于 [容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 我还将向您展示 **官方 Docker 镜像**,其中包括 **Gunicorn 和 Uvicorn worker** 以及一些对简单情况有用的默认配置。 diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md index 7ef3f3c1a..6cf35253c 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # FastAPI 社区 FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋友。 @@ -18,7 +23,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 </div> {% endif %} -我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 阅读有关此内容的更多信息。 +我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#_2){.internal-link target=_blank} 阅读有关此内容的更多信息。 ...但是在这里我想向您展示社区。 @@ -28,15 +33,15 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 这些人: -* [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 -* [创建 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* 审核 Pull Requests, 对于 [翻译](contributing.md#translations){.internal-link target=_blank} 尤为重要。 +* [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 +* [创建 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 +* 审核 Pull Requests, 对于 [翻译](contributing.md#_8){.internal-link target=_blank} 尤为重要。 向他们致以掌声。 👏 🙇 ## 上个月最活跃的用户 -上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 +上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 {% if people %} <div class="user-list user-list-center"> @@ -52,7 +57,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 以下是 **FastAPI 专家**。 🤓 -这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 +这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 他们通过帮助许多人而被证明是专家。✨ @@ -70,7 +75,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 以下是 **杰出的贡献者**。 👷 -这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 +这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 他们贡献了源代码,文档,翻译等。 📦 @@ -92,7 +97,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 ### 翻译审核 -我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#translations){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。 +我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。 --- diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index d8190032f..b613aaf72 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -1,3 +1,8 @@ +--- +hide: + - navigation +--- + # 特性 ## FastAPI 特性 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index 1a9aa57d0..d2a210c39 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -72,7 +72,7 @@ 您可以查看<a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">现有 issues</a>,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓 -如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#experts){.internal-link target=_blank}。🎉 +如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#_3){.internal-link target=_blank}。🎉 ## 监听 GitHub 资源库 @@ -98,7 +98,7 @@ * 修改文档错别字 * <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">编辑这个文件</a>,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成 * 注意,添加的链接要放在对应区块的开头 -* [翻译文档](contributing.md#translations){.internal-link target=_blank} +* [翻译文档](contributing.md#_8){.internal-link target=_blank} * 审阅别人翻译的文档 * 添加新的文档内容 * 修复现有问题/Bug @@ -110,7 +110,7 @@ !!! tip "提示" - 如有问题,请在 <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank}的帮助。 + 如有问题,请在 <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 聊天室仅供闲聊。 @@ -120,7 +120,7 @@ GitHub Issues 里提供了模板,指引您提出正确的问题,有利于获得优质的回答,甚至可能解决您还没有想到的问题。而且就算答疑解惑要耗费不少时间,我还是会尽量在 GitHub 里回答问题。但在聊天室里,我就没功夫这么做了。😅 -聊天室里的聊天内容也不如 GitHub 里好搜索,聊天里的问答很容易就找不到了。只有在 GitHub Issues 里的问答才能帮助您成为 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank},在 GitHub Issues 中为您带来更多关注。 +聊天室里的聊天内容也不如 GitHub 里好搜索,聊天里的问答很容易就找不到了。只有在 GitHub Issues 里的问答才能帮助您成为 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank},在 GitHub Issues 中为您带来更多关注。 另一方面,聊天室里有成千上万的用户,在这里,您有很大可能遇到聊得来的人。😄 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index a480d6640..eda2e8fd7 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -1,3 +1,12 @@ +--- +hide: + - navigation +--- + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + <p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 138959566..422cd7c16 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -119,7 +119,7 @@ !!! tip 我们正在使用虚构的请求首部来简化此示例。 - 但在实际情况下,使用集成的[安全性实用工具](./security/index.md){.internal-link target=_blank}会得到更好的效果。 + 但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。 ## 其他使用 `APIRouter` 的模块 diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 43f20f8fc..e529fc914 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` 知名,也怎么不常用。 diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index fa8b54d02..65d459cd1 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -213,4 +213,4 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 ## 不使用 Pydantic -即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#singular-values-in-body){.internal-link target=\_blank}。 +即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#_2){.internal-link target=\_blank}。 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index e24b9409f..4159d626e 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,10 +4,10 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” 为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 -!!! 提示 +!!! tip "提示" 确保只使用一次 `yield` 。 -!!! 注意 "技术细节" +!!! note "技术细节" 任何一个可以与以下内容一起使用的函数: @@ -41,7 +41,7 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! 提示 +!!! tip "提示" 您可以使用 `async` 或普通函数。 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 8170e6ecc..59a4af86e 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -43,7 +43,7 @@ 注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 -!!! 提示 +!!! tip "提示" 不必为你使用的所有标签都添加元数据。 ### 使用你的标签 @@ -54,7 +54,7 @@ {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! 信息 +!!! info "信息" 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 ### 查看文档 diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index 308dd68a4..77138de51 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -206,5 +206,4 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `limit`,可选的 `int` 类型参数 !!! tip "提示" - - 还可以像在[路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。 + 还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。 diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index c7f46177f..751767ea2 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -144,7 +144,7 @@ UserInDB( !!! info "说明" - `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。 + `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 ## 返回 Token diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md index 77fff7596..69841978c 100644 --- a/docs/zh/docs/tutorial/testing.md +++ b/docs/zh/docs/tutorial/testing.md @@ -8,7 +8,7 @@ ## 使用 `TestClient` -!!! 信息 +!!! info "信息" 要使用 `TestClient`,先要安装 <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. 例:`pip install httpx`. @@ -27,7 +27,7 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! 提示 +!!! tip "提示" 注意测试函数是普通的 `def`,不是 `async def`。 还有client的调用也是普通的调用,不是用 `await`。 @@ -39,7 +39,7 @@ **FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 -!!! 提示 +!!! tip "提示" 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 ## 分离测试 @@ -50,7 +50,7 @@ ### **FastAPI** app 文件 -假设你有一个像 [更大的应用](./bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构: +假设你有一个像 [更大的应用](bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构: ``` . @@ -130,7 +130,7 @@ === "Python 3.10+ non-Annotated" - !!! tip + !!! tip "提示" Prefer to use the `Annotated` version if possible. ```Python @@ -139,7 +139,7 @@ === "Python 3.8+ non-Annotated" - !!! tip + !!! tip "提示" Prefer to use the `Annotated` version if possible. ```Python @@ -168,7 +168,7 @@ 关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX 文档</a>. -!!! 信息 +!!! info "信息" 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 From 610534b7034d96ba56b83e2e2f57787e69a5fd84 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Apr 2024 19:53:46 +0000 Subject: [PATCH 397/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 836793d3b..9dcfdc153 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Tweak docs and translations links, typos, format. PR [#11389](https://github.com/tiangolo/fastapi/pull/11389) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Fix typo in `docs/es/docs/async.md`. PR [#11400](https://github.com/tiangolo/fastapi/pull/11400) by [@fabianfalon](https://github.com/fabianfalon). * 📝 Update OpenAPI client generation docs to use `@hey-api/openapi-ts`. PR [#11339](https://github.com/tiangolo/fastapi/pull/11339) by [@jordanshatford](https://github.com/jordanshatford). From f08234f35aa54a9038f239d064c5eebe593ee1ef Mon Sep 17 00:00:00 2001 From: Waket Zheng <waketzheng@gmail.com> Date: Fri, 19 Apr 2024 05:53:24 +0800 Subject: [PATCH 398/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/index.html`=20(#11430)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/zh/docs/index.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index eda2e8fd7..dfe5af827 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -23,6 +23,9 @@ hide: <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> </a> +<a href="https://pypi.org/project/fastapi" target="_blank"> + <img src="https://img.shields.io/pypi/pyversions/fastapi.svg?color=%2334D058" alt="Supported Python versions"> +</a> </p> --- @@ -196,7 +199,7 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Note**: -如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">关于 `async` 和 `await` 的部分</a>。 +如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 <a href="https://fastapi.tiangolo.com/zh/async/#in-a-hurry" target="_blank">关于 `async` 和 `await` 的部分</a>。 </details> @@ -419,7 +422,7 @@ item: Item  -<a href="https://fastapi.tiangolo.com/tutorial/">教程 - 用户指南</a> 中有包含更多特性的更完整示例。 +<a href="https://fastapi.tiangolo.com/zh/tutorial/">教程 - 用户指南</a> 中有包含更多特性的更完整示例。 **剧透警告**: 教程 - 用户指南中的内容有: @@ -440,7 +443,7 @@ item: Item 独立机构 TechEmpower 所作的基准测试结果显示,基于 Uvicorn 运行的 **FastAPI** 程序是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python web 框架之一</a>,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用了它们)。(*) -想了解更多,请查阅 <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">基准测试</a> 章节。 +想了解更多,请查阅 <a href="https://fastapi.tiangolo.com/zh/benchmarks/" class="internal-link" target="_blank">基准测试</a> 章节。 ## 可选依赖 @@ -463,7 +466,7 @@ item: Item * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - 用于加载和运行你的应用程序的服务器。 * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - 使用 `ORJSONResponse` 时安装。 -你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。 +你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。 ## 许可协议 From 071b8f27f965c29caeab6e04b17f7b9201b090e4 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Apr 2024 21:53:48 +0000 Subject: [PATCH 399/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9dcfdc153..15f75efb1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/index.html`. PR [#11430](https://github.com/tiangolo/fastapi/pull/11430) by [@waketzheng](https://github.com/waketzheng). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#11411](https://github.com/tiangolo/fastapi/pull/11411) by [@anton2yakovlev](https://github.com/anton2yakovlev). * 🌐 Add Portuguese translations for `learn/index.md` `resources/index.md` `help/index.md` `about/index.md`. PR [#10807](https://github.com/tiangolo/fastapi/pull/10807) by [@nazarepiedady](https://github.com/nazarepiedady). * 🌐 Update Russian translations for deployments docs. PR [#11271](https://github.com/tiangolo/fastapi/pull/11271) by [@Lufa1u](https://github.com/Lufa1u). From 09e4859cab3354dd17c5884806bbc5a1330380dd Mon Sep 17 00:00:00 2001 From: arjwilliams <arjwilliams@yahoo.co.uk> Date: Thu, 18 Apr 2024 22:56:59 +0100 Subject: [PATCH 400/846] =?UTF-8?q?=F0=9F=90=9B=20Fix=20support=20for=20qu?= =?UTF-8?q?ery=20parameters=20with=20list=20types,=20handle=20JSON=20encod?= =?UTF-8?q?ing=20Pydantic=20`UndefinedType`=20(#9929)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Andrew Williams <Andrew.Williams@contemi.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- fastapi/encoders.py | 4 +- tests/main.py | 12 ++++- tests/test_application.py | 85 ++++++++++++++++++++++++++++++++++ tests/test_jsonable_encoder.py | 8 +++- tests/test_query.py | 23 +++++++++ 5 files changed, 129 insertions(+), 3 deletions(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 2f9c4a4f7..451ea0760 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -24,7 +24,7 @@ from pydantic.networks import AnyUrl, NameEmail from pydantic.types import SecretBytes, SecretStr from typing_extensions import Annotated, Doc -from ._compat import PYDANTIC_V2, Url, _model_dump +from ._compat import PYDANTIC_V2, UndefinedType, Url, _model_dump # Taken from Pydantic v1 as is @@ -259,6 +259,8 @@ def jsonable_encoder( return str(obj) if isinstance(obj, (str, int, float, type(None))): return obj + if isinstance(obj, UndefinedType): + return None if isinstance(obj, dict): encoded_dict = {} allowed_keys = set(obj.keys()) diff --git a/tests/main.py b/tests/main.py index 15760c039..6927eab61 100644 --- a/tests/main.py +++ b/tests/main.py @@ -1,5 +1,5 @@ import http -from typing import FrozenSet, Optional +from typing import FrozenSet, List, Optional from fastapi import FastAPI, Path, Query @@ -192,3 +192,13 @@ def get_enum_status_code(): @app.get("/query/frozenset") def get_query_type_frozenset(query: FrozenSet[int] = Query(...)): return ",".join(map(str, sorted(query))) + + +@app.get("/query/list") +def get_query_list(device_ids: List[int] = Query()) -> List[int]: + return device_ids + + +@app.get("/query/list-default") +def get_query_list_default(device_ids: List[int] = Query(default=[])) -> List[int]: + return device_ids diff --git a/tests/test_application.py b/tests/test_application.py index ea7a80128..5c62f5f6e 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -1163,6 +1163,91 @@ def test_openapi_schema(): }, } }, + "/query/list": { + "get": { + "summary": "Get Query List", + "operationId": "get_query_list_query_list_get", + "parameters": [ + { + "name": "device_ids", + "in": "query", + "required": True, + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Device Ids", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Response Get Query List Query List Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/query/list-default": { + "get": { + "summary": "Get Query List Default", + "operationId": "get_query_list_default_query_list_default_get", + "parameters": [ + { + "name": "device_ids", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "integer"}, + "default": [], + "title": "Device Ids", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Response Get Query List Default Query List Default Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 7c8338ff3..1906d6bf1 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -7,7 +7,7 @@ from pathlib import PurePath, PurePosixPath, PureWindowsPath from typing import Optional import pytest -from fastapi._compat import PYDANTIC_V2 +from fastapi._compat import PYDANTIC_V2, Undefined from fastapi.encoders import jsonable_encoder from pydantic import BaseModel, Field, ValidationError @@ -310,3 +310,9 @@ def test_encode_deque_encodes_child_models(): dq = deque([Model(test="test")]) assert jsonable_encoder(dq)[0]["test"] == "test" + + +@needs_pydanticv2 +def test_encode_pydantic_undefined(): + data = {"value": Undefined} + assert jsonable_encoder(data) == {"value": None} diff --git a/tests/test_query.py b/tests/test_query.py index 2ce4fcd0b..57f551d2a 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -396,3 +396,26 @@ def test_query_frozenset_query_1_query_1_query_2(): response = client.get("/query/frozenset/?query=1&query=1&query=2") assert response.status_code == 200 assert response.json() == "1,2" + + +def test_query_list(): + response = client.get("/query/list/?device_ids=1&device_ids=2") + assert response.status_code == 200 + assert response.json() == [1, 2] + + +def test_query_list_empty(): + response = client.get("/query/list/") + assert response.status_code == 422 + + +def test_query_list_default(): + response = client.get("/query/list-default/?device_ids=1&device_ids=2") + assert response.status_code == 200 + assert response.json() == [1, 2] + + +def test_query_list_default_empty(): + response = client.get("/query/list-default/") + assert response.status_code == 200 + assert response.json() == [] From 5815fa58fb2011b69fe10bfb17d7ca1401fd8314 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Apr 2024 21:57:19 +0000 Subject: [PATCH 401/846] =?UTF-8?q?=F0=9F=93=9D=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 15f75efb1..f7342373b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Fix support for query parameters with list types, handle JSON encoding Pydantic `UndefinedType`. PR [#9929](https://github.com/tiangolo/fastapi/pull/9929) by [@arjwilliams](https://github.com/arjwilliams). + ### Refactors * ✨ Add support for Pydantic's 2.7 new deprecated Field parameter, remove URL from validation errors response. PR [#11461](https://github.com/tiangolo/fastapi/pull/11461) by [@tiangolo](https://github.com/tiangolo). From 74cc33d16b70a910e6c3a2dcd8be586c2e6b66c4 Mon Sep 17 00:00:00 2001 From: Paul <77851879+JoeTanto2@users.noreply.github.com> Date: Thu, 18 Apr 2024 18:49:33 -0400 Subject: [PATCH 402/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Simplify=20Pydanti?= =?UTF-8?q?c=20configs=20in=20OpenAPI=20models=20in=20`fastapi/openapi/mod?= =?UTF-8?q?els.py`=20(#10886)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- fastapi/openapi/models.py | 222 +++++--------------------------------- 1 file changed, 28 insertions(+), 194 deletions(-) diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py index 5f3bdbb20..ed07b40f5 100644 --- a/fastapi/openapi/models.py +++ b/fastapi/openapi/models.py @@ -55,11 +55,7 @@ except ImportError: # pragma: no cover return with_info_plain_validator_function(cls._validate) -class Contact(BaseModel): - name: Optional[str] = None - url: Optional[AnyUrl] = None - email: Optional[EmailStr] = None - +class BaseModelWithConfig(BaseModel): if PYDANTIC_V2: model_config = {"extra": "allow"} @@ -69,21 +65,19 @@ class Contact(BaseModel): extra = "allow" -class License(BaseModel): - name: str - identifier: Optional[str] = None +class Contact(BaseModelWithConfig): + name: Optional[str] = None url: Optional[AnyUrl] = None + email: Optional[EmailStr] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" +class License(BaseModelWithConfig): + name: str + identifier: Optional[str] = None + url: Optional[AnyUrl] = None -class Info(BaseModel): +class Info(BaseModelWithConfig): title: str summary: Optional[str] = None description: Optional[str] = None @@ -92,42 +86,18 @@ class Info(BaseModel): license: Optional[License] = None version: str - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class ServerVariable(BaseModel): +class ServerVariable(BaseModelWithConfig): enum: Annotated[Optional[List[str]], Field(min_length=1)] = None default: str description: Optional[str] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class Server(BaseModel): +class Server(BaseModelWithConfig): url: Union[AnyUrl, str] description: Optional[str] = None variables: Optional[Dict[str, ServerVariable]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class Reference(BaseModel): ref: str = Field(alias="$ref") @@ -138,36 +108,20 @@ class Discriminator(BaseModel): mapping: Optional[Dict[str, str]] = None -class XML(BaseModel): +class XML(BaseModelWithConfig): name: Optional[str] = None namespace: Optional[str] = None prefix: Optional[str] = None attribute: Optional[bool] = None wrapped: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class ExternalDocumentation(BaseModel): +class ExternalDocumentation(BaseModelWithConfig): description: Optional[str] = None url: AnyUrl - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Schema(BaseModel): +class Schema(BaseModelWithConfig): # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu # Core Vocabulary schema_: Optional[str] = Field(default=None, alias="$schema") @@ -253,14 +207,6 @@ class Schema(BaseModel): ), ] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - # Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents # A JSON Schema MUST be an object or a boolean. @@ -289,38 +235,22 @@ class ParameterInType(Enum): cookie = "cookie" -class Encoding(BaseModel): +class Encoding(BaseModelWithConfig): contentType: Optional[str] = None headers: Optional[Dict[str, Union["Header", Reference]]] = None style: Optional[str] = None explode: Optional[bool] = None allowReserved: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class MediaType(BaseModel): +class MediaType(BaseModelWithConfig): schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None encoding: Optional[Dict[str, Encoding]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class ParameterBase(BaseModel): +class ParameterBase(BaseModelWithConfig): description: Optional[str] = None required: Optional[bool] = None deprecated: Optional[bool] = None @@ -334,14 +264,6 @@ class ParameterBase(BaseModel): # Serialization rules for more complex scenarios content: Optional[Dict[str, MediaType]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class Parameter(ParameterBase): name: str @@ -352,21 +274,13 @@ class Header(ParameterBase): pass -class RequestBody(BaseModel): +class RequestBody(BaseModelWithConfig): description: Optional[str] = None content: Dict[str, MediaType] required: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class Link(BaseModel): +class Link(BaseModelWithConfig): operationRef: Optional[str] = None operationId: Optional[str] = None parameters: Optional[Dict[str, Union[Any, str]]] = None @@ -374,31 +288,15 @@ class Link(BaseModel): description: Optional[str] = None server: Optional[Server] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Response(BaseModel): +class Response(BaseModelWithConfig): description: str headers: Optional[Dict[str, Union[Header, Reference]]] = None content: Optional[Dict[str, MediaType]] = None links: Optional[Dict[str, Union[Link, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Operation(BaseModel): +class Operation(BaseModelWithConfig): tags: Optional[List[str]] = None summary: Optional[str] = None description: Optional[str] = None @@ -413,16 +311,8 @@ class Operation(BaseModel): security: Optional[List[Dict[str, List[str]]]] = None servers: Optional[List[Server]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class PathItem(BaseModel): +class PathItem(BaseModelWithConfig): ref: Optional[str] = Field(default=None, alias="$ref") summary: Optional[str] = None description: Optional[str] = None @@ -437,14 +327,6 @@ class PathItem(BaseModel): servers: Optional[List[Server]] = None parameters: Optional[List[Union[Parameter, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class SecuritySchemeType(Enum): apiKey = "apiKey" @@ -453,18 +335,10 @@ class SecuritySchemeType(Enum): openIdConnect = "openIdConnect" -class SecurityBase(BaseModel): +class SecurityBase(BaseModelWithConfig): type_: SecuritySchemeType = Field(alias="type") description: Optional[str] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class APIKeyIn(Enum): query = "query" @@ -488,18 +362,10 @@ class HTTPBearer(HTTPBase): bearerFormat: Optional[str] = None -class OAuthFlow(BaseModel): +class OAuthFlow(BaseModelWithConfig): refreshUrl: Optional[str] = None scopes: Dict[str, str] = {} - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class OAuthFlowImplicit(OAuthFlow): authorizationUrl: str @@ -518,20 +384,12 @@ class OAuthFlowAuthorizationCode(OAuthFlow): tokenUrl: str -class OAuthFlows(BaseModel): +class OAuthFlows(BaseModelWithConfig): implicit: Optional[OAuthFlowImplicit] = None password: Optional[OAuthFlowPassword] = None clientCredentials: Optional[OAuthFlowClientCredentials] = None authorizationCode: Optional[OAuthFlowAuthorizationCode] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class OAuth2(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") @@ -548,7 +406,7 @@ class OpenIdConnect(SecurityBase): SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer] -class Components(BaseModel): +class Components(BaseModelWithConfig): schemas: Optional[Dict[str, Union[Schema, Reference]]] = None responses: Optional[Dict[str, Union[Response, Reference]]] = None parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None @@ -561,30 +419,14 @@ class Components(BaseModel): callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Tag(BaseModel): +class Tag(BaseModelWithConfig): name: str description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class OpenAPI(BaseModel): +class OpenAPI(BaseModelWithConfig): openapi: str info: Info jsonSchemaDialect: Optional[str] = None @@ -597,14 +439,6 @@ class OpenAPI(BaseModel): tags: Optional[List[Tag]] = None externalDocs: Optional[ExternalDocumentation] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - _model_rebuild(Schema) _model_rebuild(Operation) From 8a456451771bdee3108acb63a617e2010cd012a2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Apr 2024 22:49:56 +0000 Subject: [PATCH 403/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f7342373b..49df7a771 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Refactors +* ♻️ Simplify Pydantic configs in OpenAPI models in `fastapi/openapi/models.py`. PR [#10886](https://github.com/tiangolo/fastapi/pull/10886) by [@JoeTanto2](https://github.com/JoeTanto2). * ✨ Add support for Pydantic's 2.7 new deprecated Field parameter, remove URL from validation errors response. PR [#11461](https://github.com/tiangolo/fastapi/pull/11461) by [@tiangolo](https://github.com/tiangolo). ### Docs From a901e2f449e7b940ce9a4844b6605a7993ca7227 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 18 Apr 2024 18:58:47 -0500 Subject: [PATCH 404/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20references=20to?= =?UTF-8?q?=20UJSON=20(#11464)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/bn/docs/index.md | 3 +-- docs/em/docs/index.md | 3 +-- docs/en/docs/index.md | 2 +- docs/es/docs/index.md | 2 +- docs/fa/docs/index.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 | 3 +-- docs/ja/docs/index.md | 2 +- docs/ko/docs/index.md | 2 +- docs/pl/docs/index.md | 2 +- docs/pt/docs/index.md | 2 +- docs/ru/docs/index.md | 2 +- docs/tr/docs/index.md | 2 +- docs/uk/docs/index.md | 2 +- docs/vi/docs/index.md | 3 +-- docs/yo/docs/index.md | 2 +- docs/zh-hant/docs/index.md | 2 +- docs/zh/docs/index.md | 2 +- 21 files changed, 21 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 67275d29d..bcb18ac66 100644 --- a/README.md +++ b/README.md @@ -463,12 +463,12 @@ Used by Starlette: * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. Used by FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. You can install all of these with `pip install "fastapi[all]"`. diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 688f3f95a..bbc3e9a3a 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -439,7 +439,6 @@ item: Item Pydantic দ্বারা ব্যবহৃত: -- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - দ্রুত JSON এর জন্য <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>. - <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - ইমেল যাচাইকরণের জন্য। স্টারলেট দ্বারা ব্যবহৃত: @@ -450,12 +449,12 @@ Pydantic দ্বারা ব্যবহৃত: - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` সহায়তার জন্য প্রয়োজন। - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)। - <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` সহায়তার জন্য প্রয়োজন। -- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। FastAPI / Starlette দ্বারা ব্যবহৃত: - <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে। - <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। +- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। আপনি এই সব ইনস্টল করতে পারেন `pip install fastapi[all]` দিয়ে. diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index cf4fa0def..c4e41ce17 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -454,7 +454,6 @@ item: Item ⚙️ Pydantic: -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - ⏩ 🎻 <abbr title="converting the string that comes from an HTTP request into Python data">"🎻"</abbr>. * <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - 📧 🔬. ⚙️ 💃: @@ -464,12 +463,12 @@ item: Item * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - ✔ 🚥 👆 💚 🐕🦺 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>, ⏮️ `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - ✔ `SessionMiddleware` 🐕🦺. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - ✔ 💃 `SchemaGenerator` 🐕🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. ⚙️ FastAPI / 💃: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - 💽 👈 📐 & 🍦 👆 🈸. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - ✔ 🚥 👆 💚 ⚙️ `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. 👆 💪 ❎ 🌐 👫 ⏮️ `pip install "fastapi[all]"`. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 86b0c699b..a5ed8b330 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -465,12 +465,12 @@ Used by Starlette: * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. Used by FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. You can install all of these with `pip install "fastapi[all]"`. diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 776d98ce5..9fc275caf 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -452,12 +452,12 @@ Usados por Starlette: * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Requerido para dar soporte a `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Requerido para dar soporte a `GraphQLApp`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Requerido si quieres usar `UJSONResponse`. Usado por FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - para el servidor que carga y sirve tu aplicación. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Requerido si quieres usar `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Requerido si quieres usar `UJSONResponse`. Puedes instalarlos con `pip install fastapi[all]`. diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index 71c23b7f7..623bc0f75 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -456,12 +456,12 @@ item: Item * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - در صورتی که از `GraphQLApp` پشتیبانی میکنید. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - در صورتی که بخواهید از `UJSONResponse` استفاده کنید. استفاده شده توسط FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - برای سرور اجرا کننده برنامه وب. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - در صورتی که بخواهید از `ORJSONResponse` استفاده کنید. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - در صورتی که بخواهید از `UJSONResponse` استفاده کنید. میتوان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index eb02e2a0c..324681a74 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -463,12 +463,12 @@ Utilisées par Starlette : * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Obligatoire si vous souhaitez supporter le <abbr title="convertit la chaine de caractère d'une requête HTTP en donnée Python">"décodage"</abbr> de formulaire avec `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Obligatoire pour la prise en charge de `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Obligatoire si vous souhaitez utiliser `UJSONResponse`. Utilisées par FastAPI / Starlette : * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - Pour le serveur qui charge et sert votre application. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Obligatoire si vous voulez utiliser `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Obligatoire si vous souhaitez utiliser `UJSONResponse`. Vous pouvez tout installer avec `pip install fastapi[all]`. diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 8f1f2a124..621126128 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -458,12 +458,12 @@ item: Item - <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - דרוש אם ברצונכם לתמוך ב <abbr title="המרת המחרוזת שמגיעה מבקשת HTTP למידע פייתון">"פרסור"</abbr> טפסים, באצמעות <code dir="ltr">request.form()</code>. - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`. - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI). -- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. בשימוש FastAPI / Starlette: - <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - לשרת שטוען ומגיש את האפליקציה שלכם. - <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`. +- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. תוכלו להתקין את כל אלו באמצעות <code dir="ltr">pip install "fastapi[all]"</code>. diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 75ea88c4d..896db6d1f 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -456,12 +456,12 @@ Starlette által használt: * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Követelmény ha <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>-ot akarsz támogatni, `request.form()`-al. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Követelmény `SessionMiddleware` támogatáshoz. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szükség FastAPI használása esetén). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Követelmény ha `UJSONResponse`-t akarsz használni. FastAPI / Starlette által használt * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - Szerverekhez amíg betöltik és szolgáltatják az applikációdat. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Követelmény ha `ORJSONResponse`-t akarsz használni. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Követelmény ha `UJSONResponse`-t akarsz használni. Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal. diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index a69008d2b..c06d3a174 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -438,7 +438,6 @@ Per approfondire, consulta la sezione <a href="https://fastapi.tiangolo.com/benc Usate da Pydantic: -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - per un <abbr title="convertire la stringa che proviene da una richiesta HTTP in dati Python">"parsing"</abbr> di JSON più veloce. * <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - per la validazione di email. Usate da Starlette: @@ -450,12 +449,12 @@ Usate da Starlette: * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Richiesto per usare `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Richiesto per il supporto di `GraphQLApp`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Richiesto se vuoi usare `UJSONResponse`. Usate da FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - per il server che carica e serve la tua applicazione. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - ichiesto se vuoi usare `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Richiesto se vuoi usare `UJSONResponse`. Puoi installarle tutte con `pip install fastapi[all]`. diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 37cddae5e..a991222cb 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -450,12 +450,12 @@ Starlette によって使用されるもの: - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` サポートのためには必要です。 - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。) - <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` サポートのためには必要です。 -- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse`を使用する場合は必須です。 FastAPI / Starlette に使用されるもの: - <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - アプリケーションをロードしてサーブするサーバーのため。 - <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - `ORJSONResponse`を使用したい場合は必要です。 +- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse`を使用する場合は必須です。 これらは全て `pip install fastapi[all]`でインストールできます。 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 85482718e..dea087332 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -456,12 +456,12 @@ Starlette이 사용하는: * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` 지원을 위해 필요. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` 지원을 위해 필요. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse`를 사용하려면 필요. FastAPI / Starlette이 사용하는: * <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - 애플리케이션을 로드하고 제공하는 서버. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - `ORJSONResponse`을 사용하려면 필요. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse`를 사용하려면 필요. `pip install fastapi[all]`를 통해 이 모두를 설치 할 수 있습니다. diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index b168b9e5e..06fa706bc 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -455,12 +455,12 @@ Używane przez Starlette: * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Wymagany dla wsparcia `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Wymagane dla wsparcia `GraphQLApp`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Wymagane jeżeli chcesz korzystać z `UJSONResponse`. Używane przez FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - jako serwer, który ładuje i obsługuje Twoją aplikację. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Wymagane jeżeli chcesz używać `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Wymagane jeżeli chcesz korzystać z `UJSONResponse`. Możesz zainstalować wszystkie te aplikacje przy pomocy `pip install fastapi[all]`. diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 1a29a9bea..86b77f117 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -449,12 +449,12 @@ Usados por Starlette: * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Necessário para suporte a `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI). * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Necessário para suporte a `GraphQLApp`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Necessário se você quer utilizar `UJSONResponse`. Usados por FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - para o servidor que carrega e serve sua aplicação. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Necessário se você quer utilizar `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Necessário se você quer utilizar `UJSONResponse`. Você pode instalar todas essas dependências com `pip install fastapi[all]`. diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index e9ecfa520..81c3835d9 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -457,12 +457,12 @@ item: Item * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Обязательно, если вы хотите поддерживать форму <abbr title="преобразование строки, полученной из HTTP-запроса, в данные Python">"парсинга"</abbr> с помощью `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Обязательно, для поддержки `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Обязательно, если вы хотите использовать `UJSONResponse`. Используется FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - сервер, который загружает и обслуживает ваше приложение. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Обязательно, если вы хотите использовать `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Обязательно, если вы хотите использовать `UJSONResponse`. Вы можете установить все это с помощью `pip install "fastapi[all]"`. diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 1c72595c5..67a9b4462 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -465,12 +465,12 @@ Starlette tarafında kullanılan: * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Eğer `request.form()` ile form <abbr title="HTTP isteği ile gelen string veriyi Python nesnesine çevirme.">dönüşümü</abbr> desteğini kullanacaksanız gereklidir. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` desteği için gerekli. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse` kullanacaksanız gerekli. Hem FastAPI hem de Starlette tarafından kullanılan: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - oluşturduğumuz uygulamayı servis edecek web sunucusu görevini üstlenir. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - `ORJSONResponse` kullanacaksanız gereklidir. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse` kullanacaksanız gerekli. Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index 32f1f544a..bb21b68c2 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -451,12 +451,12 @@ Starlette використовує: * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Необхідно, якщо Ви хочете підтримувати <abbr title="перетворення рядка, який надходить із запиту HTTP, на дані Python">"розбір"</abbr> форми за допомогою `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Необхідно для підтримки `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. FastAPI / Starlette використовують: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - для сервера, який завантажує та обслуговує вашу програму. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Необхідно, якщо Ви хочете використовувати `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. Ви можете встановити все це за допомогою `pip install fastapi[all]`. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index eb078bc4a..652218afa 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -457,7 +457,6 @@ Independent TechEmpower benchmarks cho thấy các ứng dụng **FastAPI** ch Sử dụng bởi Pydantic: -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - <abbr title="chuyển dổi string từ HTTP request sang dữ liệu Python">"Parse"</abbr> JSON nhanh hơn. * <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - cho email validation. Sử dụng Starlette: @@ -467,12 +466,12 @@ Sử dụng Starlette: * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Bắt buộc nếu bạn muốn hỗ trợ <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, form với `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Bắt buộc để hỗ trợ `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Bắt buộc để hỗ trợ `SchemaGenerator` cho Starlette (bạn có thể không cần nó trong FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. Sử dụng bởi FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - Server để chạy ứng dụng của bạn. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Bắt buộc nếu bạn muốn sử dụng `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. Bạn có thể cài đặt tất cả những dependency trên với `pip install "fastapi[all]"`. diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index c3c709350..352bf4df8 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -465,12 +465,12 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn <a href="https://fastapi.tian * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún <abbr title="tí ó se ìyípadà ọ̀rọ̀-ìyọ̀/òkun-ọ̀rọ̀ tí ó wà láti ìbéèrè HTTP sí inú àkójọf'áyẹ̀wò Python">"àyẹ̀wò"</abbr> fọọmu, pẹ̀lú `request.form()`. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Nílò fún àtìlẹ́yìn `SessionMiddleware`. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI). -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. Èyí tí FastAPI / Starlette ń lò: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - Fún olupin tí yóò sẹ́ àmúyẹ àti tí yóò ṣe ìpèsè fún iṣẹ́ rẹ tàbí ohun èlò rẹ. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Nílò tí ó bá fẹ́ láti lọ `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. Ó lè fi gbogbo àwọn wọ̀nyí sórí ẹrọ pẹ̀lú `pip install "fastapi[all]"`. diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index 9859d3c51..f90eb2177 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -456,12 +456,12 @@ item: Item - <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - 需要使用 `request.form()` 對表單進行<abbr title="轉換來自表單的 HTTP 請求到 Python 資料型別"> "解析" </abbr>時安裝。 - <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - 需要使用 `SessionMiddleware` 支援時安裝。 - <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。 -- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 使用 `UJSONResponse` 時必須安裝。 用於 FastAPI / Starlette: - <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - 用於加載和運行應用程式的服務器。 - <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - 使用 `ORJSONResponse`時必須安裝。 +- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 使用 `UJSONResponse` 時必須安裝。 你可以使用 `pip install "fastapi[all]"` 來安裝這些所有依賴套件。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index dfe5af827..2a67e8d08 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -459,12 +459,12 @@ item: Item * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - 需要 `SessionMiddleware` 支持时安装。 * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。 * <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - 需要 `GraphQLApp` 支持时安装。 -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 使用 `UJSONResponse` 时安装。 用于 FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - 用于加载和运行你的应用程序的服务器。 * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - 使用 `ORJSONResponse` 时安装。 +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 使用 `UJSONResponse` 时安装。 你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。 From d84d6e03f42f7cde8c4fdd4367e33e06f37ad667 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Apr 2024 23:59:09 +0000 Subject: [PATCH 405/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 49df7a771..3cd23f69e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Docs +* 📝 Update references to UJSON. PR [#11464](https://github.com/tiangolo/fastapi/pull/11464) by [@tiangolo](https://github.com/tiangolo). * 📝 Tweak docs and translations links, typos, format. PR [#11389](https://github.com/tiangolo/fastapi/pull/11389) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Fix typo in `docs/es/docs/async.md`. PR [#11400](https://github.com/tiangolo/fastapi/pull/11400) by [@fabianfalon](https://github.com/fabianfalon). * 📝 Update OpenAPI client generation docs to use `@hey-api/openapi-ts`. PR [#11339](https://github.com/tiangolo/fastapi/pull/11339) by [@jordanshatford](https://github.com/jordanshatford). From 6d523d62d0ff1433beeba6c0c0774690cc072edb Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Fri, 19 Apr 2024 02:11:40 +0200 Subject: [PATCH 406/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20types=20in=20examp?= =?UTF-8?q?les=20under=20`docs=5Fsrc/extra=5Fdata=5Ftypes`=20(#10535)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs_src/extra_data_types/tutorial001.py | 8 +-- docs_src/extra_data_types/tutorial001_an.py | 8 +-- .../extra_data_types/tutorial001_an_py310.py | 8 +-- .../extra_data_types/tutorial001_an_py39.py | 8 +-- .../extra_data_types/tutorial001_py310.py | 8 +-- .../test_extra_data_types/test_tutorial001.py | 54 ++++++------------- .../test_tutorial001_an.py | 54 ++++++------------- .../test_tutorial001_an_py310.py | 54 ++++++------------- .../test_tutorial001_an_py39.py | 54 ++++++------------- .../test_tutorial001_py310.py | 54 ++++++------------- 10 files changed, 95 insertions(+), 215 deletions(-) diff --git a/docs_src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001.py index 8ae8472a7..71de958ff 100644 --- a/docs_src/extra_data_types/tutorial001.py +++ b/docs_src/extra_data_types/tutorial001.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Union[datetime, None] = Body(default=None), - end_datetime: Union[datetime, None] = Body(default=None), + start_datetime: datetime = Body(), + end_datetime: datetime = Body(), + process_after: timedelta = Body(), repeat_at: Union[time, None] = Body(default=None), - process_after: Union[timedelta, None] = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an.py b/docs_src/extra_data_types/tutorial001_an.py index a4c074241..257d0c7c8 100644 --- a/docs_src/extra_data_types/tutorial001_an.py +++ b/docs_src/extra_data_types/tutorial001_an.py @@ -11,10 +11,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -22,8 +22,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an_py310.py b/docs_src/extra_data_types/tutorial001_an_py310.py index 4f69c40d9..668bf1909 100644 --- a/docs_src/extra_data_types/tutorial001_an_py310.py +++ b/docs_src/extra_data_types/tutorial001_an_py310.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[datetime | None, Body()] = None, - end_datetime: Annotated[datetime | None, Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[time | None, Body()] = None, - process_after: Annotated[timedelta | None, Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an_py39.py b/docs_src/extra_data_types/tutorial001_an_py39.py index 630d36ae3..fa3551d66 100644 --- a/docs_src/extra_data_types/tutorial001_an_py39.py +++ b/docs_src/extra_data_types/tutorial001_an_py39.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_py310.py b/docs_src/extra_data_types/tutorial001_py310.py index d22f81888..a275a0577 100644 --- a/docs_src/extra_data_types/tutorial001_py310.py +++ b/docs_src/extra_data_types/tutorial001_py310.py @@ -9,10 +9,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: datetime | None = Body(default=None), - end_datetime: datetime | None = Body(default=None), + start_datetime: datetime = Body(), + end_datetime: datetime = Body(), + process_after: timedelta = Body(), repeat_at: time | None = Body(default=None), - process_after: timedelta | None = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -20,8 +20,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py index 7710446ce..5558671b9 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py @@ -67,6 +67,7 @@ def test_openapi_schema(): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -86,7 +87,7 @@ def test_openapi_schema(): } ) } - } + }, }, } } @@ -97,40 +98,16 @@ def test_openapi_schema(): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -151,10 +128,8 @@ def test_openapi_schema(): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -166,6 +141,7 @@ def test_openapi_schema(): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py index 9951b3b51..e309f8bd6 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py @@ -67,6 +67,7 @@ def test_openapi_schema(): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -86,7 +87,7 @@ def test_openapi_schema(): } ) } - } + }, }, } } @@ -97,40 +98,16 @@ def test_openapi_schema(): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -151,10 +128,8 @@ def test_openapi_schema(): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -166,6 +141,7 @@ def test_openapi_schema(): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py index 7c482b8cb..ca110dc00 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py @@ -76,6 +76,7 @@ def test_openapi_schema(client: TestClient): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -95,7 +96,7 @@ def test_openapi_schema(client: TestClient): } ) } - } + }, }, } } @@ -106,40 +107,16 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -160,10 +137,8 @@ def test_openapi_schema(client: TestClient): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -175,6 +150,7 @@ def test_openapi_schema(client: TestClient): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py index 87473867b..3386fb1fd 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py @@ -76,6 +76,7 @@ def test_openapi_schema(client: TestClient): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -95,7 +96,7 @@ def test_openapi_schema(client: TestClient): } ) } - } + }, }, } } @@ -106,40 +107,16 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -160,10 +137,8 @@ def test_openapi_schema(client: TestClient): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -175,6 +150,7 @@ def test_openapi_schema(client: TestClient): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py index 0b71d9177..50c9aefdf 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py @@ -76,6 +76,7 @@ def test_openapi_schema(client: TestClient): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -95,7 +96,7 @@ def test_openapi_schema(client: TestClient): } ) } - } + }, }, } } @@ -106,40 +107,16 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -160,10 +137,8 @@ def test_openapi_schema(client: TestClient): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -175,6 +150,7 @@ def test_openapi_schema(client: TestClient): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", From 4ae63ae4953054e03f07d47e38209dddd4bee4e6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 19 Apr 2024 00:12:01 +0000 Subject: [PATCH 407/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3cd23f69e..6c346ee76 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Docs +* 📝 Fix types in examples under `docs_src/extra_data_types`. PR [#10535](https://github.com/tiangolo/fastapi/pull/10535) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Update references to UJSON. PR [#11464](https://github.com/tiangolo/fastapi/pull/11464) by [@tiangolo](https://github.com/tiangolo). * 📝 Tweak docs and translations links, typos, format. PR [#11389](https://github.com/tiangolo/fastapi/pull/11389) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Fix typo in `docs/es/docs/async.md`. PR [#11400](https://github.com/tiangolo/fastapi/pull/11400) by [@fabianfalon](https://github.com/fabianfalon). From be1e3faa63bd6785399d6cd98dbc8417ddd045dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 18 Apr 2024 19:31:47 -0500 Subject: [PATCH 408/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?0.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6c346ee76..8bba785ce 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.110.2 + ### Fixes * 🐛 Fix support for query parameters with list types, handle JSON encoding Pydantic `UndefinedType`. PR [#9929](https://github.com/tiangolo/fastapi/pull/9929) by [@arjwilliams](https://github.com/arjwilliams). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 5a77101fb..f28657712 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.110.1" +__version__ = "0.110.2" from starlette import status as status From 1aedc6e29d1fbf84aac962cff8e66fafd761206b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 18 Apr 2024 19:41:55 -0500 Subject: [PATCH 409/846] =?UTF-8?q?=F0=9F=94=A7=20Ungroup=20dependabot=20u?= =?UTF-8?q?pdates=20(#11465)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/dependabot.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0a59adbd6..8979aabf8 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,9 +12,5 @@ updates: directory: "/" schedule: interval: "monthly" - groups: - python-packages: - patterns: - - "*" commit-message: prefix: ⬆ From fb165a55f02bfb99ad635526a87d86419d76cc3c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 19 Apr 2024 00:42:15 +0000 Subject: [PATCH 410/846] =?UTF-8?q?=F0=9F=93=9D=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 8bba785ce..13c926d84 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* 🔧 Ungroup dependabot updates. PR [#11465](https://github.com/tiangolo/fastapi/pull/11465) by [@tiangolo](https://github.com/tiangolo). + ## 0.110.2 ### Fixes From 11f95ddef6ebb656572531aeec82e1672fedb314 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 18 Apr 2024 19:43:24 -0500 Subject: [PATCH 411/846] =?UTF-8?q?=E2=AC=86=20Bump=20pillow=20from=2010.2?= =?UTF-8?q?.0=20to=2010.3.0=20(#11403)?= 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.2.0 to 10.3.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.2.0...10.3.0) --- updated-dependencies: - dependency-name: pillow dependency-type: direct:production ... Signed-off-by: dependabot[bot] <support@github.com> 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 8fa64cf39..8462479ff 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.2.0 +pillow==10.3.0 # For image processing by Material for MkDocs cairosvg==2.7.0 mkdocstrings[python]==0.23.0 From 14442d356fdc6367ac71766c9a4a49189a01b148 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 19 Apr 2024 00:46:03 +0000 Subject: [PATCH 412/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 13c926d84..072dba750 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Internal +* ⬆ Bump pillow from 10.2.0 to 10.3.0. PR [#11403](https://github.com/tiangolo/fastapi/pull/11403) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Ungroup dependabot updates. PR [#11465](https://github.com/tiangolo/fastapi/pull/11465) by [@tiangolo](https://github.com/tiangolo). ## 0.110.2 From 2f686ce1e5efdecc61105f8b9283f0118ec8b1e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 18 Apr 2024 19:56:59 -0500 Subject: [PATCH 413/846] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20MkDocs?= =?UTF-8?q?=20Material=20and=20re-enable=20cards=20(#11466)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.insiders.yml | 11 +++++------ requirements-docs.txt | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index 8f3538a80..d204974b8 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -1,8 +1,7 @@ plugins: - # TODO: Re-enable once this is fixed: https://github.com/squidfunk/mkdocs-material/issues/6983 - # social: - # cards_layout_dir: ../en/layouts - # cards_layout: custom - # cards_layout_options: - # logo: ../en/docs/img/icon-white.svg + social: + cards_layout_dir: ../en/layouts + cards_layout: custom + cards_layout_options: + logo: ../en/docs/img/icon-white.svg typeset: diff --git a/requirements-docs.txt b/requirements-docs.txt index 8462479ff..599e01f16 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -1,6 +1,6 @@ -e . -r requirements-docs-tests.txt -mkdocs-material==9.4.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.0 From 25c692d77df37b88d89a807a6108c002a5ebf477 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 19 Apr 2024 01:03:14 +0000 Subject: [PATCH 414/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 072dba750..a950414bf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Internal +* ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pillow from 10.2.0 to 10.3.0. PR [#11403](https://github.com/tiangolo/fastapi/pull/11403) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Ungroup dependabot updates. PR [#11465](https://github.com/tiangolo/fastapi/pull/11465) by [@tiangolo](https://github.com/tiangolo). From ce1fb1a23bc62d033ac5852de66828e1f366a98b Mon Sep 17 00:00:00 2001 From: Omar Mokhtar <omokhtarm@gmail.com> Date: Fri, 19 Apr 2024 17:29:38 +0200 Subject: [PATCH 415/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`security/http.py`=20(#11455)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/security/http.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/security/http.py b/fastapi/security/http.py index b45bee55c..a142b135d 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -15,7 +15,7 @@ from typing_extensions import Annotated, Doc class HTTPBasicCredentials(BaseModel): """ - The HTTP Basic credendials given as the result of using `HTTPBasic` in a + The HTTP Basic credentials given as the result of using `HTTPBasic` in a dependency. Read more about it in the From e00d29e78418ae8eca64047ea10191c5c8d77565 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 19 Apr 2024 15:30:04 +0000 Subject: [PATCH 416/846] =?UTF-8?q?=F0=9F=93=9D=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 a950414bf..e61117245 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* ✏️ Fix typo in `security/http.py`. PR [#11455](https://github.com/tiangolo/fastapi/pull/11455) by [@omarmoo5](https://github.com/omarmoo5). + ### Internal * ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo). From 1551913223eb5d36516d70084dae4f6529fd2ce4 Mon Sep 17 00:00:00 2001 From: Fabian Falon <fabian.falon@gmail.com> Date: Fri, 19 Apr 2024 21:30:26 +0200 Subject: [PATCH 417/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20cookie-params=20`docs/es/docs/tutorial/cookie-param?= =?UTF-8?q?s.md`=20(#11410)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/tutorial/cookie-params.md | 97 ++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 docs/es/docs/tutorial/cookie-params.md diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..9f736575d --- /dev/null +++ b/docs/es/docs/tutorial/cookie-params.md @@ -0,0 +1,97 @@ +# Parámetros de Cookie + +Puedes definir parámetros de Cookie de la misma manera que defines parámetros de `Query` y `Path`. + +## Importar `Cookie` + +Primero importa `Cookie`: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +## Declarar parámetros de `Cookie` + +Luego declara los parámetros de cookie usando la misma estructura que con `Path` y `Query`. + +El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +!!! note "Detalles Técnicos" + `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. + + Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. + +!!! info + Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. + +## Resumen + +Declara cookies con `Cookie`, usando el mismo patrón común que `Query` y `Path`. From 91dad1cb3af203bef60bff635cb1adb897d2a671 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 19 Apr 2024 19:30:49 +0000 Subject: [PATCH 418/846] =?UTF-8?q?=F0=9F=93=9D=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 e61117245..7668a3edf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * ✏️ Fix typo in `security/http.py`. PR [#11455](https://github.com/tiangolo/fastapi/pull/11455) by [@omarmoo5](https://github.com/omarmoo5). +### Translations + +* 🌐 Add Spanish translation for cookie-params `docs/es/docs/tutorial/cookie-params.md`. PR [#11410](https://github.com/tiangolo/fastapi/pull/11410) by [@fabianfalon](https://github.com/fabianfalon). + ### Internal * ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo). From 943159afb078f7f6ce5cdc03fc815240902f19a0 Mon Sep 17 00:00:00 2001 From: Bill Zhong <billzhong@users.noreply.github.com> Date: Mon, 22 Apr 2024 21:11:09 -0230 Subject: [PATCH 419/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/how-to/index.md`=20and=20`docs/zh/doc?= =?UTF-8?q?s/how-to/general.md`=20(#11443)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/how-to/general.md | 39 ++++++++++++++++++++++++++++++++++ docs/zh/docs/how-to/index.md | 11 ++++++++++ 2 files changed, 50 insertions(+) create mode 100644 docs/zh/docs/how-to/general.md create mode 100644 docs/zh/docs/how-to/index.md diff --git a/docs/zh/docs/how-to/general.md b/docs/zh/docs/how-to/general.md new file mode 100644 index 000000000..e8b6dd3b2 --- /dev/null +++ b/docs/zh/docs/how-to/general.md @@ -0,0 +1,39 @@ +# 通用 - 如何操作 - 诀窍 + +这里是一些指向文档中其他部分的链接,用于解答一般性或常见问题。 + +## 数据过滤 - 安全性 + +为确保不返回超过需要的数据,请阅读 [教程 - 响应模型 - 返回类型](../tutorial/response-model.md){.internal-link target=_blank} 文档。 + +## 文档的标签 - OpenAPI + +在文档界面中添加**路径操作**的标签和进行分组,请阅读 [教程 - 路径操作配置 - Tags 参数](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} 文档。 + +## 文档的概要和描述 - OpenAPI + +在文档界面中添加**路径操作**的概要和描述,请阅读 [教程 - 路径操作配置 - Summary 和 Description 参数](../tutorial/path-operation-configuration.md#summary-description){.internal-link target=_blank} 文档。 + +## 文档的响应描述 - OpenAPI + +在文档界面中定义并显示响应描述,请阅读 [教程 - 路径操作配置 - 响应描述](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} 文档。 + +## 文档弃用**路径操作** - OpenAPI + +在文档界面中显示弃用的**路径操作**,请阅读 [教程 - 路径操作配置 - 弃用](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} 文档。 + +## 将任何数据转换为 JSON 兼容格式 + +要将任何数据转换为 JSON 兼容格式,请阅读 [教程 - JSON 兼容编码器](../tutorial/encoder.md){.internal-link target=_blank} 文档。 + +## OpenAPI 元数据 - 文档 + +要添加 OpenAPI 的元数据,包括许可证、版本、联系方式等,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md){.internal-link target=_blank} 文档。 + +## OpenAPI 自定义 URL + +要自定义 OpenAPI 的 URL(或删除它),请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} 文档。 + +## OpenAPI 文档 URL + +要更改用于自动生成文档的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md new file mode 100644 index 000000000..c0688c72a --- /dev/null +++ b/docs/zh/docs/how-to/index.md @@ -0,0 +1,11 @@ +# 如何操作 - 诀窍 + +在这里,你将看到关于**多个主题**的不同诀窍或“如何操作”指南。 + +这些方法多数是**相互独立**的,在大多数情况下,你只需在这些内容适用于**你的项目**时才需要学习它们。 + +如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 + +!!! 小技巧 + + 如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 From 5c054fdd652842e6ee26b8d5e09d9c57b9fbfcfd Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 22 Apr 2024 23:41:32 +0000 Subject: [PATCH 420/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7668a3edf..636ed04dd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/how-to/index.md` and `docs/zh/docs/how-to/general.md`. PR [#11443](https://github.com/tiangolo/fastapi/pull/11443) by [@billzhong](https://github.com/billzhong). * 🌐 Add Spanish translation for cookie-params `docs/es/docs/tutorial/cookie-params.md`. PR [#11410](https://github.com/tiangolo/fastapi/pull/11410) by [@fabianfalon](https://github.com/fabianfalon). ### Internal From 550092a3bd7d6a427c76eae050de9194648a683d Mon Sep 17 00:00:00 2001 From: ch33zer <ch33zer@gmail.com> Date: Tue, 23 Apr 2024 15:29:18 -0700 Subject: [PATCH 421/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`fastapi/security/api=5Fkey.py`=20(#11481)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/security/api_key.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py index b74a017f1..d68bdb037 100644 --- a/fastapi/security/api_key.py +++ b/fastapi/security/api_key.py @@ -76,7 +76,7 @@ class APIKeyQuery(APIKeyBase): Doc( """ By default, if the query parameter is not provided, `APIKeyQuery` will - automatically cancel the request and sebd the client an error. + automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the query parameter is not available, instead of erroring out, the dependency result will be From 38929aae1b6d42848652705e5ca618a675dba0e1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 23 Apr 2024 22:29:42 +0000 Subject: [PATCH 422/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 636ed04dd..b94e017e4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix typo in `fastapi/security/api_key.py`. PR [#11481](https://github.com/tiangolo/fastapi/pull/11481) by [@ch33zer](https://github.com/ch33zer). * ✏️ Fix typo in `security/http.py`. PR [#11455](https://github.com/tiangolo/fastapi/pull/11455) by [@omarmoo5](https://github.com/omarmoo5). ### Translations From 026af6e2483c32e7f1fb33c317da23b6d88e958c Mon Sep 17 00:00:00 2001 From: Bill Zhong <billzhong@users.noreply.github.com> Date: Thu, 25 Apr 2024 14:39:48 -0230 Subject: [PATCH 423/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/fastapi-people.md`=20(#11476)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/fastapi-people.md | 93 ++++++++++++++++++++++++++-------- 1 file changed, 73 insertions(+), 20 deletions(-) diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md index 6cf35253c..d6a3e66c3 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -33,39 +33,98 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 这些人: -* [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 +* [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 * [创建 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 * 审核 Pull Requests, 对于 [翻译](contributing.md#_8){.internal-link target=_blank} 尤为重要。 向他们致以掌声。 👏 🙇 -## 上个月最活跃的用户 +## FastAPI 专家 -上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 +这些用户一直以来致力于 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🙇 + +他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨ + +!!! 小提示 + 你也可以成为认可的 FastAPI 专家! + + 只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 + +你可以查看不同时期的 **FastAPI 专家**: + +* [上个月](#fastapi-experts-last-month) 🤓 +* [三个月](#fastapi-experts-3-months) 😎 +* [六个月](#fastapi-experts-6-months) 🧐 +* [一年](#fastapi-experts-1-year) 🧑🔬 +* [**全部时间**](#fastapi-experts-all-time) 🧙 + +## FastAPI 专家 - 上个月 + +这些是在过去一个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🤓 {% if people %} <div class="user-list user-list-center"> {% for user in people.last_month_experts[:10] %} -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI 专家 - 三个月 + +这些是在过去三个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 😎 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.three_months_experts[:10] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI 专家 - 六个月 + +这些是在过去六个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧐 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.six_months_experts[:10] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> {% endfor %} </div> {% endif %} -## 专家组 +### FastAPI 专家 - 一年 + +这些是在过去一年中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧑🔬 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.one_year_experts[:20] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} -以下是 **FastAPI 专家**。 🤓 +## FastAPI 专家 - 全部时间 -这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 +以下是全部时间的 **FastAPI 专家**。 🤓🤯 -他们通过帮助许多人而被证明是专家。✨ +这些用户一直以来致力于 [帮助他人解决 GitHub 的 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🧙 {% if people %} <div class="user-list user-list-center"> {% for user in people.experts[:50] %} -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> {% endfor %} </div> @@ -89,25 +148,19 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 </div> {% endif %} -还有很多其他贡献者(超过100个),你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷 - -## 杰出审核者 - -以下用户是「杰出的评审者」。 🕵️ +还有很多别的贡献者(超过100个),你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷 -### 翻译审核 +## 杰出翻译审核者 -我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。 - ---- +以下用户是 **杰出的评审者**。 🕵️ -**杰出的评审者** 🕵️ 评审了最多来自他人的 Pull Requests,他们保证了代码、文档尤其是 **翻译** 的质量。 +我只会说少数几种语言(而且还不是很流利 😅)。所以这些评审者们具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank}。如果没有他们,就不会有多语言文档。 {% if people %} <div class="user-list user-list-center"> {% for user in people.top_translations_reviewers[:50] %} -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">审核数: {{ user.count }}</div></div> {% endfor %} </div> From b254688f37fc4e958774d1b6ef00cd22684cae09 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 25 Apr 2024 17:10:18 +0000 Subject: [PATCH 424/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b94e017e4..29c76636c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/fastapi-people.md`. PR [#11476](https://github.com/tiangolo/fastapi/pull/11476) by [@billzhong](https://github.com/billzhong). * 🌐 Add Chinese translation for `docs/zh/docs/how-to/index.md` and `docs/zh/docs/how-to/general.md`. PR [#11443](https://github.com/tiangolo/fastapi/pull/11443) by [@billzhong](https://github.com/billzhong). * 🌐 Add Spanish translation for cookie-params `docs/es/docs/tutorial/cookie-params.md`. PR [#11410](https://github.com/tiangolo/fastapi/pull/11410) by [@fabianfalon](https://github.com/fabianfalon). From 8045f34c52a273c4f21cdc5fa5f0109b142d3ba7 Mon Sep 17 00:00:00 2001 From: Ian Chiu <36751646+KNChiu@users.noreply.github.com> Date: Sat, 27 Apr 2024 22:30:56 +0800 Subject: [PATCH 425/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/benchmarks.md`=20(#1148?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/benchmarks.md | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/zh-hant/docs/benchmarks.md diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md new file mode 100644 index 000000000..cbd5a6cde --- /dev/null +++ b/docs/zh-hant/docs/benchmarks.md @@ -0,0 +1,34 @@ +# 基準測試 + +由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 可用框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。 + +但是在查看基準得分和對比時,請注意以下幾點。 + +## 基準測試和速度 + +當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。 + +具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。 + +該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。 + +層次結構如下: + +* **Uvicorn**:ASGI 伺服器 + * **Starlette**:(使用 Uvicorn)一個網頁微框架 + * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。 + +* **Uvicorn**: + * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。 + * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。 + * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。 +* **Starlette**: + * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。 + * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。 + * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。 +* **FastAPI**: + * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。 + * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。 + * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。 + * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。 + * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。 From 1d41a7d2df5714e6598b541cac3cac5859b3ad4b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 27 Apr 2024 14:31:16 +0000 Subject: [PATCH 426/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 29c76636c..f0ed3368f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/benchmarks.md`. PR [#11484](https://github.com/tiangolo/fastapi/pull/11484) by [@KNChiu](https://github.com/KNChiu). * 🌐 Update Chinese translation for `docs/zh/docs/fastapi-people.md`. PR [#11476](https://github.com/tiangolo/fastapi/pull/11476) by [@billzhong](https://github.com/billzhong). * 🌐 Add Chinese translation for `docs/zh/docs/how-to/index.md` and `docs/zh/docs/how-to/general.md`. PR [#11443](https://github.com/tiangolo/fastapi/pull/11443) by [@billzhong](https://github.com/billzhong). * 🌐 Add Spanish translation for cookie-params `docs/es/docs/tutorial/cookie-params.md`. PR [#11410](https://github.com/tiangolo/fastapi/pull/11410) by [@fabianfalon](https://github.com/fabianfalon). From d1293b878664079405d1c5e6a016bad64106480f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 27 Apr 2024 19:27:34 -0500 Subject: [PATCH 427/846] =?UTF-8?q?=E2=AC=86=20Bump=20mkdocstrings[python]?= =?UTF-8?q?=20from=200.23.0=20to=200.24.3=20(#11469)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [mkdocstrings[python]](https://github.com/mkdocstrings/mkdocstrings) from 0.23.0 to 0.24.3. - [Release notes](https://github.com/mkdocstrings/mkdocstrings/releases) - [Changelog](https://github.com/mkdocstrings/mkdocstrings/blob/main/CHANGELOG.md) - [Commits](https://github.com/mkdocstrings/mkdocstrings/compare/0.23.0...0.24.3) --- updated-dependencies: - dependency-name: mkdocstrings[python] dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> 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 599e01f16..c672f0ef7 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -11,7 +11,7 @@ jieba==0.42.1 pillow==10.3.0 # For image processing by Material for MkDocs cairosvg==2.7.0 -mkdocstrings[python]==0.23.0 +mkdocstrings[python]==0.24.3 griffe-typingdoc==0.2.2 # For griffe, it formats with black black==24.3.0 From 285ac017a97997c861ea1242cbb8606369345ebf Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 28 Apr 2024 00:28:00 +0000 Subject: [PATCH 428/846] =?UTF-8?q?=F0=9F=93=9D=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 f0ed3368f..a80ab47e5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆ Bump mkdocstrings[python] from 0.23.0 to 0.24.3. PR [#11469](https://github.com/tiangolo/fastapi/pull/11469) by [@dependabot[bot]](https://github.com/apps/dependabot). + ### Docs * ✏️ Fix typo in `fastapi/security/api_key.py`. PR [#11481](https://github.com/tiangolo/fastapi/pull/11481) by [@ch33zer](https://github.com/ch33zer). From 7b55bf37b58cabfcde03eac4d3fb0fee459bdd40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 28 Apr 2024 22:18:04 -0700 Subject: [PATCH 429/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20references=20to?= =?UTF-8?q?=20Python=20version,=20FastAPI=20supports=20all=20the=20current?= =?UTF-8?q?=20versions,=20no=20need=20to=20make=20the=20version=20explicit?= =?UTF-8?q?=20(#11496)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++---- docs/az/docs/index.md | 6 ++---- docs/de/docs/index.md | 6 ++---- docs/en/docs/index.md | 6 ++---- docs/es/docs/index.md | 6 ++---- docs/fr/docs/index.md | 6 ++---- docs/hu/docs/index.md | 6 ++---- docs/ja/docs/index.md | 4 +--- docs/ko/docs/index.md | 6 ++---- docs/pl/docs/index.md | 6 ++---- docs/pt/docs/index.md | 6 ++---- docs/ru/docs/index.md | 6 ++---- docs/tr/docs/index.md | 6 ++---- docs/uk/docs/index.md | 6 ++---- docs/vi/docs/index.md | 6 ++---- docs/yo/docs/index.md | 6 ++---- docs/zh-hant/docs/index.md | 6 ++---- docs/zh/docs/index.md | 6 +++--- 18 files changed, 36 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index bcb18ac66..c7adc49cd 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. The key features are: @@ -122,8 +122,6 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be ## Requirements -Python 3.8+ - FastAPI stands on the shoulders of giants: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts. @@ -338,7 +336,7 @@ You do that with standard modern Python types. You don't have to learn a new syntax, the methods or classes of a specific library, etc. -Just standard **Python 3.8+**. +Just standard **Python**. For example, for an `int`: diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index 33bcc1556..430295d91 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python <abbr title="Tip Məsləhətləri: Type Hints">tip məsləhətlərinə</abbr> əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür. +FastAPI Python ilə API yaratmaq üçün standart Python <abbr title="Tip Məsləhətləri: Type Hints">tip məsləhətlərinə</abbr> əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür. Əsas xüsusiyyətləri bunlardır: @@ -115,8 +115,6 @@ FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python <abbr title="Tip M ## Tələblər -Python 3.8+ - FastAPI nəhənglərin çiyinlərində dayanır: * Web tərəfi üçün <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. @@ -330,7 +328,7 @@ Bunu standart müasir Python tipləri ilə edirsiniz. Yeni sintaksis, müəyyən bir kitabxananın metodlarını və ya siniflərini və s. öyrənmək məcburiyyətində deyilsiniz. -Sadəcə standart **Python 3.8+**. +Sadəcə standart **Python**. Məsələn, `int` üçün: diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index cf5a2b2d6..9b8a73003 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python 3.8+ auf Basis von Standard-Python-Typhinweisen. +FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python auf Basis von Standard-Python-Typhinweisen. Seine Schlüssel-Merkmale sind: @@ -125,8 +125,6 @@ Wenn Sie eine <abbr title="Command Line Interface – Kommandozeilen-Schnittstel ## Anforderungen -Python 3.8+ - FastAPI steht auf den Schultern von Giganten: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> für die Webanteile. @@ -340,7 +338,7 @@ Das machen Sie mit modernen Standard-Python-Typen. Sie müssen keine neue Syntax, Methoden oder Klassen einer bestimmten Bibliothek usw. lernen. -Nur Standard-**Python 3.8+**. +Nur Standard-**Python+**. Zum Beispiel für ein `int`: diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index a5ed8b330..508e859a1 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. The key features are: @@ -124,8 +124,6 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be ## Requirements -Python 3.8+ - FastAPI stands on the shoulders of giants: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts. @@ -340,7 +338,7 @@ You do that with standard modern Python types. You don't have to learn a new syntax, the methods or classes of a specific library, etc. -Just standard **Python 3.8+**. +Just standard **Python**. For example, for an `int`: diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 9fc275caf..631be7463 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -32,7 +32,7 @@ hide: **Código Fuente**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.8+ basado en las anotaciones de tipos estándar de Python. +FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python basado en las anotaciones de tipos estándar de Python. Sus características principales son: @@ -115,8 +115,6 @@ Si estás construyendo un app de <abbr title="Interfaz de línea de comandos en ## Requisitos -Python 3.8+ - FastAPI está sobre los hombros de gigantes: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> para las partes web. @@ -328,7 +326,7 @@ Lo haces con tipos modernos estándar de Python. No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc. -Solo **Python 3.8+** estándar. +Solo **Python** estándar. Por ejemplo, para un `int`: diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 324681a74..e31f416ce 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.8+, basé sur les annotations de type standard de Python. +FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python, basé sur les annotations de type standard de Python. Les principales fonctionnalités sont : @@ -124,8 +124,6 @@ Si vous souhaitez construire une application <abbr title="Command Line Interface ## Prérequis -Python 3.8+ - FastAPI repose sur les épaules de géants : * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> pour les parties web. @@ -340,7 +338,7 @@ Vous faites cela avec les types Python standard modernes. Vous n'avez pas à apprendre une nouvelle syntaxe, les méthodes ou les classes d'une bibliothèque spécifique, etc. -Juste du **Python 3.8+** standard. +Juste du **Python** standard. Par exemple, pour un `int`: diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 896db6d1f..671b0477f 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -26,7 +26,7 @@ **Forrás kód**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> --- -A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python 3.8+-al, a Python szabványos típusjelöléseire építve. +A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python -al, a Python szabványos típusjelöléseire építve. Kulcs funkciók: @@ -115,8 +115,6 @@ Ha egy olyan CLI alkalmazást fejlesztesz amit a parancssorban kell használni w ## Követelmények -Python 3.8+ - A FastAPI óriások vállán áll: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> a webes részekhez. @@ -331,7 +329,7 @@ Ezt standard modern Python típusokkal csinálod. Nem kell új szintaxist, vagy specifikus könyvtár mert metódósait, stb. megtanulnod. -Csak standard **Python 3.8+**. +Csak standard **Python**. Például egy `int`-nek: diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index a991222cb..f95ac060f 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -33,7 +33,7 @@ hide: --- -FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 +FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 主な特徴: @@ -116,8 +116,6 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 ## 必要条件 -Python 3.8+ - FastAPI は巨人の肩の上に立っています。 - Web の部分は<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index dea087332..4bc92c36c 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -33,7 +33,7 @@ hide: --- -FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다. +FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크입니다. 주요 특징으로: @@ -116,8 +116,6 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 ## 요구사항 -Python 3.8+ - FastAPI는 거인들의 어깨 위에 서 있습니다: * 웹 부분을 위한 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. @@ -332,7 +330,7 @@ def update_item(item_id: int, item: Item): 새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다. -그저 표준 **Python 3.8+** 입니다. +그저 표준 **Python** 입니다. 예를 들어, `int`에 대해선: diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 06fa706bc..4bd100f13 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -33,7 +33,7 @@ hide: --- -FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.8+ bazujący na standardowym typowaniu Pythona. +FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona bazujący na standardowym typowaniu Pythona. Kluczowe cechy: @@ -115,8 +115,6 @@ Jeżeli tworzysz aplikacje <abbr title="aplikacja z interfejsem konsolowym">CLI< ## Wymagania -Python 3.8+ - FastAPI oparty jest na: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> dla części webowej. @@ -330,7 +328,7 @@ Robisz to tak samo jak ze standardowymi typami w Pythonie. Nie musisz sie uczyć żadnej nowej składni, metod lub klas ze specyficznych bibliotek itp. -Po prostu standardowy **Python 3.8+**. +Po prostu standardowy **Python**. Na przykład, dla danych typu `int`: diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 86b77f117..223aeee46 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -33,7 +33,7 @@ hide: --- -FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.8 ou superior, baseado nos _type hints_ padrões do Python. +FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python, baseado nos _type hints_ padrões do Python. Os recursos chave são: @@ -109,8 +109,6 @@ Se você estiver construindo uma aplicação <abbr title="Command Line Interface ## Requisitos -Python 3.8+ - FastAPI está nos ombros de gigantes: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> para as partes web. @@ -325,7 +323,7 @@ Você faz com tipos padrão do Python moderno. Você não terá que aprender uma nova sintaxe, métodos ou classes de uma biblioteca específica etc. -Apenas **Python 3.8+** padrão. +Apenas **Python** padrão. Por exemplo, para um `int`: diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 81c3835d9..03087448c 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.8+, в основе которого лежит стандартная аннотация типов Python. +FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python, в основе которого лежит стандартная аннотация типов Python. Ключевые особенности: @@ -118,8 +118,6 @@ FastAPI — это современный, быстрый (высокопрои ## Зависимости -Python 3.8+ - FastAPI стоит на плечах гигантов: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> для части связанной с вебом. @@ -334,7 +332,7 @@ def update_item(item_id: int, item: Item): Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д. -Только стандартный **Python 3.8+**. +Только стандартный **Python**. Например, для `int`: diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 67a9b4462..4b9c0705d 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI, Python <abbr title="Python 3.8 ve üzeri">3.8+</abbr>'nin standart <abbr title="Tip Belirteçleri: Type Hints">tip belirteçleri</abbr>ne dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. +FastAPI, Python 'nin standart <abbr title="Tip Belirteçleri: Type Hints">tip belirteçleri</abbr>ne dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. Temel özellikleri şunlardır: @@ -124,8 +124,6 @@ Eğer API yerine, terminalde kullanılmak üzere bir <abbr title="Komut Satırı ## Gereksinimler -Python 3.8+ - FastAPI iki devin omuzları üstünde duruyor: * Web tarafı için <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. @@ -340,7 +338,7 @@ Bu işlemi standart modern Python tipleriyle yapıyoruz. Yeni bir sözdizimi yapısını, bir kütüphane özel metod veya sınıfları öğrenmeye gerek yoktur. -Hepsi sadece **Python 3.8+** standartlarına dayalıdır. +Hepsi sadece **Python** standartlarına dayalıdır. Örnek olarak, `int` tanımlamak için: diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index bb21b68c2..e32389772 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python. +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python,в основі якого лежить стандартна анотація типів Python. Ключові особливості: @@ -110,8 +110,6 @@ FastAPI - це сучасний, швидкий (високопродуктив ## Вимоги -Python 3.8+ - FastAPI стоїть на плечах гігантів: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> для web частини. @@ -326,7 +324,7 @@ def update_item(item_id: int, item: Item): Вам не потрібно вивчати новий синтаксис, методи чи класи конкретної бібліотеки тощо. -Використовуючи стандартний **Python 3.8+**. +Використовуючи стандартний **Python**. Наприклад, для `int`: diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 652218afa..b13f91fb7 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python 3.8+ dựa trên tiêu chuẩn Python type hints. +FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python dựa trên tiêu chuẩn Python type hints. Những tính năng như: @@ -125,8 +125,6 @@ Nếu bạn đang xây dựng một <abbr title="Giao diện dòng lệnh">CLI</ ## Yêu cầu -Python 3.8+ - FastAPI đứng trên vai những người khổng lồ: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> cho phần web. @@ -341,7 +339,7 @@ Bạn định nghĩa bằng cách sử dụng các kiểu dữ liệu chuẩn c Bạn không phải học một cú pháp mới, các phương thức và class của một thư viện cụ thể nào. -Chỉ cần sử dụng các chuẩn của **Python 3.8+**. +Chỉ cần sử dụng các chuẩn của **Python**. Ví dụ, với một tham số kiểu `int`: diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 352bf4df8..9bd21c4b9 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python 3.8+ èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. +FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. Àwọn ẹya pàtàkì ni: @@ -124,8 +124,6 @@ Ti o ba n kọ ohun èlò <abbr title="Command Line Interface">CLI</abbr> láti ## Èròjà -Python 3.8+ - FastAPI dúró lórí àwọn èjìká tí àwọn òmíràn: * <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> fún àwọn ẹ̀yà ayélujára. @@ -340,7 +338,7 @@ O ṣe ìyẹn pẹ̀lú irúfẹ́ àmì ìtọ́kasí ìgbàlódé Python. O ò nílò láti kọ́ síńtáàsì tuntun, ìlànà tàbí ọ̀wọ́ kíláàsì kan pàtó, abbl (i.e. àti bẹbẹ lọ). -Ìtọ́kasí **Python 3.8+** +Ìtọ́kasí **Python** Fún àpẹẹrẹ, fún `int`: diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index f90eb2177..cdd98ae84 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.8+ 並採用標準 Python 型別提示。 +FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。 主要特點包含: @@ -115,8 +115,6 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3. ## 安裝需求 -Python 3.8+ - FastAPI 是站在以下巨人的肩膀上: - <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> 負責網頁的部分 @@ -331,7 +329,7 @@ def update_item(item_id: int, item: Item): 你不需要學習新的語法、類別、方法或函式庫等等。 -只需要使用 **Python 3.8 以上的版本**。 +只需要使用 **Python 以上的版本**。 舉個範例,比如宣告 int 的型別: diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 2a67e8d08..aef3b3a50 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。 +FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 并基于标准的 Python 类型提示。 关键特性: @@ -119,7 +119,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 ## 依赖 -Python 3.8 及更高版本 +Python 及更高版本 FastAPI 站在以下巨人的肩膀之上: @@ -335,7 +335,7 @@ def update_item(item_id: int, item: Item): 你不需要去学习新的语法、了解特定库的方法或类,等等。 -只需要使用标准的 **Python 3.8 及更高版本**。 +只需要使用标准的 **Python 及更高版本**。 举个例子,比如声明 `int` 类型: From bec2ec7e4c3f3c947c0ac5e159f72396ea052c6e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 29 Apr 2024 05:18:26 +0000 Subject: [PATCH 430/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a80ab47e5..824a2bf82 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Update references to Python version, FastAPI supports all the current versions, no need to make the version explicit. PR [#11496](https://github.com/tiangolo/fastapi/pull/11496) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `fastapi/security/api_key.py`. PR [#11481](https://github.com/tiangolo/fastapi/pull/11481) by [@ch33zer](https://github.com/ch33zer). * ✏️ Fix typo in `security/http.py`. PR [#11455](https://github.com/tiangolo/fastapi/pull/11455) by [@omarmoo5](https://github.com/omarmoo5). From 41fcbc7d009edb60b807695206fc00dba891f137 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Apr 2024 16:48:42 -0700 Subject: [PATCH 431/846] =?UTF-8?q?=F0=9F=94=A7=20Migrate=20from=20Hatch?= =?UTF-8?q?=20to=20PDM=20for=20the=20internal=20build=20(#11498)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/publish.yml | 15 +++++----- fastapi/__init__.py | 2 +- pyproject.toml | 56 +++++++++++++++++++++++++++++++---- requirements-tests.txt | 7 +---- requirements.txt | 1 - 5 files changed, 60 insertions(+), 21 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a5cbf6da4..5ec81b02b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -8,6 +8,12 @@ on: jobs: publish: runs-on: ubuntu-latest + strategy: + matrix: + package: + - fastapi + permissions: + id-token: write steps: - name: Dump GitHub context env: @@ -21,19 +27,14 @@ jobs: # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" # cache-dependency-path: pyproject.toml - - uses: actions/cache@v4 - id: cache - with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish - name: Install build dependencies run: pip install build - name: Build distribution + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish uses: pypa/gh-action-pypi-publish@v1.8.14 - with: - password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} diff --git a/fastapi/__init__.py b/fastapi/__init__.py index f28657712..32d5c41e1 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.110.2" +__version__ = "0.110.3.dev2" from starlette import status as status diff --git a/pyproject.toml b/pyproject.toml index 6c3bebf2b..8f7e0313c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,13 @@ [build-system] -requires = ["hatchling >= 1.13.0"] -build-backend = "hatchling.build" +requires = ["pdm-backend"] +build-backend = "pdm.backend" [project] name = "fastapi" +dynamic = ["version"] description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" readme = "README.md" requires-python = ">=3.8" -license = "MIT" authors = [ { name = "Sebastián Ramírez", email = "tiangolo@gmail.com" }, ] @@ -45,7 +45,6 @@ dependencies = [ "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", ] -dynamic = ["version"] [project.urls] Homepage = "https://github.com/tiangolo/fastapi" @@ -53,22 +52,67 @@ Documentation = "https://fastapi.tiangolo.com/" Repository = "https://github.com/tiangolo/fastapi" [project.optional-dependencies] + +# standard = [ +# # For the test client +# "httpx >=0.23.0", +# # For templates +# "jinja2 >=2.11.2", +# # For forms and file uploads +# "python-multipart >=0.0.7", +# # For UJSONResponse +# "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", +# # For ORJSONResponse +# "orjson >=3.2.1", +# # To validate email fields +# "email_validator >=2.0.0", +# # Uvicorn with uvloop +# "uvicorn[standard] >=0.12.0", +# # Settings management +# "pydantic-settings >=2.0.0", +# # Extra Pydantic data types +# "pydantic-extra-types >=2.0.0", +# ] + all = [ + # # For the test client "httpx >=0.23.0", + # For templates "jinja2 >=2.11.2", + # For forms and file uploads "python-multipart >=0.0.7", + # For Starlette's SessionMiddleware, not commonly used with FastAPI "itsdangerous >=1.1.0", + # For Starlette's schema generation, would not be used with FastAPI "pyyaml >=5.3.1", + # For UJSONResponse "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", + # For ORJSONResponse "orjson >=3.2.1", + # To validate email fields "email_validator >=2.0.0", + # Uvicorn with uvloop "uvicorn[standard] >=0.12.0", + # Settings management "pydantic-settings >=2.0.0", + # Extra Pydantic data types "pydantic-extra-types >=2.0.0", ] -[tool.hatch.version] -path = "fastapi/__init__.py" +[tool.pdm] +version = { source = "file", path = "fastapi/__init__.py" } +distribution = true + +[tool.pdm.build] +source-includes = [ + "tests/", + "docs_src/", + "requirements*.txt", + "scripts/", + # For a test + "docs/en/docs/img/favicon.png", + ] + [tool.mypy] strict = true diff --git a/requirements-tests.txt b/requirements-tests.txt index 30762bc64..88a553330 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,19 +1,14 @@ --e . +-e .[all] -r requirements-docs-tests.txt -pydantic-settings >=2.0.0 pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 ruff ==0.2.0 -email_validator >=1.1.1,<3.0.0 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel sqlalchemy >=1.3.18,<1.4.43 databases[sqlite] >=0.3.2,<0.7.0 -orjson >=3.2.1,<4.0.0 -ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,<6.0.0 -python-multipart >=0.0.7,<0.1.0 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 python-jose[cryptography] >=3.3.0,<4.0.0 diff --git a/requirements.txt b/requirements.txt index ef25ec483..8e1fef341 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,6 @@ -e .[all] -r requirements-tests.txt -r requirements-docs.txt -uvicorn[standard] >=0.12.0,<0.23.0 pre-commit >=2.17.0,<4.0.0 # For generating screenshots playwright From 13ce009e9a80c01064ac158ab6da0d59f49c8590 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 29 Apr 2024 23:49:03 +0000 Subject: [PATCH 432/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 824a2bf82..cf7f2cbce 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Internal +* 🔧 Migrate from Hatch to PDM for the internal build. PR [#11498](https://github.com/tiangolo/fastapi/pull/11498) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pillow from 10.2.0 to 10.3.0. PR [#11403](https://github.com/tiangolo/fastapi/pull/11403) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Ungroup dependabot updates. PR [#11465](https://github.com/tiangolo/fastapi/pull/11465) by [@tiangolo](https://github.com/tiangolo). From f49da7420099a5ef6f383591d8e465e8dbf42ede Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Apr 2024 17:03:14 -0700 Subject: [PATCH 433/846] =?UTF-8?q?=F0=9F=94=A8=20Update=20internal=20scri?= =?UTF-8?q?pts=20and=20remove=20unused=20ones=20(#11499)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/build-docs.sh | 8 -------- scripts/clean.sh | 8 -------- scripts/docs-live.sh | 5 ----- scripts/format.sh | 2 +- scripts/lint.sh | 2 +- scripts/netlify-docs.sh | 14 -------------- scripts/publish.sh | 5 ----- 7 files changed, 2 insertions(+), 42 deletions(-) delete mode 100755 scripts/build-docs.sh delete mode 100755 scripts/clean.sh delete mode 100755 scripts/docs-live.sh delete mode 100755 scripts/netlify-docs.sh delete mode 100755 scripts/publish.sh diff --git a/scripts/build-docs.sh b/scripts/build-docs.sh deleted file mode 100755 index 7aa0a9a47..000000000 --- a/scripts/build-docs.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -set -e -set -x - -# Check README.md is up to date -python ./scripts/docs.py verify-docs -python ./scripts/docs.py build-all diff --git a/scripts/clean.sh b/scripts/clean.sh deleted file mode 100755 index d5a4b790a..000000000 --- a/scripts/clean.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/sh -e - -if [ -d 'dist' ] ; then - rm -r dist -fi -if [ -d 'site' ] ; then - rm -r site -fi diff --git a/scripts/docs-live.sh b/scripts/docs-live.sh deleted file mode 100755 index 30637a528..000000000 --- a/scripts/docs-live.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -set -e - -mkdocs serve --dev-addr 0.0.0.0:8008 diff --git a/scripts/format.sh b/scripts/format.sh index 11f25f1ce..45742f79a 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -1,5 +1,5 @@ #!/bin/sh -e set -x -ruff fastapi tests docs_src scripts --fix +ruff check fastapi tests docs_src scripts --fix ruff format fastapi tests docs_src scripts diff --git a/scripts/lint.sh b/scripts/lint.sh index c0e24db9f..18cf52a84 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -4,5 +4,5 @@ set -e set -x mypy fastapi -ruff fastapi tests docs_src scripts +ruff check fastapi tests docs_src scripts ruff format fastapi tests --check diff --git a/scripts/netlify-docs.sh b/scripts/netlify-docs.sh deleted file mode 100755 index 8f9065e23..000000000 --- a/scripts/netlify-docs.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -set -x -set -e -# Install pip -cd /tmp -curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py -python3.6 get-pip.py --user -cd - -# Install Flit to be able to install all -python3.6 -m pip install --user flit -# Install with Flit -python3.6 -m flit install --user --extras doc -# Finally, run mkdocs -python3.6 -m mkdocs build diff --git a/scripts/publish.sh b/scripts/publish.sh deleted file mode 100755 index 122728a60..000000000 --- a/scripts/publish.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -set -e - -flit publish From 62f82296f38e5e776a3c303621508bb3b5fbaeca Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 30 Apr 2024 00:03:35 +0000 Subject: [PATCH 434/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cf7f2cbce..db577922c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Internal +* 🔨 Update internal scripts and remove unused ones. PR [#11499](https://github.com/tiangolo/fastapi/pull/11499) by [@tiangolo](https://github.com/tiangolo). * 🔧 Migrate from Hatch to PDM for the internal build. PR [#11498](https://github.com/tiangolo/fastapi/pull/11498) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pillow from 10.2.0 to 10.3.0. PR [#11403](https://github.com/tiangolo/fastapi/pull/11403) by [@dependabot[bot]](https://github.com/apps/dependabot). From e0a969226132fe4660510398c4f61a0805c1e287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Apr 2024 17:31:58 -0700 Subject: [PATCH 435/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index db577922c..bd5b1b77f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Internal +* ⬆ Bump mkdocstrings[python] from 0.23.0 to 0.24.3. PR [#11469](https://github.com/tiangolo/fastapi/pull/11469) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔨 Update internal scripts and remove unused ones. PR [#11499](https://github.com/tiangolo/fastapi/pull/11499) by [@tiangolo](https://github.com/tiangolo). * 🔧 Migrate from Hatch to PDM for the internal build. PR [#11498](https://github.com/tiangolo/fastapi/pull/11498) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo). From 92b67b1b29dcfb24223d08a3862bd9d9d3ecb7b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Apr 2024 17:33:07 -0700 Subject: [PATCH 436/846] =?UTF-8?q?=F0=9F=93=9D=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 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bd5b1b77f..7a1939976 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,10 +7,6 @@ hide: ## Latest Changes -### Upgrades - -* ⬆ Bump mkdocstrings[python] from 0.23.0 to 0.24.3. PR [#11469](https://github.com/tiangolo/fastapi/pull/11469) by [@dependabot[bot]](https://github.com/apps/dependabot). - ### Docs * 📝 Update references to Python version, FastAPI supports all the current versions, no need to make the version explicit. PR [#11496](https://github.com/tiangolo/fastapi/pull/11496) by [@tiangolo](https://github.com/tiangolo). From 32be95dd867386d8331705a3c47d1b8b64bb1c9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Apr 2024 17:34:06 -0700 Subject: [PATCH 437/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?0.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 7a1939976..7109c47c3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -5,6 +5,8 @@ hide: # Release Notes +## 0.110.3 + ## Latest Changes ### Docs diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 32d5c41e1..d657d5484 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.110.3.dev2" +__version__ = "0.110.3" from starlette import status as status From ea1f2190d36af3642c793b2b0046c28cc4f1d901 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Apr 2024 23:38:13 -0700 Subject: [PATCH 438/846] =?UTF-8?q?=F0=9F=94=A7=20Add=20configs=20and=20se?= =?UTF-8?q?tup=20for=20`fastapi-slim`=20including=20optional=20extras=20`f?= =?UTF-8?q?astapi-slim[standard]`,=20and=20`fastapi`=20including=20by=20de?= =?UTF-8?q?fault=20the=20same=20`standard`=20extras=20(#11503)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/publish.yml | 1 + .github/workflows/test-redistribute.yml | 16 +++--- fastapi/__init__.py | 2 +- pdm_build.py | 39 ++++++++++++++ pyproject.toml | 72 ++++++++++++++++++------- 5 files changed, 103 insertions(+), 27 deletions(-) create mode 100644 pdm_build.py diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5ec81b02b..e7c69befc 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -12,6 +12,7 @@ jobs: matrix: package: - fastapi + - fastapi-slim permissions: id-token: write steps: diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml index c2e05013b..a249b18a7 100644 --- a/.github/workflows/test-redistribute.yml +++ b/.github/workflows/test-redistribute.yml @@ -12,6 +12,11 @@ on: jobs: test-redistribute: runs-on: ubuntu-latest + strategy: + matrix: + package: + - fastapi + - fastapi-slim steps: - name: Dump GitHub context env: @@ -22,12 +27,11 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.10" - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - name: Install build dependencies run: pip install build - name: Build source distribution + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build --sdist - name: Decompress source distribution run: | @@ -35,16 +39,16 @@ jobs: tar xvf fastapi*.tar.gz - name: Install test dependencies run: | - cd dist/fastapi-*/ + cd dist/fastapi*/ pip install -r requirements-tests.txt - name: Run source distribution tests run: | - cd dist/fastapi-*/ + cd dist/fastapi*/ bash scripts/test.sh - name: Build wheel distribution run: | cd dist - pip wheel --no-deps fastapi-*.tar.gz + pip wheel --no-deps fastapi*.tar.gz - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} diff --git a/fastapi/__init__.py b/fastapi/__init__.py index d657d5484..006c0ec5a 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.110.3" +__version__ = "0.111.0.dev1" from starlette import status as status diff --git a/pdm_build.py b/pdm_build.py new file mode 100644 index 000000000..45922d471 --- /dev/null +++ b/pdm_build.py @@ -0,0 +1,39 @@ +import os +from typing import Any, Dict, List + +from pdm.backend.hooks import Context + +TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "fastapi") + + +def pdm_build_initialize(context: Context) -> None: + metadata = context.config.metadata + # Get custom config for the current package, from the env var + config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][ + "_internal-slim-build" + ]["packages"][TIANGOLO_BUILD_PACKAGE] + project_config: Dict[str, Any] = config["project"] + # Get main optional dependencies, extras + optional_dependencies: Dict[str, List[str]] = metadata.get( + "optional-dependencies", {} + ) + # Get custom optional dependencies name to always include in this (non-slim) package + include_optional_dependencies: List[str] = config.get( + "include-optional-dependencies", [] + ) + # Override main [project] configs with custom configs for this package + for key, value in project_config.items(): + metadata[key] = value + # Get custom build config for the current package + build_config: Dict[str, Any] = ( + config.get("tool", {}).get("pdm", {}).get("build", {}) + ) + # Override PDM build config with custom build config for this package + for key, value in build_config.items(): + context.config.build_config[key] = value + # Get main dependencies + dependencies: List[str] = metadata.get("dependencies", []) + # Add optional dependencies to the default dependencies for this (non-slim) package + for include_optional in include_optional_dependencies: + optional_dependencies_group = optional_dependencies.get(include_optional, []) + dependencies.extend(optional_dependencies_group) diff --git a/pyproject.toml b/pyproject.toml index 8f7e0313c..05c68841f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,26 +53,27 @@ Repository = "https://github.com/tiangolo/fastapi" [project.optional-dependencies] -# standard = [ -# # For the test client -# "httpx >=0.23.0", -# # For templates -# "jinja2 >=2.11.2", -# # For forms and file uploads -# "python-multipart >=0.0.7", -# # For UJSONResponse -# "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", -# # For ORJSONResponse -# "orjson >=3.2.1", -# # To validate email fields -# "email_validator >=2.0.0", -# # Uvicorn with uvloop -# "uvicorn[standard] >=0.12.0", -# # Settings management -# "pydantic-settings >=2.0.0", -# # Extra Pydantic data types -# "pydantic-extra-types >=2.0.0", -# ] +standard = [ + # For the test client + "httpx >=0.23.0", + # For templates + "jinja2 >=2.11.2", + # For forms and file uploads + "python-multipart >=0.0.7", + # For UJSONResponse + "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", + # For ORJSONResponse + "orjson >=3.2.1", + # To validate email fields + "email_validator >=2.0.0", + # Uvicorn with uvloop + "uvicorn[standard] >=0.12.0", + # TODO: this should be part of some pydantic optional extra dependencies + # # Settings management + # "pydantic-settings >=2.0.0", + # # Extra Pydantic data types + # "pydantic-extra-types >=2.0.0", +] all = [ # # For the test client @@ -113,6 +114,37 @@ source-includes = [ "docs/en/docs/img/favicon.png", ] +[tool.tiangolo._internal-slim-build.packages.fastapi-slim.project] +name = "fastapi-slim" + +[tool.tiangolo._internal-slim-build.packages.fastapi] +include-optional-dependencies = ["standard"] + +[tool.tiangolo._internal-slim-build.packages.fastapi.project.optional-dependencies] +all = [ + # # For the test client + "httpx >=0.23.0", + # For templates + "jinja2 >=2.11.2", + # For forms and file uploads + "python-multipart >=0.0.7", + # For Starlette's SessionMiddleware, not commonly used with FastAPI + "itsdangerous >=1.1.0", + # For Starlette's schema generation, would not be used with FastAPI + "pyyaml >=5.3.1", + # For UJSONResponse + "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", + # For ORJSONResponse + "orjson >=3.2.1", + # To validate email fields + "email_validator >=2.0.0", + # Uvicorn with uvloop + "uvicorn[standard] >=0.12.0", + # Settings management + "pydantic-settings >=2.0.0", + # Extra Pydantic data types + "pydantic-extra-types >=2.0.0", +] [tool.mypy] strict = true From a94ef3351e0a25ffa45d131b9ba9b0f7f7c31fe5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 30 Apr 2024 06:38:41 +0000 Subject: [PATCH 439/846] =?UTF-8?q?=F0=9F=93=9D=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 7109c47c3..5d64c8d0b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,10 @@ hide: ## Latest Changes +### Refactors + +* 🔧 Add configs and setup for `fastapi-slim` including optional extras `fastapi-slim[standard]`, and `fastapi` including by default the same `standard` extras. PR [#11503](https://github.com/tiangolo/fastapi/pull/11503) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Update references to Python version, FastAPI supports all the current versions, no need to make the version explicit. PR [#11496](https://github.com/tiangolo/fastapi/pull/11496) by [@tiangolo](https://github.com/tiangolo). From d71be59217ccb9d115a5a2c21157a5ed97c52990 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 2 May 2024 15:37:31 -0700 Subject: [PATCH 440/846] =?UTF-8?q?=E2=9C=A8=20Add=20FastAPI=20CLI,=20the?= =?UTF-8?q?=20new=20`fastapi`=20command=20(#11522)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 70 ++++++++++------- docs/en/docs/advanced/behind-a-proxy.md | 12 +-- docs/en/docs/advanced/openapi-callbacks.md | 2 +- docs/en/docs/advanced/openapi-webhooks.md | 2 +- docs/en/docs/advanced/settings.md | 2 +- docs/en/docs/advanced/websockets.md | 4 +- docs/en/docs/advanced/wsgi.md | 2 +- docs/en/docs/css/termynal.css | 1 + docs/en/docs/deployment/concepts.md | 2 +- docs/en/docs/deployment/docker.md | 35 ++++----- docs/en/docs/deployment/manually.md | 88 ++++++++++++++++++++-- docs/en/docs/fastapi-cli.md | 84 +++++++++++++++++++++ docs/en/docs/features.md | 4 +- docs/en/docs/index.md | 70 ++++++++++------- docs/en/docs/tutorial/first-steps.md | 85 ++++++++++----------- docs/en/docs/tutorial/index.md | 75 +++++++++++------- docs/en/mkdocs.yml | 1 + pyproject.toml | 2 + 18 files changed, 376 insertions(+), 165 deletions(-) create mode 100644 docs/en/docs/fastapi-cli.md diff --git a/README.md b/README.md index c7adc49cd..1db8a8949 100644 --- a/README.md +++ b/README.md @@ -139,18 +139,6 @@ $ pip install fastapi </div> -You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. - -<div class="termy"> - -```console -$ pip install "uvicorn[standard]" - ----> 100% -``` - -</div> - ## Example ### Create it @@ -211,11 +199,24 @@ Run the server with: <div class="termy"> ```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -223,13 +224,13 @@ INFO: Application startup complete. </div> <details markdown="1"> -<summary>About the command <code>uvicorn main:app --reload</code>...</summary> +<summary>About the command <code>fastapi dev main.py</code>...</summary> -The command `uvicorn main:app` refers to: +The command `fastapi dev` reads your `main.py` file, detects the **FastAPI** app in it, and starts a server using <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>. -* `main`: the file `main.py` (the Python "module"). -* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -* `--reload`: make the server restart after code changes. Only do this for development. +By default, `fastapi dev` will start with auto-reload enabled for local development. + +You can read more about it in the <a href="https://fastapi.tiangolo.com/fastapi-cli/" target="_blank">FastAPI CLI docs</a>. </details> @@ -302,7 +303,7 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -The server should reload automatically (because you added `--reload` to the `uvicorn` command above). +The `fastapi dev` server should reload automatically. ### Interactive API docs upgrade @@ -446,7 +447,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>. -## Optional Dependencies +## Dependencies Used by Pydantic: @@ -459,16 +460,33 @@ Used by Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Required if you want to use the `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration. * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. -* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support. -* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). Used by FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. +* `fastapi-cli` - to provide the `fastapi` command. + +When you install `fastapi` it comes these standard dependencies. + +## `fastapi-slim` + +If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. + +When you install with: + +```bash +pip install fastapi +``` + +...it includes the same code and dependencies as: + +```bash +pip install "fastapi-slim[standard]" +``` -You can install all of these with `pip install "fastapi[all]"`. +The standard extra dependencies are the ones mentioned above. ## License diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index b25c11b17..c17b024f9 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -22,7 +22,7 @@ Even though all your code is written assuming there's just `/app`. {!../../../docs_src/behind_a_proxy/tutorial001.py!} ``` -And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, 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`. +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`. Up to here, everything would work as normally. @@ -63,7 +63,7 @@ The docs UI would also need the OpenAPI schema to declare that this API `server` } ``` -In this example, the "Proxy" could be something like **Traefik**. And the server would be something like **Uvicorn**, running your FastAPI application. +In this example, the "Proxy" could be something like **Traefik**. And the server would be something like FastAPI CLI with **Uvicorn**, running your FastAPI application. ### Providing the `root_path` @@ -72,7 +72,7 @@ To achieve this, you can use the command line option `--root-path` like: <div class="termy"> ```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -101,7 +101,7 @@ Then, if you start Uvicorn with: <div class="termy"> ```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -216,12 +216,12 @@ INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml </div> -And now start your app with Uvicorn, using the `--root-path` option: +And now start your app, using the `--root-path` option: <div class="termy"> ```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 2785ee140..1ff51f077 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -172,7 +172,7 @@ Now use the parameter `callbacks` in *your API's path operation decorator* to pa ### Check the docs -Now you can start your app with Uvicorn and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. +Now you can start your app and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look like: diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index 63cbdc610..f7f43b357 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -44,7 +44,7 @@ This is because it is expected that **your users** would define the actual **URL ### Check the docs -Now you can start your app with Uvicorn and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. +Now you can start your app and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. You will see your docs have the normal *path operations* and now also some **webhooks**: diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 8f72bf63a..f9b525a58 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -199,7 +199,7 @@ Next, you would run the server passing the configurations as environment variabl <div class="termy"> ```console -$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index b8dfab1d1..3b6471dd5 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -72,7 +72,7 @@ If your file is named `main.py`, run your application with: <div class="termy"> ```console -$ uvicorn main:app --reload +$ fastapi dev main.py <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -160,7 +160,7 @@ If your file is named `main.py`, run your application with: <div class="termy"> ```console -$ uvicorn main:app --reload +$ fastapi dev main.py <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index 852e25019..f07609ed6 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -22,7 +22,7 @@ Now, every request under the path `/v1/` will be handled by the Flask applicatio And the rest will be handled by **FastAPI**. -If you run it with Uvicorn and go to <a href="http://localhost:8000/v1/" class="external-link" target="_blank">http://localhost:8000/v1/</a> you will see the response from Flask: +If you run it and go to <a href="http://localhost:8000/v1/" class="external-link" target="_blank">http://localhost:8000/v1/</a> you will see the response from Flask: ```txt Hello, World from Flask! diff --git a/docs/en/docs/css/termynal.css b/docs/en/docs/css/termynal.css index 406c00897..af2fbe670 100644 --- a/docs/en/docs/css/termynal.css +++ b/docs/en/docs/css/termynal.css @@ -26,6 +26,7 @@ position: relative; -webkit-box-sizing: border-box; box-sizing: border-box; + line-height: 1.2; } [data-termynal]:before { diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index b771ae663..9701c67d8 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**, ### In a Remote Server -When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to run Uvicorn (or similar) manually, the same way you do when developing locally. +When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to use `fastapi run`, Uvicorn (or similar) manually, the same way you do when developing locally. And it will work and will be useful **during development**. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 467ba72de..5181f77e0 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -21,10 +21,10 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--port", "80"] # If running behind a proxy like Nginx or Traefik add --proxy-headers -# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"] ``` </details> @@ -113,9 +113,8 @@ You would of course use the same ideas you read in [About FastAPI versions](vers For example, your `requirements.txt` could look like: ``` -fastapi>=0.68.0,<0.69.0 -pydantic>=1.8.0,<2.0.0 -uvicorn>=0.15.0,<0.16.0 +fastapi>=0.112.0,<0.113.0 +pydantic>=2.7.0,<3.0.0 ``` And you would normally install those package dependencies with `pip`, for example: @@ -125,7 +124,7 @@ And you would normally install those package dependencies with `pip`, for exampl ```console $ pip install -r requirements.txt ---> 100% -Successfully installed fastapi pydantic uvicorn +Successfully installed fastapi pydantic ``` </div> @@ -133,8 +132,6 @@ Successfully installed fastapi pydantic uvicorn !!! info There are other formats and tools to define and install package dependencies. - I'll show you an example using Poetry later in a section below. 👇 - ### Create the **FastAPI** Code * Create an `app` directory and enter it. @@ -180,7 +177,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app # (6) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` 1. Start from the official Python base image. @@ -214,14 +211,12 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] So, it's important to put this **near the end** of the `Dockerfile`, to optimize the container image build times. -6. Set the **command** to run the `uvicorn` server. +6. Set the **command** to use `fastapi run`, which uses Uvicorn underneath. `CMD` takes a list of strings, each of these strings is what you would type in the command line separated by spaces. This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`. - Because the program will be started at `/code` and inside of it is the directory `./app` with your code, **Uvicorn** will be able to see and **import** `app` from `app.main`. - !!! tip Review what each line does by clicking each number bubble in the code. 👆 @@ -238,10 +233,10 @@ You should now have a directory structure like: #### Behind a TLS Termination Proxy -If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc. +If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn (through the FastAPI CLI) to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc. ```Dockerfile -CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] ``` #### Docker Cache @@ -362,14 +357,14 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./main.py /code/ # (2) -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "main.py", "--port", "80"] ``` 1. Copy the `main.py` file to the `/code` directory directly (without any `./app` directory). -2. Run Uvicorn and tell it to import the `app` object from `main` (instead of importing from `app.main`). +2. Use `fastapi run` to serve your application in the single file `main.py`. -Then adjust the Uvicorn command to use the new module `main` instead of `app.main` to import the FastAPI object `app`. +When you pass the file to `fastapi run` it will detect automatically that it is a single file and not part of a package and will know how to import it and serve your FastAPI app. 😎 ## Deployment Concepts @@ -626,7 +621,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app # (11) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` 1. This is the first stage, it is named `requirements-stage`. @@ -655,7 +650,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 10. Copy the `app` directory to the `/code` directory. -11. Run the `uvicorn` command, telling it to use the `app` object imported from `app.main`. +11. Use the `fastapi run` command to run your app. !!! tip Click the bubble numbers to see what each line does. @@ -677,7 +672,7 @@ Then in the next (and final) stage you would build the image more or less in the Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command: ```Dockerfile -CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] ``` ## Recap diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index b10a3686d..3baaa8253 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -1,8 +1,68 @@ -# Run a Server Manually - Uvicorn +# Run a Server Manually -The main thing you need to run a **FastAPI** application in a remote server machine is an ASGI server program like **Uvicorn**. +## Use the `fastapi run` Command -There are 3 main alternatives: +In short, use `fastapi run` to serve your FastAPI application: + +<div class="termy"> + +```console +$ <font color="#4E9A06">fastapi</font> run <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <font color="#4E9A06">╭─────────── FastAPI CLI - Production mode ───────────╮</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ Serving at: http://0.0.0.0:8000 │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ API docs: http://0.0.0.0:8000/docs │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ Running in production mode, for development use: │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ </font><font color="#8AE234"><b>fastapi dev</b></font><font color="#4E9A06"> │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">╰─────────────────────────────────────────────────────╯</font> + +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2306215</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://0.0.0.0:8000</b> (Press CTRL+C to quit) +``` + +</div> + +That would work for most of the cases. 😎 + +You could use that command for example to start your **FastAPI** app in a container, in a server, etc. + +## ASGI Servers + +Let's go a little deeper into the details. + +FastAPI uses a standard for building Python web frameworks and servers called <abbr title="Asynchronous Server Gateway Interface">ASGI</abbr>. FastAPI is an ASGI web framework. + +The main thing you need to run a **FastAPI** application (or any other ASGI application) in a remote server machine is an ASGI server program like **Uvicorn**, this is the one that comes by default in the `fastapi` command. + +There are several alternatives, including: * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: a high performance ASGI server. * <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: an ASGI server compatible with HTTP/2 and Trio among other features. @@ -20,7 +80,9 @@ When referring to the remote machine, it's common to call it **server**, but als ## Install the Server Program -You can install an ASGI compatible server with: +When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command. + +But you can also install an ASGI server manually: === "Uvicorn" @@ -41,6 +103,8 @@ You can install an ASGI compatible server with: That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. + When you install FastAPI with something like `pip install fastapi` you already get `uvicorn[standard]` as well. + === "Hypercorn" * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2. @@ -59,7 +123,7 @@ You can install an ASGI compatible server with: ## Run the Server Program -You can then run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.: +If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application: === "Uvicorn" @@ -85,8 +149,20 @@ You can then run your application the same way you have done in the tutorials, b </div> +!!! note + The command `uvicorn main:app` refers to: + + * `main`: the file `main.py` (the Python "module"). + * `app`: the object created inside of `main.py` with the line `app = FastAPI()`. + + It is equivalent to: + + ```Python + from main import app + ``` + !!! warning - Remember to remove the `--reload` option if you were using it. + Uvicorn and others support a `--reload` option that is useful during development. The `--reload` option consumes much more resources, is more unstable, etc. diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md new file mode 100644 index 000000000..0e6295bb4 --- /dev/null +++ b/docs/en/docs/fastapi-cli.md @@ -0,0 +1,84 @@ +# FastAPI CLI + +**FastAPI CLI** is a command line program `fastapi` that you can use to serve your FastAPI app, manage your FastAPI project, and more. + +When you install FastAPI (e.g. with `pip install fastapi`), it includes a package called `fastapi-cli`, this package provides the `fastapi` command in the terminal. + +To run your FastAPI app for development, you can use the `fastapi dev` command: + +<div class="termy"> + +```console +$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span> + +<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit) +<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font> +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +``` + +</div> + +That command line program called `fastapi` is **FastAPI CLI**. + +FastAPI CLI takes the path to your Python program and automatically detects the variable with the FastAPI (commonly named `app`) and how to import it, and then serves it. + +For production you would use `fastapi run` instead. 🚀 + +Internally, **FastAPI CLI** uses <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>, a high-performance, production-ready, ASGI server. 😎 + +## `fastapi dev` + +When you run `fastapi dev`, it will run on development mode. + +By default, it will have **auto-reload** enabled, so it will automatically reload the server when you make changes to your code. This is resource intensive and could be less stable than without it, you should only use it for development. + +By default it will listen on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`). + +## `fastapi run` + +When you run `fastapi run`, it will run on production mode by default. + +It will have **auto-reload disabled** by default. + +It will listen on the IP address `0.0.0.0`, which means all the available IP addresses, this way it will be publicly accessible to anyone that can communicate with the machine. This is how you would normally run it in production, for example, in a container. + +In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. + +!!! tip + You can learn more about it in the [deployment documentation](../deployment/index.md){.internal-link target=_blank}. diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 6f0e74b3d..8afa13a98 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -30,7 +30,7 @@ Interactive API documentation and exploration web user interfaces. As the framew ### Just Modern Python -It's all based on standard **Python 3.6 type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python. +It's all based on standard **Python type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python. If you need a 2 minute refresher of how to use Python types (even if you don't use FastAPI), check the short tutorial: [Python Types](python-types.md){.internal-link target=_blank}. @@ -77,7 +77,7 @@ my_second_user: User = User(**second_user_data) All the framework was designed to be easy and intuitive to use, all the decisions were tested on multiple editors even before starting development, to ensure the best development experience. -In the last Python developer survey it was clear <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">that the most used feature is "autocompletion"</a>. +In the Python developer surveys, it's clear <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">that one of the most used features is "autocompletion"</a>. The whole **FastAPI** framework is based to satisfy that. Autocompletion works everywhere. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 508e859a1..434c70893 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -141,18 +141,6 @@ $ pip install fastapi </div> -You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. - -<div class="termy"> - -```console -$ pip install "uvicorn[standard]" - ----> 100% -``` - -</div> - ## Example ### Create it @@ -213,11 +201,24 @@ Run the server with: <div class="termy"> ```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -225,13 +226,13 @@ INFO: Application startup complete. </div> <details markdown="1"> -<summary>About the command <code>uvicorn main:app --reload</code>...</summary> +<summary>About the command <code>fastapi dev main.py</code>...</summary> -The command `uvicorn main:app` refers to: +The command `fastapi dev` reads your `main.py` file, detects the **FastAPI** app in it, and starts a server using <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>. -* `main`: the file `main.py` (the Python "module"). -* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -* `--reload`: make the server restart after code changes. Only do this for development. +By default, `fastapi dev` will start with auto-reload enabled for local development. + +You can read more about it in the <a href="https://fastapi.tiangolo.com/fastapi-cli/" target="_blank">FastAPI CLI docs</a>. </details> @@ -304,7 +305,7 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -The server should reload automatically (because you added `--reload` to the `uvicorn` command above). +The `fastapi dev` server should reload automatically. ### Interactive API docs upgrade @@ -448,7 +449,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>. -## Optional Dependencies +## Dependencies Used by Pydantic: @@ -461,16 +462,33 @@ Used by Starlette: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Required if you want to use the `TestClient`. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration. * <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. -* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support. -* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). Used by FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. * <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. +* `fastapi-cli` - to provide the `fastapi` command. + +When you install `fastapi` it comes these standard dependencies. + +## `fastapi-slim` + +If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. + +When you install with: + +```bash +pip install fastapi +``` + +...it includes the same code and dependencies as: + +```bash +pip install "fastapi-slim[standard]" +``` -You can install all of these with `pip install "fastapi[all]"`. +The standard extra dependencies are the ones mentioned above. ## License diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index cfa159329..35b2feb41 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -13,24 +13,51 @@ Run the live server: <div class="termy"> ```console -$ uvicorn main:app --reload - -<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -<span style="color: green;">INFO</span>: Started reloader process [28720] -<span style="color: green;">INFO</span>: Started server process [28722] -<span style="color: green;">INFO</span>: Waiting for application startup. -<span style="color: green;">INFO</span>: Application startup complete. +$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span> + +<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit) +<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font> +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. ``` </div> -!!! note - The command `uvicorn main:app` refers to: - - * `main`: the file `main.py` (the Python "module"). - * `app`: the object created inside of `main.py` with the line `app = FastAPI()`. - * `--reload`: make the server restart after code changes. Only use for development. - In the output, there's a line with something like: ```hl_lines="4" @@ -151,36 +178,6 @@ Here the `app` variable will be an "instance" of the class `FastAPI`. This will be the main point of interaction to create all your API. -This `app` is the same one referred by `uvicorn` in the command: - -<div class="termy"> - -```console -$ uvicorn main:app --reload - -<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -</div> - -If you create your app like: - -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` - -And put it in a file `main.py`, then you would call `uvicorn` like: - -<div class="termy"> - -```console -$ uvicorn main:my_awesome_api --reload - -<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -</div> - ### Step 3: create a *path operation* #### Path diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 75665324d..74fe06acd 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -12,18 +12,53 @@ So you can come back and see exactly what you need. All the code blocks can be copied and used directly (they are actually tested Python files). -To run any of the examples, copy the code to a file `main.py`, and start `uvicorn` with: +To run any of the examples, copy the code to a file `main.py`, and start `fastapi dev` with: <div class="termy"> ```console -$ uvicorn main:app --reload - -<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -<span style="color: green;">INFO</span>: Started reloader process [28720] -<span style="color: green;">INFO</span>: Started server process [28722] -<span style="color: green;">INFO</span>: Waiting for application startup. -<span style="color: green;">INFO</span>: Application startup complete. +$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span> + +<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit) +<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font> +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +</pre> ``` </div> @@ -36,38 +71,22 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing ## Install FastAPI -The first step is to install FastAPI. - -For the tutorial, you might want to install it with all the optional dependencies and features: +The first step is to install FastAPI: <div class="termy"> ```console -$ pip install "fastapi[all]" +$ pip install fastapi ---> 100% ``` </div> -...that also includes `uvicorn`, that you can use as the server that runs your code. - !!! note - You can also install it part by part. - - This is what you would probably do once you want to deploy your application to production: - - ``` - pip install fastapi - ``` - - Also install `uvicorn` to work as the server: - - ``` - pip install "uvicorn[standard]" - ``` + When you install with `pip install fastapi` it comes with some default optional standard dependencies. - And the same for each of the optional dependencies that you want to use. + If you don't want to have those optional dependencies, you can instead install `pip install fastapi-slim`. ## Advanced User Guide diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 933e7e4a2..05dffb706 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -167,6 +167,7 @@ nav: - advanced/openapi-webhooks.md - advanced/wsgi.md - advanced/generate-clients.md + - fastapi-cli.md - Deployment: - deployment/index.md - deployment/versions.md diff --git a/pyproject.toml b/pyproject.toml index 05c68841f..a79845646 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,6 +54,7 @@ Repository = "https://github.com/tiangolo/fastapi" [project.optional-dependencies] standard = [ + "fastapi-cli >=0.0.2", # For the test client "httpx >=0.23.0", # For templates @@ -76,6 +77,7 @@ standard = [ ] all = [ + "fastapi-cli >=0.0.2", # # For the test client "httpx >=0.23.0", # For templates From 9ed94e4f6893005239c20e7400f3bb4a7093cef0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 2 May 2024 22:37:53 +0000 Subject: [PATCH 441/846] =?UTF-8?q?=F0=9F=93=9D=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 5d64c8d0b..0206e3aae 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,10 @@ hide: ## Latest Changes +### Features + +* ✨ Add FastAPI CLI, the new `fastapi` command. PR [#11522](https://github.com/tiangolo/fastapi/pull/11522) by [@tiangolo](https://github.com/tiangolo). + ### Refactors * 🔧 Add configs and setup for `fastapi-slim` including optional extras `fastapi-slim[standard]`, and `fastapi` including by default the same `standard` extras. PR [#11503](https://github.com/tiangolo/fastapi/pull/11503) by [@tiangolo](https://github.com/tiangolo). From 67da3bb52ebe79657380e2f1b9ba098cc95eca75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 2 May 2024 15:50:18 -0700 Subject: [PATCH 442/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?1.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 6 ++++-- fastapi/__init__.py | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0206e3aae..f5723ac99 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -5,10 +5,10 @@ hide: # Release Notes -## 0.110.3 - ## Latest Changes +## 0.111.0 + ### Features * ✨ Add FastAPI CLI, the new `fastapi` command. PR [#11522](https://github.com/tiangolo/fastapi/pull/11522) by [@tiangolo](https://github.com/tiangolo). @@ -17,6 +17,8 @@ hide: * 🔧 Add configs and setup for `fastapi-slim` including optional extras `fastapi-slim[standard]`, and `fastapi` including by default the same `standard` extras. PR [#11503](https://github.com/tiangolo/fastapi/pull/11503) by [@tiangolo](https://github.com/tiangolo). +## 0.110.3 + ### Docs * 📝 Update references to Python version, FastAPI supports all the current versions, no need to make the version explicit. PR [#11496](https://github.com/tiangolo/fastapi/pull/11496) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 006c0ec5a..04305ad8b 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.111.0.dev1" +__version__ = "0.111.0" from starlette import status as status From ab8f5572500717b8980fe55d8c37de0ae6367efd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 2 May 2024 17:16:02 -0700 Subject: [PATCH 443/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f5723ac99..173ceee92 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -12,6 +12,7 @@ hide: ### Features * ✨ Add FastAPI CLI, the new `fastapi` command. PR [#11522](https://github.com/tiangolo/fastapi/pull/11522) by [@tiangolo](https://github.com/tiangolo). + * New docs: [FastAPI CLI](https://fastapi.tiangolo.com/fastapi-cli/). ### Refactors From 1c3e6918750ccb3f20ea260e9a4238ce2c0e5f63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 2 May 2024 17:20:30 -0700 Subject: [PATCH 444/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 173ceee92..827ac53d3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,34 @@ hide: * ✨ Add FastAPI CLI, the new `fastapi` command. PR [#11522](https://github.com/tiangolo/fastapi/pull/11522) by [@tiangolo](https://github.com/tiangolo). * New docs: [FastAPI CLI](https://fastapi.tiangolo.com/fastapi-cli/). +Try it out with: + +```console +$ pip install --upgrade fastapi + +$ fastapi dev main.py + + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + ### Refactors * 🔧 Add configs and setup for `fastapi-slim` including optional extras `fastapi-slim[standard]`, and `fastapi` including by default the same `standard` extras. PR [#11503](https://github.com/tiangolo/fastapi/pull/11503) by [@tiangolo](https://github.com/tiangolo). From 96b1625eedf6479fe841d5657b152cb64333aad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 3 May 2024 15:21:11 -0700 Subject: [PATCH 445/846] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20(#11511)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions <github-actions@github.com> --- docs/en/data/github_sponsors.yml | 131 ++--- docs/en/data/people.yml | 804 ++++++++++++++++--------------- 2 files changed, 484 insertions(+), 451 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 385bcb498..cd7ea52ac 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -56,10 +56,7 @@ sponsors: - login: acsone avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4 url: https://github.com/acsone -- - login: owlur - avatarUrl: https://avatars.githubusercontent.com/u/20010787?v=4 - url: https://github.com/owlur - - login: Trivie +- - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie - - login: americanair @@ -98,15 +95,15 @@ sponsors: - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - - login: koconder - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 - url: https://github.com/koconder - login: b-rad-c avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 url: https://github.com/b-rad-c - login: ehaca avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 url: https://github.com/ehaca + - login: raphaellaude + avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=9ae4b158c0d2cb29ebd46df6b6edb7de08a67566&v=4 + url: https://github.com/raphaellaude - login: timlrx avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 url: https://github.com/timlrx @@ -119,6 +116,12 @@ sponsors: - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure + - login: wdwinslow + avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 + url: https://github.com/wdwinslow + - login: catherinenelson1 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 + url: https://github.com/catherinenelson1 - login: jsoques avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 url: https://github.com/jsoques @@ -146,15 +149,9 @@ sponsors: - login: RaamEEIL avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 url: https://github.com/RaamEEIL - - login: Filimoa - avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 - url: https://github.com/Filimoa - - login: prodhype - avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 - url: https://github.com/prodhype - - login: yakkonaut - avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 - url: https://github.com/yakkonaut + - login: CodeProcessor + avatarUrl: https://avatars.githubusercontent.com/u/24785073?u=b4dd0ef3f42ced86412a060dd2bd6c8caaf771aa&v=4 + url: https://github.com/CodeProcessor - login: patsatsia avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 url: https://github.com/patsatsia @@ -170,15 +167,15 @@ sponsors: - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare + - login: jugeeem + avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 + url: https://github.com/jugeeem - login: apitally avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 url: https://github.com/apitally - login: logic-automation avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 url: https://github.com/logic-automation - - login: thenickben - avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 - url: https://github.com/thenickben - login: ddilidili avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 url: https://github.com/ddilidili @@ -188,12 +185,15 @@ sponsors: - login: dudikbender avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 url: https://github.com/dudikbender + - login: prodhype + avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 + url: https://github.com/prodhype + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith - - login: mickaelandrieu - avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 - url: https://github.com/mickaelandrieu - login: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 @@ -209,21 +209,24 @@ sponsors: - login: Shark009 avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 url: https://github.com/Shark009 - - login: dblackrun - avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 - url: https://github.com/dblackrun - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden - login: andreaso avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 url: https://github.com/andreaso + - login: robintw + avatarUrl: https://avatars.githubusercontent.com/u/296686?v=4 + url: https://github.com/robintw - login: pamelafox avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4 url: https://github.com/pamelafox - login: ericof avatarUrl: https://avatars.githubusercontent.com/u/306014?u=cf7c8733620397e6584a451505581c01c5d842d7&v=4 url: https://github.com/ericof + - login: falquaddoomi + avatarUrl: https://avatars.githubusercontent.com/u/312923?u=aab6efa665ed9495ce37371af1cd637ec554772f&v=4 + url: https://github.com/falquaddoomi - login: wshayes avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes @@ -236,6 +239,12 @@ sponsors: - login: mintuhouse avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 url: https://github.com/mintuhouse + - login: dblackrun + avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 + url: https://github.com/dblackrun + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw - login: Rehket avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 url: https://github.com/Rehket @@ -245,12 +254,6 @@ sponsors: - login: TrevorBenson avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=afdd1766fdb79e04e59094cc6a54cd011ee7f686&v=4 url: https://github.com/TrevorBenson - - login: wdwinslow - avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 - url: https://github.com/wdwinslow - - login: catherinenelson1 - avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 - url: https://github.com/catherinenelson1 - login: zsinx6 avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 url: https://github.com/zsinx6 @@ -284,15 +287,15 @@ sponsors: - login: FernandoCelmer avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - - login: getsentry avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 url: https://github.com/getsentry - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy + - login: SebTota + avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 + url: https://github.com/SebTota - login: nisutec avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 url: https://github.com/nisutec @@ -312,11 +315,14 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 url: https://github.com/engineerjoe440 - login: bnkc - avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4 url: https://github.com/bnkc - - login: petercool - avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 - url: https://github.com/petercool + - login: DevOpsKev + avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4 + url: https://github.com/DevOpsKev + - login: Zuzah + avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 + url: https://github.com/Zuzah - login: JimFawkes avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 url: https://github.com/JimFawkes @@ -338,9 +344,6 @@ sponsors: - login: pers0n4 avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 url: https://github.com/pers0n4 - - login: SebTota - avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 - url: https://github.com/SebTota - login: fernandosmither avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 url: https://github.com/fernandosmither @@ -350,12 +353,15 @@ sponsors: - login: PelicanQ avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 url: https://github.com/PelicanQ - - login: jugeeem - avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 - url: https://github.com/jugeeem - login: tahmarrrr23 avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 url: https://github.com/tahmarrrr23 + - login: zk-Call + avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4 + url: https://github.com/zk-Call + - login: petercool + avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 + url: https://github.com/petercool - login: curegit avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 url: https://github.com/curegit @@ -375,11 +381,17 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan - login: hgalytoby - avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 url: https://github.com/hgalytoby - login: conservative-dude avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 url: https://github.com/conservative-dude + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji + - login: browniebroke + avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 + url: https://github.com/browniebroke - login: miguelgr avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4 url: https://github.com/miguelgr @@ -419,12 +431,6 @@ sponsors: - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 url: https://github.com/securancy - - login: tochikuji - avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 - url: https://github.com/tochikuji - - login: browniebroke - avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 - url: https://github.com/browniebroke - login: KentShikama avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 url: https://github.com/KentShikama @@ -470,6 +476,9 @@ sponsors: - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa + - login: Graeme22 + avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 + url: https://github.com/Graeme22 - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -488,24 +497,24 @@ sponsors: - login: jakeecolution avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 url: https://github.com/jakeecolution -- - login: abizovnuralem - avatarUrl: https://avatars.githubusercontent.com/u/33475993?u=6ce72b11a16a8232d3dd1f958f460b4735f520d8&v=4 - url: https://github.com/abizovnuralem - - login: danburonline + - login: stephane-rbn + avatarUrl: https://avatars.githubusercontent.com/u/5939522?u=eb7ffe768fa3bcbcd04de14fe4a47444cc00ec4c&v=4 + url: https://github.com/stephane-rbn +- - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu + - login: Mehver + avatarUrl: https://avatars.githubusercontent.com/u/75297777?u=dcd857f4278df055d98cd3486c2ce8bad368eb50&v=4 + url: https://github.com/Mehver - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - login: YungBricoCoop - avatarUrl: https://avatars.githubusercontent.com/u/42273436?u=80470b400c416d1eabc2cc71b1efffc0e3503146&v=4 - url: https://github.com/YungBricoCoop - - login: nlazaro - avatarUrl: https://avatars.githubusercontent.com/u/44237350?u=939a570fc965d93e9db1284b5acc173c1a0be4a0&v=4 - url: https://github.com/nlazaro + - login: zee229 + avatarUrl: https://avatars.githubusercontent.com/u/48365508?u=eac8e8bb968ed3391439a98490d3e6e5f6f2826b&v=4 + url: https://github.com/zee229 - login: Patechoc avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 url: https://github.com/Patechoc diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index cc5479c82..01f97b2ce 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo - answers: 1878 - prs: 559 + answers: 1880 + prs: 570 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 598 + count: 600 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -14,7 +14,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: jgould22 - count: 235 + count: 240 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: Mause @@ -45,6 +45,10 @@ experts: count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv +- login: YuriiMotov + count: 75 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: ghandic count: 71 avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 @@ -53,54 +57,50 @@ experts: count: 71 avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik +- login: JavierSanchezCastro + count: 60 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: falkben count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben -- login: JavierSanchezCastro - count: 55 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: n8sty - count: 52 + count: 54 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty +- login: acidjunk + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: yinziyan1206 + count: 49 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 - login: sm-Fifteen count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen -- login: yinziyan1206 - count: 48 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: acidjunk - count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: adriangb +- login: Dustyposa count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa - login: insomnes count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 url: https://github.com/insomnes -- login: Dustyposa +- login: adriangb count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 - url: https://github.com/Dustyposa -- login: YuriiMotov + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb +- login: odiseo0 count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 + url: https://github.com/odiseo0 - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 url: https://github.com/frankie567 -- login: odiseo0 - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 - url: https://github.com/odiseo0 - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 @@ -141,6 +141,10 @@ experts: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 url: https://github.com/SirTelemak +- login: hasansezertasan + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 @@ -153,10 +157,6 @@ experts: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf -- login: hasansezertasan - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 @@ -193,92 +193,120 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 url: https://github.com/caeser1996 -- login: jonatasoli +- login: dstlny count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 - url: https://github.com/jonatasoli + avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 + url: https://github.com/dstlny last_month_experts: - login: YuriiMotov - count: 40 + count: 33 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: jgould22 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: JavierSanchezCastro - count: 11 + count: 5 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: sehraramiz + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: estebanx64 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: ryanisn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: acidjunk + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: pprunty + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty +- login: n8sty + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: angely-dev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: mastizada + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada - login: Kludex - count: 8 + count: 2 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: jgould22 - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: omarcruzpantoja - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: pythonweb2 +- login: Jackiexiao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: PhysicallyActive - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: VatsalJagani + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: hasansezertasan count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 - url: https://github.com/VatsalJagani -- login: khaledadrani + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: sm-Fifteen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 - url: https://github.com/khaledadrani -- login: chrisK824 + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: methane count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: ThirVondukr + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: konstantinos1981 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 + url: https://github.com/konstantinos1981 +- login: fabianfalon count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 + url: https://github.com/fabianfalon three_months_experts: -- login: Kludex - count: 84 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex - login: YuriiMotov - count: 43 + count: 75 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: Kludex + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex - login: jgould22 - count: 30 + count: 28 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: JavierSanchezCastro - count: 24 + count: 22 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: n8sty count: 11 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty +- login: estebanx64 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 - login: hasansezertasan - count: 8 + count: 5 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: dolfinus - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 - url: https://github.com/dolfinus -- login: aanchlia - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia +- login: acidjunk + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: sehraramiz + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz - login: GodMoonGoodman count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 @@ -287,38 +315,82 @@ three_months_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 +- login: PhysicallyActive + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: angely-dev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: ryanisn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: pythonweb2 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 - login: omarcruzpantoja count: 3 avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 url: https://github.com/omarcruzpantoja -- login: fmelihh - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 - url: https://github.com/fmelihh - login: ahmedabdou14 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 url: https://github.com/ahmedabdou14 -- login: chrisK824 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: pythonweb2 +- login: pprunty count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty +- login: leonidktoto count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +- login: JonnyBootsNpants + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 + url: https://github.com/JonnyBootsNpants - login: richin13 count: 2 avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 url: https://github.com/richin13 +- login: mastizada + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada +- login: Jackiexiao + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: sm-Fifteen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: JoshYuJump + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: methane + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: konstantinos1981 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 + url: https://github.com/konstantinos1981 +- login: druidance + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 + url: https://github.com/druidance +- login: fabianfalon + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 + url: https://github.com/fabianfalon +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 - login: VatsalJagani count: 2 avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 @@ -327,14 +399,10 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 url: https://github.com/khaledadrani -- login: acidjunk - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: agn-7 +- login: chrisK824 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 - url: https://github.com/agn-7 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: ThirVondukr count: 2 avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 @@ -343,14 +411,6 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 url: https://github.com/hussein-awala -- login: JoshYuJump - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump -- login: bhumkong - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 - url: https://github.com/bhumkong - login: falkben count: 2 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 @@ -359,87 +419,47 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 url: https://github.com/mielvds -- login: admo1 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 - login: pbasista count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 url: https://github.com/pbasista -- login: bogdan-coman-uv - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 - url: https://github.com/bogdan-coman-uv -- login: leonidktoto - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 - url: https://github.com/leonidktoto - login: DJoepie count: 2 avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4 url: https://github.com/DJoepie -- login: binbjz - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: JonnyBootsNpants - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 - url: https://github.com/JonnyBootsNpants -- login: TarasKuzyo - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/7178184?v=4 - url: https://github.com/TarasKuzyo - login: msehnout count: 2 avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 url: https://github.com/msehnout -- login: rafalkrupinski - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3732079?u=929e95d40d524301cb481da05208a25ed059400d&v=4 - url: https://github.com/rafalkrupinski -- login: morian - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1735308?u=8ef15491399b040bd95e2675bb8c8f2462e977b0&v=4 - url: https://github.com/morian -- login: garg10may - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 - url: https://github.com/garg10may six_months_experts: - login: Kludex - count: 108 + count: 101 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: jgould22 - count: 67 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: YuriiMotov - count: 43 + count: 75 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: jgould22 + count: 53 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: JavierSanchezCastro - count: 35 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: n8sty - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: hasansezertasan - count: 20 + count: 18 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: WilliamStam - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 - url: https://github.com/WilliamStam -- login: pythonweb2 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 +- login: n8sty + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: estebanx64 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 @@ -452,42 +472,74 @@ six_months_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 url: https://github.com/Ventura94 -- login: White-Mask - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 - url: https://github.com/White-Mask -- login: nymous +- login: acidjunk count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: sehraramiz + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz - login: shashstormer count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 url: https://github.com/shashstormer -- login: GodMoonGoodman +- login: yinziyan1206 count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: nymous + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: JoshYuJump count: 4 avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 url: https://github.com/JoshYuJump +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman - login: flo-at count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 +- login: PhysicallyActive + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: angely-dev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: fmelihh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 + url: https://github.com/fmelihh +- login: ryanisn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: theobouwman + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 + url: https://github.com/theobouwman +- login: amacfie + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie +- login: pythonweb2 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 - login: omarcruzpantoja count: 3 avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 url: https://github.com/omarcruzpantoja -- login: fmelihh +- login: bogdan-coman-uv count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 - url: https://github.com/fmelihh + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv - login: ahmedabdou14 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 @@ -496,191 +548,163 @@ six_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: ebottos94 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: binbjz - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: theobouwman - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 - url: https://github.com/theobouwman -- login: sriram-kondakindi - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/32274323?v=4 - url: https://github.com/sriram-kondakindi -- login: yinziyan1206 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: pcorvoh +- login: WilliamStam count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/48502122?u=89fe3e55f3cfd15d34ffac239b32af358cca6481&v=4 - url: https://github.com/pcorvoh -- login: osangu + avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 + url: https://github.com/WilliamStam +- login: pprunty count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 - url: https://github.com/osangu -- login: PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty +- login: leonidktoto count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +- login: JonnyBootsNpants + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 + url: https://github.com/JonnyBootsNpants - login: richin13 count: 2 avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 url: https://github.com/richin13 -- login: amacfie - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie -- login: WSH032 +- login: mastizada count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/126865849?v=4 - url: https://github.com/WSH032 + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada - login: MRigal count: 2 avatarUrl: https://avatars.githubusercontent.com/u/2190327?u=557f399ee90319da7bc4a7d9274e110836b0bd60&v=4 url: https://github.com/MRigal -- login: VatsalJagani - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 - url: https://github.com/VatsalJagani -- login: nameer - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 - url: https://github.com/nameer -- login: kiraware +- login: WSH032 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/117554978?v=4 - url: https://github.com/kiraware -- login: iudeen + avatarUrl: https://avatars.githubusercontent.com/u/126865849?v=4 + url: https://github.com/WSH032 +- login: Jackiexiao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: khaledadrani + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: osangu count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 - url: https://github.com/khaledadrani -- login: acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 + url: https://github.com/osangu +- login: sm-Fifteen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: yavuzakyazici + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: goharShoukat count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/148442912?u=1d2d150172c53daf82020b950c6483a6c6a77b7e&v=4 - url: https://github.com/yavuzakyazici -- login: AntonioBarral + avatarUrl: https://avatars.githubusercontent.com/u/25367760?u=50ced9bb83eca72813fb907b7b201defde635d33&v=4 + url: https://github.com/goharShoukat +- login: elijahsgh count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/22151181?u=64416447a37a420e6dfd16e675cf74f66c9f204d&v=4 - url: https://github.com/AntonioBarral -- login: agn-7 + avatarUrl: https://avatars.githubusercontent.com/u/3681218?u=d46e61b498776e3e21815a46f52ceee08c3f2184&v=4 + url: https://github.com/elijahsgh +- login: jw-00000 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 - url: https://github.com/agn-7 -- login: ThirVondukr + avatarUrl: https://avatars.githubusercontent.com/u/2936?u=93c349e055ad517dc1d83f30bdf6fa9211d7f6a9&v=4 + url: https://github.com/jw-00000 +- login: garg10may count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 + url: https://github.com/garg10may +- login: methane count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala -- login: jcphlux + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: konstantinos1981 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/996689?v=4 - url: https://github.com/jcphlux -- login: bhumkong + avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 + url: https://github.com/konstantinos1981 +- login: druidance count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 - url: https://github.com/bhumkong -- login: falkben + avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 + url: https://github.com/druidance +- login: fabianfalon count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 - url: https://github.com/falkben -- login: mielvds + avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 + url: https://github.com/fabianfalon +- login: admo1 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 - url: https://github.com/mielvds + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 one_year_experts: - login: Kludex - count: 218 + count: 208 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: jgould22 - count: 133 + count: 130 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: JavierSanchezCastro - count: 55 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: YuriiMotov - count: 43 + count: 75 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: JavierSanchezCastro + count: 60 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: n8sty - count: 37 + count: 38 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty +- login: hasansezertasan + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: hasansezertasan - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: nymous - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous - login: ahmedabdou14 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 url: https://github.com/ahmedabdou14 -- login: abhint - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint - login: arjwilliams count: 12 avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 url: https://github.com/arjwilliams -- login: iudeen +- login: nymous + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: abhint count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint +- login: iudeen + count: 10 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 url: https://github.com/iudeen - login: WilliamStam count: 10 avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 url: https://github.com/WilliamStam -- login: yinziyan1206 - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: mateoradman - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/48420316?u=066f36b8e8e263b0d90798113b0f291d3266db7c&v=4 - url: https://github.com/mateoradman -- login: Viicos +- login: estebanx64 count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4 - url: https://github.com/Viicos + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 - login: pythonweb2 - count: 6 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 url: https://github.com/pythonweb2 -- login: ebottos94 +- login: yinziyan1206 count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: acidjunk + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 url: https://github.com/dolfinus +- login: ebottos94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: aanchlia count: 6 avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 @@ -701,14 +725,18 @@ one_year_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 url: https://github.com/mikeedjones -- login: ThirVondukr +- login: sehraramiz count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: dmontagu + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: JoshYuJump count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: nzig + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 + url: https://github.com/nzig - login: alex-pobeditel-2004 count: 5 avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 @@ -717,34 +745,22 @@ one_year_experts: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 url: https://github.com/shashstormer -- login: nzig - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 - url: https://github.com/nzig - login: wu-clan count: 5 avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 url: https://github.com/wu-clan -- login: 8thgencore - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/30128845?u=a747e840f751a1d196d70d0ecf6d07a530d412a1&v=4 - url: https://github.com/8thgencore +- login: amacfie + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie - login: anthonycepeda count: 4 avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 url: https://github.com/anthonycepeda -- login: acidjunk - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk - login: GodMoonGoodman count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 url: https://github.com/GodMoonGoodman -- login: JoshYuJump - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump - login: flo-at count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 @@ -753,57 +769,65 @@ one_year_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4 url: https://github.com/commonism -- login: estebanx64 +- login: dmontagu count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu - login: djimontyp count: 4 avatarUrl: https://avatars.githubusercontent.com/u/53098395?u=583bade70950b277c322d35f1be2b75c7b0f189c&v=4 url: https://github.com/djimontyp - login: sanzoghenzo count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/977953?u=d94445b7b87b7096a92a2d4b652ca6c560f34039&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/977953?v=4 url: https://github.com/sanzoghenzo -- login: adriangb - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb -- login: 9en9i - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/44907258?u=297d0f31ea99c22b718118c1deec82001690cadb&v=4 - url: https://github.com/9en9i -- login: mht2953658596 +- login: PhysicallyActive count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4 - url: https://github.com/mht2953658596 -- login: omarcruzpantoja + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: angely-dev count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev - login: fmelihh count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 url: https://github.com/fmelihh -- login: amacfie +- login: ryanisn count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie -- login: nameer + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: NeilBotelho count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 - url: https://github.com/nameer + avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 + url: https://github.com/NeilBotelho +- login: theobouwman + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 + url: https://github.com/theobouwman +- login: methane + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: omarcruzpantoja + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: bogdan-coman-uv + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv - login: hhartzer count: 3 avatarUrl: https://avatars.githubusercontent.com/u/100533792?v=4 url: https://github.com/hhartzer -- login: binbjz +- login: nameer count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer top_contributors: - login: nilslindemann - count: 127 + count: 130 avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 url: https://github.com/nilslindemann - login: jaystone776 @@ -818,14 +842,14 @@ top_contributors: count: 24 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi +- login: SwftAlpc + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc - login: Kludex count: 22 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: SwftAlpc - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc - login: dmontagu count: 17 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -842,6 +866,10 @@ top_contributors: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 url: https://github.com/mariacamilagl +- login: AlertRED + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED - login: hasansezertasan count: 12 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 @@ -850,10 +878,6 @@ top_contributors: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 url: https://github.com/Smlep -- login: AlertRED - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 - url: https://github.com/AlertRED - login: hard-coders count: 10 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 @@ -864,7 +888,7 @@ top_contributors: url: https://github.com/alejsdev - login: KaniKim count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=d8ff6fca8542d22f94388cd2c4292e76e3898584&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=db09b15514eaf86c30e56401aaeb1e6ec0e31b71&v=4 url: https://github.com/KaniKim - login: xzmeng count: 9 @@ -1032,7 +1056,7 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: alejsdev - count: 37 + count: 38 avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 url: https://github.com/alejsdev - login: JarroVGIT @@ -1103,10 +1127,18 @@ top_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 url: https://github.com/zy7y +- login: junah201 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 - login: peidrao count: 17 avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 url: https://github.com/peidrao +- login: JavierSanchezCastro + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: yanever count: 16 avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 @@ -1119,6 +1151,10 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 url: https://github.com/axel584 +- login: codespearhead + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/72931357?u=0fce6b82219b604d58adb614a761556425579cb5&v=4 + url: https://github.com/codespearhead - login: Alexandrhub count: 16 avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 @@ -1136,17 +1172,13 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 - login: Aruelius - count: 14 + count: 15 avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 url: https://github.com/Aruelius - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk -- login: junah201 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 - url: https://github.com/junah201 - login: wdh99 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 @@ -1155,10 +1187,6 @@ top_reviewers: count: 13 avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 url: https://github.com/r0b2g1t -- login: JavierSanchezCastro - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: RunningIkkyu count: 12 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 @@ -1179,13 +1207,9 @@ top_reviewers: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 url: https://github.com/dpinezich -- login: mariacamilagl - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 - url: https://github.com/mariacamilagl top_translations_reviewers: - login: s111d - count: 143 + count: 146 avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 url: https://github.com/s111d - login: Xewus @@ -1352,6 +1376,10 @@ top_translations_reviewers: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 url: https://github.com/ComicShrimp +- login: junah201 + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 - login: simatheone count: 18 avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 @@ -1376,7 +1404,3 @@ top_translations_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 url: https://github.com/spacesphere -- login: panko - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/1569515?u=a84a5d255621ed82f8e1ca052f5f2eeb75997da2&v=4 - url: https://github.com/panko From f243315696eb20de77db3f2305bf5248290591e3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 3 May 2024 22:21:32 +0000 Subject: [PATCH 446/846] =?UTF-8?q?=F0=9F=93=9D=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 827ac53d3..0cfc10795 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo). + ## 0.111.0 ### Features From 9406e822ec62c88ee366239e57d3819214c3abee Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem <svlandeg@users.noreply.github.com> Date: Sat, 4 May 2024 01:25:16 +0200 Subject: [PATCH 447/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20link=20in=20?= =?UTF-8?q?`fastapi-cli.md`=20(#11524)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/en/docs/fastapi-cli.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md index 0e6295bb4..deff6f875 100644 --- a/docs/en/docs/fastapi-cli.md +++ b/docs/en/docs/fastapi-cli.md @@ -81,4 +81,4 @@ It will listen on the IP address `0.0.0.0`, which means all the available IP add In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. !!! tip - You can learn more about it in the [deployment documentation](../deployment/index.md){.internal-link target=_blank}. + You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}. From 8c572a9ef2269405404b3e1803ce53d5fce52d67 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 3 May 2024 23:25:42 +0000 Subject: [PATCH 448/846] =?UTF-8?q?=F0=9F=93=9D=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 0cfc10795..5f938d293 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg). + ### Internal * 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo). From 6ec46c17d3f88054de4a89908380b0e171b20e87 Mon Sep 17 00:00:00 2001 From: Nick Chen <119087246+nick-cjyx9@users.noreply.github.com> Date: Mon, 6 May 2024 05:32:54 +0800 Subject: [PATCH 449/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`/docs/advanced/security/http-basic-auth.md`=20(?= =?UTF-8?q?#11512)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/http-basic-auth.md | 82 ++++++++++++++++--- 1 file changed, 69 insertions(+), 13 deletions(-) diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index 1f251ca45..ab8961e7c 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -14,15 +14,32 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 ## 简单的 HTTP 基础授权 -* 导入 `HTTPBsic` 与 `HTTPBasicCredentials` -* 使用 `HTTPBsic` 创建**安全概图** +* 导入 `HTTPBasic` 与 `HTTPBasicCredentials` +* 使用 `HTTPBasic` 创建**安全概图** * 在*路径操作*的依赖项中使用 `security` * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `password` -```Python hl_lines="2 6 10" -{!../../../docs_src/security/tutorial006.py!} -``` +=== "Python 3.9+" + + ```Python hl_lines="4 8 12" + {!> ../../../docs_src/security/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="2 7 11" + {!> ../../../docs_src/security/tutorial006_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="2 6 10" + {!> ../../../docs_src/security/tutorial006.py!} + ``` 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -34,13 +51,35 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 使用依赖项检查用户名与密码是否正确。 -为此要使用 Python 标准模块 <a href="https://docs.python.org/3/library/secrets.html" class="external-link" target="_blank">`secrets`</a> 检查用户名与密码: +为此要使用 Python 标准模块 <a href="https://docs.python.org/3/library/secrets.html" class="external-link" target="_blank">`secrets`</a> 检查用户名与密码。 -```Python hl_lines="1 11-13" -{!../../../docs_src/security/tutorial007.py!} -``` +`secrets.compare_digest()` 需要仅包含 ASCII 字符(英语字符)的 `bytes` 或 `str`,这意味着它不适用于像`á`一样的字符,如 `Sebastián`。 + +为了解决这个问题,我们首先将 `username` 和 `password` 转换为使用 UTF-8 编码的 `bytes` 。 + +然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 + +=== "Python 3.9+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an_py39.py!} + ``` -这段代码确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。与以下代码类似: +=== "Python 3.8+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="1 11-21" + {!> ../../../docs_src/security/tutorial007.py!} + ``` +这类似于: ```Python if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): @@ -102,6 +141,23 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -```Python hl_lines="15-19" -{!../../../docs_src/security/tutorial007.py!} -``` +=== "Python 3.9+" + + ```Python hl_lines="26-30" + {!> ../../../docs_src/security/tutorial007_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="26-30" + {!> ../../../docs_src/security/tutorial007_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="23-27" + {!> ../../../docs_src/security/tutorial007.py!} + ``` From e688c57f30fab5d13a46230e31618289a88f5021 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 5 May 2024 21:33:20 +0000 Subject: [PATCH 450/846] =?UTF-8?q?=F0=9F=93=9D=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 5f938d293..1c309ea59 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg). +### Translations + +* 🌐 Update Chinese translation for `/docs/advanced/security/http-basic-auth.md`. PR [#11512](https://github.com/tiangolo/fastapi/pull/11512) by [@nick-cjyx9](https://github.com/nick-cjyx9). + ### Internal * 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo). From 0c82015a8c512191bc04810bde99c7d038cf0f6b Mon Sep 17 00:00:00 2001 From: Lucas-lyh <76511930+Lucas-lyh@users.noreply.github.com> Date: Mon, 6 May 2024 05:34:13 +0800 Subject: [PATCH 451/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/how-to/configure-swagger-ui.md`=20(#1?= =?UTF-8?q?1501)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/how-to/configure-swagger-ui.md | 78 +++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/zh/docs/how-to/configure-swagger-ui.md diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..c0d09f943 --- /dev/null +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# 配置 Swagger UI + +你可以配置一些额外的 <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">Swagger UI 参数</a>. + +如果需要配置它们,可以在创建 `FastAPI()` 应用对象时或调用 `get_swagger_ui_html()` 函数时传递 `swagger_ui_parameters` 参数。 + +`swagger_ui_parameters` 接受一个直接传递给 Swagger UI的字典,包含配置参数键值对。 + +FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因为这是 Swagger UI 需要的。 + +## 不使用语法高亮 + +比如,你可以禁用 Swagger UI 中的语法高亮。 + +当没有改变设置时,语法高亮默认启用: + +<img src="/img/tutorial/extending-openapi/image02.png"> + +但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +...在此之后,Swagger UI 将不会高亮代码: + +<img src="/img/tutorial/extending-openapi/image03.png"> + +## 改变主题 + +同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +``` + +这个配置会改变语法高亮主题: + +<img src="/img/tutorial/extending-openapi/image04.png"> + +## 改变默认 Swagger UI 参数 + +FastAPI 包含了一些默认配置参数,适用于大多数用例。 + +其包括这些默认配置参数: + +```Python +{!../../../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!} +``` + +## 其他 Swagger UI 参数 + +查看其他 Swagger UI 参数,请阅读 <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">docs for Swagger UI parameters</a>。 + +## JavaScript-only 配置 + +Swagger UI 同样允许使用 **JavaScript-only** 配置对象(例如,JavaScript 函数)。 + +FastAPI 包含这些 JavaScript-only 的 `presets` 设置: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +这些是 **JavaScript** 对象,而不是字符串,所以你不能直接从 Python 代码中传递它们。 + +如果你需要像这样使用 JavaScript-only 配置,你可以使用上述方法之一。覆盖所有 Swagger UI *path operation* 并手动编写任何你需要的 JavaScript。 From e04d397e3224d3674cf73332303b956fc3d00b3d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 5 May 2024 21:35:58 +0000 Subject: [PATCH 452/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1c309ea59..d4cea10d0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/how-to/configure-swagger-ui.md`. PR [#11501](https://github.com/tiangolo/fastapi/pull/11501) by [@Lucas-lyh](https://github.com/Lucas-lyh). * 🌐 Update Chinese translation for `/docs/advanced/security/http-basic-auth.md`. PR [#11512](https://github.com/tiangolo/fastapi/pull/11512) by [@nick-cjyx9](https://github.com/nick-cjyx9). ### Internal From aa50dc200f3ef4912cc57e28c31f337a87ce2781 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 7 May 2024 11:31:27 -0700 Subject: [PATCH 453/846] =?UTF-8?q?=F0=9F=91=B7=20Tweak=20CI=20for=20test-?= =?UTF-8?q?redistribute,=20add=20needed=20env=20vars=20for=20slim=20(#1154?= =?UTF-8?q?9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test-redistribute.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml index a249b18a7..0cc5f866e 100644 --- a/.github/workflows/test-redistribute.yml +++ b/.github/workflows/test-redistribute.yml @@ -41,6 +41,8 @@ jobs: run: | cd dist/fastapi*/ pip install -r requirements-tests.txt + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} - name: Run source distribution tests run: | cd dist/fastapi*/ From 8c2e9ddd5035daddc3c9d81a093e1237b147cc0c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 7 May 2024 18:31:47 +0000 Subject: [PATCH 454/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d4cea10d0..507dec5b3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#11549](https://github.com/tiangolo/fastapi/pull/11549) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo). ## 0.111.0 From c4f6439888edb639306538921afd290ea496bb1e Mon Sep 17 00:00:00 2001 From: chaoless <64477804+chaoless@users.noreply.github.com> Date: Wed, 8 May 2024 05:00:22 +0800 Subject: [PATCH 455/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/sql-databases.md`=20(#115?= =?UTF-8?q?39)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/sql-databases.md | 59 ++++++++++++++------------ 1 file changed, 33 insertions(+), 26 deletions(-) diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index be0c76593..bd7c10571 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -1,12 +1,19 @@ # SQL (关系型) 数据库 +!!! info + 这些文档即将被更新。🎉 + + 当前版本假设Pydantic v1和SQLAlchemy版本小于2。 + + 新的文档将包括Pydantic v2以及 <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a>(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 + **FastAPI**不需要你使用SQL(关系型)数据库。 但是您可以使用任何您想要的关系型数据库。 在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。 -您可以很容易地将SQLAlchemy支持任何数据库,像: +您可以很容易地将其调整为任何SQLAlchemy支持的数据库,如: * PostgreSQL * MySQL @@ -74,13 +81,13 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 └── schemas.py ``` -该文件`__init__.py`只是一个空文件,但它告诉 Python 其中`sql_app`的所有模块(Python 文件)都是一个包。 +该文件`__init__.py`只是一个空文件,但它告诉 Python `sql_app` 是一个包。 现在让我们看看每个文件/模块的作用。 ## 安装 SQLAlchemy -先下载`SQLAlchemy`所需要的依赖: +首先你需要安装`SQLAlchemy`: <div class="termy"> @@ -152,17 +159,17 @@ connect_args={"check_same_thread": False} 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - 但是在 FastAPI 中,普遍使用def函数,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 + 但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 ### 创建一个`SessionLocal`类 -每个实例`SessionLocal`都会是一个数据库会话。当然该类本身还不是数据库会话。 +每个`SessionLocal`类的实例都会是一个数据库会话。当然该类本身还不是数据库会话。 但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。 -我们命名它是`SessionLocal`为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 +我们将它命名为`SessionLocal`是为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。 @@ -176,7 +183,7 @@ connect_args={"check_same_thread": False} 现在我们将使用`declarative_base()`返回一个类。 -稍后我们将用这个类继承,来创建每个数据库模型或类(ORM 模型): +稍后我们将继承这个类,来创建每个数据库模型或类(ORM 模型): ```Python hl_lines="13" {!../../../docs_src/sql_databases/sql_app/database.py!} @@ -209,7 +216,7 @@ connect_args={"check_same_thread": False} ### 创建模型属性/列 -现在创建所有模型(类)属性。 +现在创建所有模型(类)的属性。 这些属性中的每一个都代表其相应数据库表中的一列。 @@ -252,13 +259,13 @@ connect_args={"check_same_thread": False} ### 创建初始 Pydantic*模型*/模式 -创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”)以及在创建或读取数据时具有共同的属性。 +创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”),他们拥有创建或读取数据时具有的共同属性。 -`ItemCreate`为 创建一个`UserCreate`继承自它们的所有属性(因此它们将具有相同的属性),以及创建所需的任何其他数据(属性)。 +然后创建一个继承自他们的`ItemCreate`和`UserCreate`,并添加创建时所需的其他数据(或属性)。 因此在创建时也应当有一个`password`属性。 -但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如用户请求时不应该从 API 返回响应中包含它。 +但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。 === "Python 3.10+" @@ -368,7 +375,7 @@ Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`di id = data["id"] ``` -尝试从属性中获取它,如: +它还会尝试从属性中获取它,如: ```Python id = data.id @@ -404,7 +411,7 @@ current_user.items 在这个文件中,我们将编写可重用的函数用来与数据库中的数据进行交互。 -**CRUD**分别为:**增加**、**查询**、**更改**和**删除**,即增删改查。 +**CRUD**分别为:增加(**C**reate)、查询(**R**ead)、更改(**U**pdate)、删除(**D**elete),即增删改查。 ...虽然在这个例子中我们只是新增和查询。 @@ -414,7 +421,7 @@ current_user.items 导入之前的`models`(SQLAlchemy 模型)和`schemas`(Pydantic*模型*/模式)。 -创建一些实用函数来完成: +创建一些工具函数来完成: * 通过 ID 和电子邮件查询单个用户。 * 查询多个用户。 @@ -429,14 +436,14 @@ current_user.items ### 创建数据 -现在创建实用程序函数来创建数据。 +现在创建工具函数来创建数据。 它的步骤是: * 使用您的数据创建一个 SQLAlchemy 模型*实例。* -* 使用`add`来将该实例对象添加到您的数据库。 -* 使用`commit`来对数据库的事务提交(以便保存它们)。 -* 使用`refresh`来刷新您的数据库实例(以便它包含来自数据库的任何新数据,例如生成的 ID)。 +* 使用`add`来将该实例对象添加到数据库会话。 +* 使用`commit`来将更改提交到数据库(以便保存它们)。 +* 使用`refresh`来刷新您的实例对象(以便它包含来自数据库的任何新数据,例如生成的 ID)。 ```Python hl_lines="18-24 31-36" {!../../../docs_src/sql_databases/sql_app/crud.py!} @@ -505,11 +512,11 @@ current_user.items 现在使用我们在`sql_app/database.py`文件中创建的`SessionLocal`来创建依赖项。 -我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在所有请求中使用相同的会话,然后在请求完成后关闭它。 +我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在整个请求中使用相同的会话,然后在请求完成后关闭它。 然后将为下一个请求创建一个新会话。 -为此,我们将创建一个新的依赖项`yield`,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 +为此,我们将创建一个包含`yield`的依赖项,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 @@ -729,13 +736,13 @@ $ uvicorn sql_app.main:app --reload ## 中间件替代数据库会话 -如果你不能使用依赖项`yield`——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以在类似的“中间件”中设置会话方法。 +如果你不能使用带有`yield`的依赖项——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以使用类似的方法在“中间件”中设置会话。 -“中间件”基本功能是一个为每个请求执行的函数在请求之前进行执行相应的代码,以及在请求执行之后执行相应的代码。 +“中间件”基本上是一个对每个请求都执行的函数,其中一些代码在端点函数之前执行,另一些代码在端点函数之后执行。 ### 创建中间件 -我们将添加中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 +我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 === "Python 3.9+" @@ -760,7 +767,7 @@ $ uvicorn sql_app.main:app --reload `request.state`是每个`Request`对象的属性。它用于存储附加到请求本身的任意对象,例如本例中的数据库会话。您可以在[Starlette 的关于`Request`state](https://www.starlette.io/requests/#other-state)的文档中了解更多信息。 -对于这种情况下,它帮助我们确保在所有请求中使用单个数据库会话,然后关闭(在中间件中)。 +对于这种情况下,它帮助我们确保在整个请求中使用单个数据库会话,然后关闭(在中间件中)。 ### 使用`yield`依赖项与使用中间件的区别 @@ -776,9 +783,9 @@ $ uvicorn sql_app.main:app --reload * 即使处理该请求的*路径操作*不需要数据库。 !!! tip - `tyield`当依赖项 足以满足用例时,使用`tyield`依赖项方法会更好。 + 最好使用带有yield的依赖项,如果这足够满足用例需求 !!! info - `yield`的依赖项是最近刚加入**FastAPI**中的。 + 带有`yield`的依赖项是最近刚加入**FastAPI**中的。 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 From 17c1ae886ba03964440e309d61e6ed92d5dd4382 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 7 May 2024 21:00:47 +0000 Subject: [PATCH 456/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 507dec5b3..205b3c805 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#11539](https://github.com/tiangolo/fastapi/pull/11539) by [@chaoless](https://github.com/chaoless). * 🌐 Add Chinese translation for `docs/zh/docs/how-to/configure-swagger-ui.md`. PR [#11501](https://github.com/tiangolo/fastapi/pull/11501) by [@Lucas-lyh](https://github.com/Lucas-lyh). * 🌐 Update Chinese translation for `/docs/advanced/security/http-basic-auth.md`. PR [#11512](https://github.com/tiangolo/fastapi/pull/11512) by [@nick-cjyx9](https://github.com/nick-cjyx9). From 8187c54c730dc711288dc2027b07feffa5b1c6bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Wed, 8 May 2024 22:10:46 +0300 Subject: [PATCH 457/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/tutorial/request-forms.md`=20(#11553)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/tutorial/request-forms.md | 92 ++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 docs/tr/docs/tutorial/request-forms.md diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md new file mode 100644 index 000000000..2728b6164 --- /dev/null +++ b/docs/tr/docs/tutorial/request-forms.md @@ -0,0 +1,92 @@ +# Form Verisi + +İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz. + +!!! info "Bilgi" + Formları kullanmak için öncelikle <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> paketini indirmeniz gerekmektedir. + + Örneğin `pip install python-multipart`. + +## `Form` Sınıfını Projenize Dahil Edin + +`Form` sınıfını `fastapi`'den projenize dahil edin: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +## `Form` Parametrelerini Tanımlayın + +Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak <abbr title="Kullanıcı Adı: Username">"username"</abbr> ve <abbr title="Şifre: Password">"password"</abbr> gönderilmesi gerekir. + +Bu <abbr title="Spesifikasyon: Specification">spesifikasyon</abbr> form alanlarını adlandırırken isimlerinin birebir `username` ve `password` olmasını ve JSON verisi yerine form verisi olarak gönderilmesini gerektirir. + +`Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz. + +!!! info "Bilgi" + `Form` doğrudan `Body` sınıfını miras alan bir sınıftır. + +!!! tip "İpucu" + Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. + +## "Form Alanları" Hakkında + +HTML formlarının (`<form></form>`) verileri sunucuya gönderirken JSON'dan farklı özel bir kodlama kullanır. + +**FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır. + +!!! note "Teknik Detaylar" + Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. + + Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz. + + Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a> sayfasını ziyaret edebilirsiniz. + +!!! warning "Uyarı" + *Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. + + Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır. + +## Özet + +Form verisi girdi parametreleri tanımlamak için `Form` sınıfını kullanın. From 9642ff26375e44d35f6dbdc473680bacbc82e737 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 8 May 2024 19:11:08 +0000 Subject: [PATCH 458/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 205b3c805..97845718d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan). + ### Docs * ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg). From 722107fe60c3da3bfe56428079ee2132082ebee9 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein <tamird@gmail.com> Date: Thu, 9 May 2024 20:30:25 -0400 Subject: [PATCH 459/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20GitHub=20action?= =?UTF-8?q?s=20to=20download=20and=20upload=20artifacts=20to=20v4,=20for?= =?UTF-8?q?=20docs=20and=20coverage=20(#11550)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- .github/workflows/build-docs.yml | 4 ++-- .github/workflows/deploy-docs.yml | 16 +++++++--------- .github/workflows/test.yml | 11 ++++++----- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 4ff5e26cb..262c7fa5c 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -108,9 +108,9 @@ jobs: path: docs/${{ matrix.lang }}/.cache - name: Build Docs run: python ./scripts/docs.py build-lang ${{ matrix.lang }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: - name: docs-site + name: docs-site-${{ matrix.lang }} path: ./site/** # https://github.com/marketplace/actions/alls-green#why diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index b8dbb7dc5..dd54608d9 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -19,18 +19,16 @@ jobs: run: | rm -rf ./site mkdir ./site - - name: Download Artifact Docs - id: download - uses: dawidd6/action-download-artifact@v3.1.4 + - uses: actions/download-artifact@v4 with: - if_no_artifact_found: ignore - github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} - workflow: build-docs.yml - run_id: ${{ github.event.workflow_run.id }} - name: docs-site path: ./site/ + pattern: docs-site-* + merge-multiple: true + github-token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} + run-id: ${{ github.event.workflow_run.id }} - name: Deploy to Cloudflare Pages - if: steps.download.outputs.found_artifact == 'true' + # hashFiles returns an empty string if there are no files + if: hashFiles('./site/*') id: deploy uses: cloudflare/pages-action@v1 with: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fe1e419d6..a33b6a68a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -87,9 +87,9 @@ jobs: COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }} CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }} - name: Store coverage files - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: coverage + name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }} path: coverage coverage-combine: @@ -108,17 +108,18 @@ jobs: # cache: "pip" # cache-dependency-path: pyproject.toml - name: Get coverage files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: - name: coverage + pattern: coverage-* path: coverage + merge-multiple: true - run: pip install coverage[toml] - run: ls -la coverage - run: coverage combine coverage - run: coverage report - run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}" - name: Store coverage HTML - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: coverage-html path: htmlcov From e82e6479f28594142e6ddbae21111f5abf3b8e65 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 10 May 2024 00:30:46 +0000 Subject: [PATCH 460/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 97845718d..61b1023a8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Internal +* 👷 Update GitHub actions to download and upload artifacts to v4, for docs and coverage. PR [#11550](https://github.com/tiangolo/fastapi/pull/11550) by [@tamird](https://github.com/tamird). * 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#11549](https://github.com/tiangolo/fastapi/pull/11549) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo). From 1f0eecba8153317eba70bc73328943ecb331aff6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 9 May 2024 17:48:58 -0700 Subject: [PATCH 461/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20Smokeshow=20dow?= =?UTF-8?q?nload=20artifact=20GitHub=20Action=20(#11562)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/smokeshow.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index c4043cc6a..2620da839 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -24,11 +24,11 @@ jobs: - run: pip install smokeshow - - uses: dawidd6/action-download-artifact@v3.1.4 + - uses: actions/download-artifact@v4 with: - github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} - workflow: test.yml - commit: ${{ github.event.workflow_run.head_sha }} + name: coverage-html + github-token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} + run-id: ${{ github.event.workflow_run.id }} - run: smokeshow upload coverage-html env: From 2c6fb2ecd1de2668dd7dbb16c5931b290256f60b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 10 May 2024 00:49:28 +0000 Subject: [PATCH 462/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 61b1023a8..6b28a8f74 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Internal +* 👷 Update Smokeshow download artifact GitHub Action. PR [#11562](https://github.com/tiangolo/fastapi/pull/11562) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub actions to download and upload artifacts to v4, for docs and coverage. PR [#11550](https://github.com/tiangolo/fastapi/pull/11550) by [@tamird](https://github.com/tamird). * 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#11549](https://github.com/tiangolo/fastapi/pull/11549) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo). From efeee95db7775dad468d6b4e77e8f1031062a167 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 9 May 2024 18:06:31 -0700 Subject: [PATCH 463/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20Smokeshow,=20fi?= =?UTF-8?q?x=20sync=20download=20artifact=20and=20smokeshow=20configs=20(#?= =?UTF-8?q?11563)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/smokeshow.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 2620da839..ffc9c5f8a 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -27,10 +27,11 @@ jobs: - uses: actions/download-artifact@v4 with: name: coverage-html + path: htmlcov github-token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} run-id: ${{ github.event.workflow_run.id }} - - run: smokeshow upload coverage-html + - run: smokeshow upload htmlcov env: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 100 From af60d6d8ead9c924b7a65d349cb9d29e9c117d13 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 10 May 2024 01:06:55 +0000 Subject: [PATCH 464/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6b28a8f74..1e55c4af9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Internal +* 👷 Update Smokeshow, fix sync download artifact and smokeshow configs. PR [#11563](https://github.com/tiangolo/fastapi/pull/11563) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Smokeshow download artifact GitHub Action. PR [#11562](https://github.com/tiangolo/fastapi/pull/11562) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub actions to download and upload artifacts to v4, for docs and coverage. PR [#11550](https://github.com/tiangolo/fastapi/pull/11550) by [@tamird](https://github.com/tamird). * 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#11549](https://github.com/tiangolo/fastapi/pull/11549) by [@tiangolo](https://github.com/tiangolo). From dfa75c15877592d8662c5e74ff53b36f4f8a61c5 Mon Sep 17 00:00:00 2001 From: s111d <angry.kustomer@gmail.com> Date: Mon, 13 May 2024 03:58:32 +0300 Subject: [PATCH 465/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/about/index.md`=20(#10961)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/about/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/ru/docs/about/index.md diff --git a/docs/ru/docs/about/index.md b/docs/ru/docs/about/index.md new file mode 100644 index 000000000..1015b667a --- /dev/null +++ b/docs/ru/docs/about/index.md @@ -0,0 +1,3 @@ +# О проекте + +FastAPI: внутреннее устройство, повлиявшие технологии и всё такое прочее. 🤓 From 038e1142d7e482d6a2ec6c1ae05f0d53f5861ff9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 13 May 2024 00:58:56 +0000 Subject: [PATCH 466/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1e55c4af9..db10e78c1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/about/index.md`. PR [#10961](https://github.com/tiangolo/fastapi/pull/10961) by [@s111d](https://github.com/s111d). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#11539](https://github.com/tiangolo/fastapi/pull/11539) by [@chaoless](https://github.com/chaoless). * 🌐 Add Chinese translation for `docs/zh/docs/how-to/configure-swagger-ui.md`. PR [#11501](https://github.com/tiangolo/fastapi/pull/11501) by [@Lucas-lyh](https://github.com/Lucas-lyh). * 🌐 Update Chinese translation for `/docs/advanced/security/http-basic-auth.md`. PR [#11512](https://github.com/tiangolo/fastapi/pull/11512) by [@nick-cjyx9](https://github.com/nick-cjyx9). From 61ab73ea0fa3c19207a5a65770771d6b98f67d95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Tue, 14 May 2024 22:35:04 +0300 Subject: [PATCH 467/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/tutorial/cookie-params.md`=20(#11561)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/tutorial/cookie-params.md | 97 ++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 docs/tr/docs/tutorial/cookie-params.md diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..4a66f26eb --- /dev/null +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -0,0 +1,97 @@ +# Çerez (Cookie) Parametreleri + +`Query` (Sorgu) ve `Path` (Yol) parametrelerini tanımladığınız şekilde çerez parametreleri tanımlayabilirsiniz. + +## Import `Cookie` + +Öncelikle, `Cookie`'yi projenize dahil edin: + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "İpucu" + Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +## `Cookie` Parametrelerini Tanımlayın + +Çerez parametrelerini `Path` veya `Query` tanımlaması yapar gibi tanımlayın. + +İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/cookie_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "İpucu" + Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 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!} + ``` + +!!! 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. + + Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur. + +!!! info "Bilgi" + Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. + +## Özet + +Çerez tanımlamalarını `Cookie` sınıfını kullanarak `Query` ve `Path` tanımlar gibi tanımlayın. From a32902606e8d7abab83a636293d62aff52fd2429 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 14 May 2024 19:35:25 +0000 Subject: [PATCH 468/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index db10e78c1..b92a58edf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/cookie-params.md`. PR [#11561](https://github.com/tiangolo/fastapi/pull/11561) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Russian translation for `docs/ru/docs/about/index.md`. PR [#10961](https://github.com/tiangolo/fastapi/pull/10961) by [@s111d](https://github.com/s111d). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#11539](https://github.com/tiangolo/fastapi/pull/11539) by [@chaoless](https://github.com/chaoless). * 🌐 Add Chinese translation for `docs/zh/docs/how-to/configure-swagger-ui.md`. PR [#11501](https://github.com/tiangolo/fastapi/pull/11501) by [@Lucas-lyh](https://github.com/Lucas-lyh). From 817cc1d7548a508f80a346eb18889e29177ec03c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petar=20Mari=C4=87?= <petar.maric@gmail.com> Date: Sat, 18 May 2024 02:48:03 +0200 Subject: [PATCH 469/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`fastapi/applications.py`=20(#11593)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/applications.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index 4446cacfb..4f5e6f1d9 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -902,7 +902,7 @@ class FastAPI(Starlette): A state object for the application. This is the same object for the entire application, it doesn't change from request to request. - You normally woudln't use this in FastAPI, for most of the cases you + You normally wouldn't use this in FastAPI, for most of the cases you would instead use FastAPI dependencies. This is simply inherited from Starlette. From 1dae11ce50873fb6f56a6b5d25b0d79bdfbc638a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 18 May 2024 00:48:23 +0000 Subject: [PATCH 470/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b92a58edf..90c44bfaa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Docs +* ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric). * ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg). ### Translations From 23bc02c45a59509caba858a7afca076d4edbb784 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Sat, 18 May 2024 03:49:03 +0300 Subject: [PATCH 471/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/advanced/wsgi.md`=20(#11575)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/advanced/wsgi.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 docs/tr/docs/advanced/wsgi.md diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md new file mode 100644 index 000000000..54a6f20e2 --- /dev/null +++ b/docs/tr/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# WSGI - Flask, Django ve Daha Fazlasını FastAPI ile Kullanma + +WSGI uygulamalarını [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} bölümlerinde gördüğünüz gibi bağlayabilirsiniz. + +Bunun için `WSGIMiddleware` ile Flask, Django vb. WSGI uygulamanızı sarmalayabilir ve FastAPI'ya bağlayabilirsiniz. + +## `WSGIMiddleware` Kullanımı + +`WSGIMiddleware`'ı projenize dahil edin. + +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!} +``` + +## Kontrol Edelim + +Artık `/v1/` yolunun altındaki her istek Flask uygulaması tarafından işlenecektir. + +Geri kalanı ise **FastAPI** tarafından işlenecektir. + +Eğer uygulamanızı çalıştırıp <a href="http://localhost:8000/v1/" class="external-link" target="_blank">http://localhost:8000/v1/</a> adresine giderseniz, Flask'tan gelen yanıtı göreceksiniz: + +```txt +Hello, World from Flask! +``` + +Eğer <a href="http://localhost:8000/v2/" class="external-link" target="_blank">http://localhost:8000/v2/</a> adresine giderseniz, FastAPI'dan gelen yanıtı göreceksiniz: + +```JSON +{ + "message": "Hello World" +} +``` From d4ce9d5a4a6913ec37ccadaa961d20f7394e78c0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 18 May 2024 00:49:30 +0000 Subject: [PATCH 472/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 90c44bfaa..a2d3afe4b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/wsgi.md`. PR [#11575](https://github.com/tiangolo/fastapi/pull/11575) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/cookie-params.md`. PR [#11561](https://github.com/tiangolo/fastapi/pull/11561) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Russian translation for `docs/ru/docs/about/index.md`. PR [#10961](https://github.com/tiangolo/fastapi/pull/10961) by [@s111d](https://github.com/s111d). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#11539](https://github.com/tiangolo/fastapi/pull/11539) by [@chaoless](https://github.com/chaoless). From 22b033ebd71b97a112e39db6b2819df9a75f7e79 Mon Sep 17 00:00:00 2001 From: Igor Sulim <30448496+isulim@users.noreply.github.com> Date: Sat, 18 May 2024 02:50:03 +0200 Subject: [PATCH 473/846] =?UTF-8?q?=F0=9F=8C=90=20Polish=20translation=20f?= =?UTF-8?q?or=20`docs/pl/docs/fastapi-people.md`=20(#10196)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pl/docs/fastapi-people.md | 178 +++++++++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 docs/pl/docs/fastapi-people.md diff --git a/docs/pl/docs/fastapi-people.md b/docs/pl/docs/fastapi-people.md new file mode 100644 index 000000000..b244ab489 --- /dev/null +++ b/docs/pl/docs/fastapi-people.md @@ -0,0 +1,178 @@ +# Ludzie FastAPI + +FastAPI posiada wspaniałą społeczność, która jest otwarta dla ludzi z każdego środowiska. + +## Twórca - Opienik + +Cześć! 👋 + +To ja: + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.maintainers %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Liczba odpowiedzi: {{ user.answers }}</div><div class="count">Pull Requesty: {{ user.prs }}</div></div> +{% endfor %} + +</div> +{% endif %} + +Jestem twórcą i opiekunem **FastAPI**. Możesz przeczytać więcej na ten temat w [Pomoc FastAPI - Uzyskaj pomoc - Skontaktuj się z autorem](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. + +...Ale tutaj chcę pokazać Ci społeczność. + +--- + +**FastAPI** otrzymuje wiele wsparcia od społeczności. Chciałbym podkreślić ich wkład. + +To są ludzie, którzy: + +* [Pomagają innym z pytaniami na GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. +* [Tworzą Pull Requesty](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. +* Oceniają Pull Requesty, [to szczególnie ważne dla tłumaczeń](contributing.md#translations){.internal-link target=_blank}. + +Proszę o brawa dla nich. 👏 🙇 + +## Najaktywniejsi użytkownicy w zeszłym miesiącu + +Oto niektórzy użytkownicy, którzy [pomagali innym w największej liczbie pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} podczas ostatniego miesiąca. ☕ + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.last_month_active %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Udzielonych odpowiedzi: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Eksperci + +Oto **eksperci FastAPI**. 🤓 + +To użytkownicy, którzy [pomogli innym z największa liczbą pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} od *samego początku*. + +Poprzez pomoc wielu innym, udowodnili, że są ekspertami. ✨ + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.experts %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Udzielonych odpowiedzi: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Najlepsi Kontrybutorzy + +Oto **Najlepsi Kontrybutorzy**. 👷 + +Ci użytkownicy [stworzyli najwięcej Pull Requestów](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, które zostały *wcalone*. + +Współtworzyli kod źródłowy, dokumentację, tłumaczenia itp. 📦 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_contributors %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requesty: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">Kontrybutorzy FastAPI na GitHub</a>. 👷 + +## Najlepsi Oceniajacy + +Ci uzytkownicy są **Najlepszymi oceniającymi**. 🕵️ + +### Oceny Tłumaczeń + +Ja mówię tylko kilkoma językami (i to niezbyt dobrze 😅). Zatem oceniający są tymi, którzy mają [**moc zatwierdzania tłumaczeń**](contributing.md#translations){.internal-link target=_blank} dokumentacji. Bez nich nie byłoby dokumentacji w kilku innych językach. + +--- + +**Najlepsi Oceniający** 🕵️ przejrzeli więcej Pull Requestów, niż inni, zapewniając jakość kodu, dokumentacji, a zwłaszcza **tłumaczeń**. + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_reviewers %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Liczba ocen: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## Sponsorzy + +Oto **Sponsorzy**. 😎 + +Wspierają moją pracę nad **FastAPI** (i innymi), głównie poprzez <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>. + +{% if sponsors %} + +{% if sponsors.gold %} + +### Złoci Sponsorzy + +{% for sponsor in sponsors.gold -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% if sponsors.silver %} + +### Srebrni Sponsorzy + +{% for sponsor in sponsors.silver -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% if sponsors.bronze %} + +### Brązowi Sponsorzy + +{% for sponsor in sponsors.bronze -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% endif %} + +### Indywidualni Sponsorzy + +{% if github_sponsors %} +{% for group in github_sponsors.sponsors %} + +<div class="user-list user-list-center"> + +{% for user in group %} +{% if user.login not in sponsors_badge.logins %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> + +{% endif %} +{% endfor %} + +</div> + +{% endfor %} +{% endif %} + +## Techniczne szczegóły danych + +Głównym celem tej strony jest podkreślenie wysiłku społeczności w pomaganiu innym. + +Szczególnie włączając wysiłki, które są zwykle mniej widoczne, a w wielu przypadkach bardziej żmudne, tak jak pomaganie innym z pytaniami i ocenianie Pull Requestów z tłumaczeniami. + +Dane są obliczane każdego miesiąca, możesz przeczytać <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kod źródłowy tutaj</a>. + +Tutaj również podkreślam wkład od sponsorów. + +Zastrzegam sobie prawo do aktualizacji algorytmu, sekcji, progów itp. (na wszelki wypadek 🤷). From ad85917f618bb8073c43fc06378d9140f2373e87 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 18 May 2024 00:52:09 +0000 Subject: [PATCH 474/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a2d3afe4b..58d15c494 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Translations +* 🌐 Polish translation for `docs/pl/docs/fastapi-people.md`. PR [#10196](https://github.com/tiangolo/fastapi/pull/10196) by [@isulim](https://github.com/isulim). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/wsgi.md`. PR [#11575](https://github.com/tiangolo/fastapi/pull/11575) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/cookie-params.md`. PR [#11561](https://github.com/tiangolo/fastapi/pull/11561) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Russian translation for `docs/ru/docs/about/index.md`. PR [#10961](https://github.com/tiangolo/fastapi/pull/10961) by [@s111d](https://github.com/s111d). From 76d0d81e70a70e663aba67d1631cb1fe030e1a45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Sun, 19 May 2024 02:43:13 +0300 Subject: [PATCH 475/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo:=20conv?= =?UTF-8?q?ert=20every=20're-use'=20to=20'reuse'.=20(#11598)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/additional-responses.md | 2 +- .../docs/advanced/path-operation-advanced-configuration.md | 2 +- docs/en/docs/advanced/security/oauth2-scopes.md | 2 +- docs/en/docs/advanced/settings.md | 2 +- docs/en/docs/advanced/templates.md | 2 +- docs/en/docs/deployment/docker.md | 4 ++-- docs/en/docs/how-to/custom-docs-ui-assets.md | 4 ++-- docs/en/docs/how-to/nosql-databases-couchbase.md | 2 +- docs/en/docs/release-notes.md | 2 +- docs/en/docs/tutorial/background-tasks.md | 2 +- .../dependencies-in-path-operation-decorators.md | 2 +- docs/en/docs/tutorial/dependencies/sub-dependencies.md | 2 +- docs/en/docs/tutorial/handling-errors.md | 6 +++--- 13 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 41b39c18e..88d27018c 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -224,7 +224,7 @@ Here, `new_dict` will contain all the key-value pairs from `old_dict` plus the n } ``` -You can use that technique to re-use some predefined responses in your *path operations* and combine them with additional custom ones. +You can use that technique to reuse some predefined responses in your *path operations* and combine them with additional custom ones. For example: diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index c5544a78b..35f7d1b8d 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -187,6 +187,6 @@ And then in our code, we parse that YAML content directly, and then we are again In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. !!! tip - Here we re-use the same Pydantic model. + Here we reuse the same Pydantic model. But the same way, we could have validated it in some other way. diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index b93d2991c..728104865 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -361,7 +361,7 @@ It will have a property `scopes` with a list containing all the scopes required The `security_scopes` object (of class `SecurityScopes`) also provides a `scope_str` attribute with a single string, containing those scopes separated by spaces (we are going to use it). -We create an `HTTPException` that we can re-use (`raise`) later at several points. +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). diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index f9b525a58..56af4f441 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -369,7 +369,7 @@ Here we define the config `env_file` inside of your Pydantic `Settings` class, a ### Creating the `Settings` only once with `lru_cache` -Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then re-use the same settings object, instead of reading it for each request. +Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request. But every time we do: diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 6055b3017..4a577215a 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -23,7 +23,7 @@ $ pip install jinja2 ## Using `Jinja2Templates` * Import `Jinja2Templates`. -* Create a `templates` object that you can re-use later. +* Create a `templates` object that you can reuse later. * 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. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 5181f77e0..5cd24eb46 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -70,7 +70,7 @@ And there are many other images for different things like databases, for example By using a pre-made container image it's very easy to **combine** and use different tools. For example, to try out a new database. In most cases, you can use the **official images**, and just configure them with environment variables. -That way, in many cases you can learn about containers and Docker and re-use that knowledge with many different tools and components. +That way, in many cases you can learn about containers and Docker and reuse that knowledge with many different tools and components. So, you would run **multiple containers** with different things, like a database, a Python application, a web server with a React frontend application, and connect them together via their internal network. @@ -249,7 +249,7 @@ COPY ./requirements.txt /code/requirements.txt Docker and other tools **build** these container images **incrementally**, adding **one layer on top of the other**, starting from the top of the `Dockerfile` and adding any files created by each of the instructions of the `Dockerfile`. -Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **re-use the same layer** created the last time, instead of copying the file again and creating a new layer from scratch. +Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **reuse the same layer** created the last time, instead of copying the file again and creating a new layer from scratch. Just avoiding the copy of files doesn't necessarily improve things too much, but because it used the cache for that step, it can **use the cache for the next step**. For example, it could use the cache for the instruction that installs dependencies with: 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 9726be2c7..adc1c1ef4 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -26,7 +26,7 @@ To disable them, set their URLs to `None` when creating your `FastAPI` app: Now you can create the *path operations* for the custom docs. -You can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: +You can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: * `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. * `title`: the title of your API. @@ -163,7 +163,7 @@ To disable them, set their URLs to `None` when creating your `FastAPI` app: And the same way as with a custom CDN, now you can create the *path operations* for the custom docs. -Again, you can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: +Again, you can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: * `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. * `title`: the title of your API. diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md index 563318984..18e3f4b7e 100644 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -108,7 +108,7 @@ Now create a function that will: * Get the document with that ID. * Put the contents of the document in a `UserInDB` model. -By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily re-use it in multiple parts and also add <abbr title="Automated test, written in code, that checks if another piece of code is working correctly.">unit tests</abbr> for it: +By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily reuse it in multiple parts and also add <abbr title="Automated test, written in code, that checks if another piece of code is working correctly.">unit tests</abbr> for it: ```Python hl_lines="36-42" {!../../../docs_src/nosql_databases/tutorial001.py!} diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 58d15c494..b8201e9f8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -3872,7 +3872,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * New documentation about exceptions handlers: * [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers). * [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers). - * [Re-use **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#re-use-fastapis-exception-handlers). + * [Reuse **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers). * PR [#273](https://github.com/tiangolo/fastapi/pull/273). * Fix support for *paths* in *path parameters* without needing explicit `Path(...)`. diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index bc8e2af6a..bcfadc8b8 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -55,7 +55,7 @@ Inside of your *path operation function*, pass your task function to the *backgr Using `BackgroundTasks` also works with the dependency injection system, you can declare a parameter of type `BackgroundTasks` at multiple levels: in a *path operation function*, in a dependency (dependable), in a sub-dependency, etc. -**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards: +**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards: === "Python 3.10+" 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 eaab51d1b..082417f11 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 @@ -107,7 +107,7 @@ These dependencies can `raise` exceptions, the same as normal dependencies: And they can return values or not, the values won't be used. -So, you can re-use 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: +So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed: === "Python 3.9+" diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index 1cb469a80..e5def9b7d 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -157,7 +157,7 @@ query_extractor --> query_or_cookie_extractor --> read_query If one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request. -And it will save the returned value in a <abbr title="A utility/system to store computed/generated values, to re-use them instead of computing them again.">"cache"</abbr> and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request. +And it will save the returned value in a <abbr title="A utility/system to store computed/generated values, to reuse them instead of computing them again.">"cache"</abbr> and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request. In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`: diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 98ac55d1f..6133898e4 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -248,12 +248,12 @@ In this example, to be able to have both `HTTPException`s in the same code, Star from starlette.exceptions import HTTPException as StarletteHTTPException ``` -### Re-use **FastAPI**'s exception handlers +### Reuse **FastAPI**'s exception handlers -If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and re-use the default exception handlers from `fastapi.exception_handlers`: +If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" {!../../../docs_src/handling_errors/tutorial006.py!} ``` -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 re-use the default exception handlers. +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. From ca321db5dbcd53de77cca9d4ccb26dcb88f337b3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 18 May 2024 23:43:36 +0000 Subject: [PATCH 476/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b8201e9f8..fdad0494d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Docs +* ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan). * ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric). * ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg). From 651dd00a9e3bc75fd872737cb0fbc3a0f44b9e38 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 May 2024 19:24:48 -0500 Subject: [PATCH 477/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20(#11603)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/en/docs/async.md | 2 +- docs/en/docs/tutorial/first-steps.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index a0c00933a..793d691e3 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -222,7 +222,7 @@ All of the cashiers doing all the work with one client after the other 👨 And you have to wait 🕙 in the line for a long time or you lose your turn. -You probably wouldn't want to take your crush 😍 with you to do errands at the bank 🏦. +You probably wouldn't want to take your crush 😍 with you to run errands at the bank 🏦. ### Burger Conclusion diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index 35b2feb41..d18b25d97 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -325,6 +325,6 @@ There are many other objects and models that will be automatically converted to * Import `FastAPI`. * Create an `app` instance. -* Write a **path operation decorator** (like `@app.get("/")`). -* Write a **path operation function** (like `def root(): ...` above). -* Run the development server (like `uvicorn main:app --reload`). +* Write a **path operation decorator** using decorators like `@app.get("/")`. +* Define a **path operation function**; for example, `def root(): ...`. +* Run the development server using the command `fastapi dev`. From 710b320fd0e441fcf1f25b584d7ec50b36d04df0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 20 May 2024 00:25:11 +0000 Subject: [PATCH 478/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index fdad0494d..048020c8c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Docs +* 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan). * ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric). * ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg). From 5fa8e38681b1f3e835991159d27bf0a3a76308f7 Mon Sep 17 00:00:00 2001 From: Esteban Maya <emayacadavid9@gmail.com> Date: Mon, 20 May 2024 12:37:28 -0500 Subject: [PATCH 479/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20JWT=20auth=20do?= =?UTF-8?q?cumentation=20to=20use=20PyJWT=20instead=20of=20pyhon-jose=20(#?= =?UTF-8?q?11589)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Motov Yurii <109919500+YuriiMotov@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- .../docs/advanced/security/oauth2-scopes.md | 96 +++++++++---------- docs/en/docs/tutorial/security/oauth2-jwt.md | 58 ++++++----- docs_src/security/tutorial004.py | 5 +- docs_src/security/tutorial004_an.py | 5 +- docs_src/security/tutorial004_an_py310.py | 5 +- docs_src/security/tutorial004_an_py39.py | 5 +- docs_src/security/tutorial004_py310.py | 5 +- docs_src/security/tutorial005.py | 5 +- docs_src/security/tutorial005_an.py | 5 +- docs_src/security/tutorial005_an_py310.py | 5 +- docs_src/security/tutorial005_an_py39.py | 5 +- docs_src/security/tutorial005_py310.py | 5 +- docs_src/security/tutorial005_py39.py | 5 +- requirements-tests.txt | 2 +- 14 files changed, 109 insertions(+), 102 deletions(-) diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 728104865..9a9c0dff9 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -58,19 +58,19 @@ First, let's quickly see the parts that change from the examples in the main **T === "Python 3.10+" - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" + ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" + ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" + ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" + ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -88,7 +88,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" + ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -97,7 +97,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" + ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -111,19 +111,19 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri === "Python 3.10+" - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="63-66" + ```Python hl_lines="64-67" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -132,7 +132,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="61-64" + ```Python hl_lines="62-65" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -142,7 +142,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -151,7 +151,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -178,19 +178,19 @@ And we return the scopes as part of the JWT token. === "Python 3.10+" - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="156" + ```Python hl_lines="157" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="154" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -208,7 +208,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -217,7 +217,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -244,19 +244,19 @@ In this case, it requires the scope `me` (it could require more than one scope). === "Python 3.10+" - ```Python hl_lines="4 139 170" + ```Python hl_lines="5 140 171" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="4 139 170" + ```Python hl_lines="5 140 171" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="4 140 171" + ```Python hl_lines="5 141 172" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 138 167" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -274,7 +274,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 168" + ```Python hl_lines="5 140 169" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -283,7 +283,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 168" + ```Python hl_lines="5 140 169" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -310,19 +310,19 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t === "Python 3.10+" - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="8 106" + ```Python hl_lines="9 107" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -331,7 +331,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 104" + ```Python hl_lines="8 105" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -340,7 +340,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -349,7 +349,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -367,19 +367,19 @@ In this exception, we include the scopes required (if any) as a string separated === "Python 3.10+" - ```Python hl_lines="105 107-115" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="105 107-115" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="106 108-116" + ```Python hl_lines="107 109-117" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -388,7 +388,7 @@ In this exception, we include the scopes required (if any) as a string separated !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="104 106-114" + ```Python hl_lines="105 107-115" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -397,7 +397,7 @@ In this exception, we include the scopes required (if any) as a string separated !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="105 107-115" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -406,7 +406,7 @@ In this exception, we include the scopes required (if any) as a string separated !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="105 107-115" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -426,19 +426,19 @@ We also verify that we have a user with that username, and if not, we raise that === "Python 3.10+" - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="47 117-128" + ```Python hl_lines="48 118-129" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -447,7 +447,7 @@ We also verify that we have a user with that username, and if not, we raise that !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="45 115-126" + ```Python hl_lines="46 116-127" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -456,7 +456,7 @@ We also verify that we have a user with that username, and if not, we raise that !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -465,7 +465,7 @@ We also verify that we have a user with that username, and if not, we raise that !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -477,19 +477,19 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these === "Python 3.10+" - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="129-135" + ```Python hl_lines="130-136" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -498,7 +498,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="127-133" + ```Python hl_lines="128-134" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -507,7 +507,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -516,7 +516,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index b02d00c3f..b011db67a 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -26,28 +26,24 @@ After a week, the token will be expired and the user will not be authorized and If you want to play with JWT tokens and see how they work, check <a href="https://jwt.io/" class="external-link" target="_blank">https://jwt.io</a>. -## Install `python-jose` +## Install `PyJWT` -We need to install `python-jose` to generate and verify the JWT tokens in Python: +We need to install `PyJWT` to generate and verify the JWT tokens in Python: <div class="termy"> ```console -$ pip install "python-jose[cryptography]" +$ pip install pyjwt ---> 100% ``` </div> -<a href="https://github.com/mpdavis/python-jose" class="external-link" target="_blank">Python-jose</a> requires a cryptographic backend as an extra. +!!! info + If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`. -Here we are using the recommended one: <a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>. - -!!! tip - This tutorial previously used <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>. - - But it was updated to use Python-jose instead as it provides all the features from PyJWT plus some extras that you might need later when building integrations with other tools. + You can read more about it in the <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a>. ## Password hashing @@ -111,19 +107,19 @@ And another one to authenticate and return a user. === "Python 3.10+" - ```Python hl_lines="7 48 55-56 59-60 69-75" + ```Python hl_lines="8 49 56-57 60-61 70-76" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="7 48 55-56 59-60 69-75" + ```Python hl_lines="8 49 56-57 60-61 70-76" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="7 49 56-57 60-61 70-76" + ```Python hl_lines="8 50 57-58 61-62 71-77" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -132,7 +128,7 @@ And another one to authenticate and return a user. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6 47 54-55 58-59 68-74" + ```Python hl_lines="7 48 55-56 59-60 69-75" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -141,7 +137,7 @@ And another one to authenticate and return a user. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 48 55-56 59-60 69-75" + ```Python hl_lines="8 49 56-57 60-61 70-76" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -178,19 +174,19 @@ Create a utility function to generate a new access token. === "Python 3.10+" - ```Python hl_lines="6 12-14 28-30 78-86" + ```Python hl_lines="4 7 13-15 29-31 79-87" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="6 12-14 28-30 78-86" + ```Python hl_lines="4 7 13-15 29-31 79-87" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="6 13-15 29-31 79-87" + ```Python hl_lines="4 7 14-16 30-32 80-88" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -199,7 +195,7 @@ Create a utility function to generate a new access token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="5 11-13 27-29 77-85" + ```Python hl_lines="3 6 12-14 28-30 78-86" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -208,7 +204,7 @@ Create a utility function to generate a new access token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6 12-14 28-30 78-86" + ```Python hl_lines="4 7 13-15 29-31 79-87" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -222,19 +218,19 @@ If the token is invalid, return an HTTP error right away. === "Python 3.10+" - ```Python hl_lines="89-106" + ```Python hl_lines="90-107" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="89-106" + ```Python hl_lines="90-107" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="90-107" + ```Python hl_lines="91-108" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -243,7 +239,7 @@ If the token is invalid, return an HTTP error right away. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="88-105" + ```Python hl_lines="89-106" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -252,7 +248,7 @@ If the token is invalid, return an HTTP error right away. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="89-106" + ```Python hl_lines="90-107" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -264,19 +260,19 @@ Create a real JWT access token and return it. === "Python 3.10+" - ```Python hl_lines="117-132" + ```Python hl_lines="118-133" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="117-132" + ```Python hl_lines="118-133" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="118-133" + ```Python hl_lines="119-134" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -285,7 +281,7 @@ Create a real JWT access token and return it. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="114-129" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -294,7 +290,7 @@ Create a real JWT access token and return it. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="115-130" + ```Python hl_lines="116-131" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -384,7 +380,7 @@ Many packages that simplify it a lot have to make many compromises with the data It gives you all the flexibility to choose the ones that fit your project the best. -And you can use directly many well maintained and widely used packages like `passlib` and `python-jose`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages. +And you can use directly many well maintained and widely used packages like `passlib` and `PyJWT`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages. But it provides you the tools to simplify the process as much as possible without compromising flexibility, robustness, or security. diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index d0fbaa572..91d161b8a 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -98,7 +99,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index eebd36d64..df50754af 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel from typing_extensions import Annotated @@ -99,7 +100,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 4e50ada7c..eff54ef01 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -98,7 +99,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index eb49aaa67..0455b500c 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Annotated, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -98,7 +99,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 5a905783d..78bee22a3 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -1,8 +1,9 @@ from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -97,7 +98,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index d4a6975da..ccad07969 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index 982daed2f..5b67cb145 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError from typing_extensions import Annotated @@ -121,7 +122,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 79aafbff1..297193e35 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index 3bdab5507..1acf47bdc 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Annotated, List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index 9f75aa0be..b244ef08e 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -1,12 +1,13 @@ from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -119,7 +120,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index bac248932..8f0e93376 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/requirements-tests.txt b/requirements-tests.txt index 88a553330..bfe70f2f5 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -11,7 +11,7 @@ sqlalchemy >=1.3.18,<1.4.43 databases[sqlite] >=0.3.2,<0.7.0 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 -python-jose[cryptography] >=3.3.0,<4.0.0 +PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 From bfe698c667aeaaefb52a59657f8901502ff6ba54 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 20 May 2024 17:37:51 +0000 Subject: [PATCH 480/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 048020c8c..2232887ac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Docs +* 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64). * 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan). * ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric). From a4c4eb2964f163a87d3ba887b1a6714ffbe36941 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Tue, 21 May 2024 02:57:08 +0300 Subject: [PATCH 481/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/tutorial/static-files.md`=20(#11599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/tutorial/static-files.md | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/tr/docs/tutorial/static-files.md diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md new file mode 100644 index 000000000..00c833686 --- /dev/null +++ b/docs/tr/docs/tutorial/static-files.md @@ -0,0 +1,39 @@ +# Statik Dosyalar + +`StaticFiles`'ı kullanarak statik dosyaları bir yol altında sunabilirsiniz. + +## `StaticFiles` Kullanımı + +* `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!} +``` + +!!! note "Teknik Detaylar" + Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. + + **FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir. + +### Bağlama (Mounting) Nedir? + +"Bağlamak", belirli bir yola tamamen "bağımsız" bir uygulama eklemek anlamına gelir ve ardından tüm alt yollara gelen istekler bu uygulama tarafından işlenir. + +Bu, bir `APIRouter` kullanmaktan farklıdır çünkü bağlanmış bir uygulama tamamen bağımsızdır. Ana uygulamanızın OpenAPI ve dokümanlar, bağlanmış uygulamadan hiçbir şey içermez, vb. + +[Advanced User Guide](../advanced/index.md){.internal-link target=_blank} bölümünde daha fazla bilgi edinebilirsiniz. + +## Detaylar + +`"/static"` ifadesi, bu "alt uygulamanın" "bağlanacağı" alt yolu belirtir. Bu nedenle, `"/static"` ile başlayan her yol, bu uygulama tarafından işlenir. + +`directory="static"` ifadesi, statik dosyalarınızı içeren dizinin adını belirtir. + +`name="static"` ifadesi, alt uygulamanın **FastAPI** tarafından kullanılacak ismini belirtir. + +Bu parametrelerin hepsi "`static`"den farklı olabilir, bunları kendi uygulamanızın ihtiyaçlarına göre belirleyebilirsiniz. + +## Daha Fazla Bilgi + +Daha fazla detay ve seçenek için <a href="https://www.starlette.io/staticfiles/" class="external-link" target="_blank">Starlette'in Statik Dosyalar hakkındaki dokümantasyonunu</a> incelleyin. From 3e6a59183bd4feb094d8e37439e0b886c360e068 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 20 May 2024 23:57:31 +0000 Subject: [PATCH 482/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2232887ac..ba6cc8b5a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/static-files.md`. PR [#11599](https://github.com/tiangolo/fastapi/pull/11599) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Polish translation for `docs/pl/docs/fastapi-people.md`. PR [#10196](https://github.com/tiangolo/fastapi/pull/10196) by [@isulim](https://github.com/isulim). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/wsgi.md`. PR [#11575](https://github.com/tiangolo/fastapi/pull/11575) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/cookie-params.md`. PR [#11561](https://github.com/tiangolo/fastapi/pull/11561) by [@hasansezertasan](https://github.com/hasansezertasan). From f1ab5300a7fa32f37ca9ff70627078ebb6f04b2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Fri, 24 May 2024 01:46:42 +0300 Subject: [PATCH 483/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/deployment/index.md`=20(#11605)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/deployment/index.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/tr/docs/deployment/index.md diff --git a/docs/tr/docs/deployment/index.md b/docs/tr/docs/deployment/index.md new file mode 100644 index 000000000..e03bb4ee0 --- /dev/null +++ b/docs/tr/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Deployment (Yayınlama) + +**FastAPI** uygulamasını deploy etmek oldukça kolaydır. + +## Deployment Ne Anlama Gelir? + +Bir uygulamayı **deploy** etmek (yayınlamak), uygulamayı **kullanıcılara erişilebilir hale getirmek** için gerekli adımları gerçekleştirmek anlamına gelir. + +Bir **Web API** için bu süreç normalde uygulamayı **uzak bir makineye** yerleştirmeyi, iyi performans, kararlılık vb. özellikler sağlayan bir **sunucu programı** ile **kullanıcılarınızın** uygulamaya etkili ve kesintisiz bir şekilde **erişebilmesini** kapsar. + +Bu, kodu sürekli olarak değiştirdiğiniz, hata alıp hata giderdiğiniz, geliştirme sunucusunu durdurup yeniden başlattığınız vb. **geliştirme** aşamalarının tam tersidir. + +## Deployment Stratejileri + +Kullanım durumunuza ve kullandığınız araçlara bağlı olarak bir kaç farklı yol izleyebilirsiniz. + +Bir dizi araç kombinasyonunu kullanarak kendiniz **bir sunucu yayınlayabilirsiniz**, yayınlama sürecinin bir kısmını sizin için gerçekleştiren bir **bulut hizmeti** veya diğer olası seçenekleri kullanabilirsiniz. + +**FastAPI** uygulamasını yayınlarken aklınızda bulundurmanız gereken ana kavramlardan bazılarını size göstereceğim (ancak bunların çoğu diğer web uygulamaları için de geçerlidir). + +Sonraki bölümlerde akılda tutulması gereken diğer ayrıntıları ve yayınlama tekniklerinden bazılarını göreceksiniz. ✨ From dda233772293de978bade64ef2ed5fce3bd65e1c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 23 May 2024 22:47:02 +0000 Subject: [PATCH 484/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ba6cc8b5a..f0f15e299 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/deployment/index.md`. PR [#11605](https://github.com/tiangolo/fastapi/pull/11605) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/static-files.md`. PR [#11599](https://github.com/tiangolo/fastapi/pull/11599) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Polish translation for `docs/pl/docs/fastapi-people.md`. PR [#10196](https://github.com/tiangolo/fastapi/pull/10196) by [@isulim](https://github.com/isulim). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/wsgi.md`. PR [#11575](https://github.com/tiangolo/fastapi/pull/11575) by [@hasansezertasan](https://github.com/hasansezertasan). From a69f38340f5ca80e4d97fa0af7ea5f70b1d771a7 Mon Sep 17 00:00:00 2001 From: Nir Schulman <narsssx@gmail.com> Date: Fri, 24 May 2024 01:59:02 +0300 Subject: [PATCH 485/846] =?UTF-8?q?=F0=9F=93=9D=20Restored=20Swagger-UI=20?= =?UTF-8?q?links=20to=20use=20the=20latest=20version=20possible.=20(#11459?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/custom-docs-ui-assets.md | 4 ++-- docs/en/docs/how-to/custom-docs-ui-assets.md | 4 ++-- docs_src/custom_docs_ui/tutorial001.py | 4 ++-- fastapi/openapi/docs.py | 4 ++-- tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py | 6 ++---- 5 files changed, 10 insertions(+), 12 deletions(-) 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 991eaf269..a9271b3f3 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -96,8 +96,8 @@ Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und **Swagger UI** verwendet folgende Dateien: -* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a> -* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a> +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a> +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a> Und **ReDoc** verwendet diese Datei: 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 adc1c1ef4..053e5eacd 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -96,8 +96,8 @@ You can probably right-click each link and select an option similar to `Save lin **Swagger UI** uses the files: -* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a> -* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a> +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a> +* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a> And **ReDoc** uses the file: diff --git a/docs_src/custom_docs_ui/tutorial001.py b/docs_src/custom_docs_ui/tutorial001.py index 4384433e3..f7ceb0c2f 100644 --- a/docs_src/custom_docs_ui/tutorial001.py +++ b/docs_src/custom_docs_ui/tutorial001.py @@ -14,8 +14,8 @@ async def custom_swagger_ui_html(): openapi_url=app.openapi_url, title=app.title + " - Swagger UI", oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, - swagger_js_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", - swagger_css_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css", + swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js", + swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css", ) diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index 67815e0fb..c2ec358d2 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -53,7 +53,7 @@ def get_swagger_ui_html( It is normally set to a CDN URL. """ ), - ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url: Annotated[ str, Doc( @@ -63,7 +63,7 @@ def get_swagger_ui_html( It is normally set to a CDN URL. """ ), - ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css", + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css", swagger_favicon_url: Annotated[ str, Doc( diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py index 34a18b12c..aff070d74 100644 --- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py @@ -20,10 +20,8 @@ def client(): def test_swagger_ui_html(client: TestClient): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" in response.text - ) - assert "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css" in response.text + assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" in response.text + assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" in response.text def test_swagger_ui_oauth2_redirect_html(client: TestClient): From 86b410e62354398684e6357cf120082b3c45e0bc Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 23 May 2024 22:59:22 +0000 Subject: [PATCH 486/846] =?UTF-8?q?=F0=9F=93=9D=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 f0f15e299..2ac70c0da 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,10 @@ hide: * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan). +### Upgrades + +* 📝 Restored Swagger-UI links to use the latest version possible.. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster). + ### Docs * 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64). From f7a11bc0b4ee380d46d1ee974707d37c633521ce Mon Sep 17 00:00:00 2001 From: chaoless <64477804+chaoless@users.noreply.github.com> Date: Tue, 28 May 2024 00:19:21 +0800 Subject: [PATCH 487/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/advanced/templates.md`=20(#11620)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/templates.md | 71 +++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 22 deletions(-) diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index d735f1697..612b69176 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -20,24 +20,12 @@ $ pip install jinja2 </div> -如需使用静态文件,还要安装 `aiofiles`: - -<div class="termy"> - -```console -$ pip install aiofiles - ----> 100% -``` - -</div> - ## 使用 `Jinja2Templates` * 导入 `Jinja2Templates` * 创建可复用的 `templates` 对象 * 在返回模板的*路径操作*中声明 `Request` 参数 -* 使用 `templates` 渲染并返回 `TemplateResponse`, 以键值对方式在 Jinja2 的 **context** 中传递 `request` +* 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, ```Python hl_lines="4 11 15-16" {!../../../docs_src/templates/tutorial001.py!} @@ -45,7 +33,8 @@ $ pip install aiofiles !!! note "笔记" - 注意,必须为 Jinja2 以键值对方式在上下文中传递 `request`。因此,还要在*路径操作*中声明。 + 在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 + 并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 !!! tip "提示" @@ -65,30 +54,68 @@ $ pip install aiofiles {!../../../docs_src/templates/templates/item.html!} ``` -它会显示从 **context** 字典中提取的 `id`: +### 模板上下文 + +在包含如下语句的html中: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...这将显示你从"context"字典传递的 `id`: ```Python -{"request": request, "id": id} +{"id": id} +``` + +例如。当ID为 `42`时, 会渲染成: + +```html +Item ID: 42 +``` + +### 模板 `url_for` 参数 + +你还可以在模板内使用 `url_for()`,其参数与*路径操作函数*的参数相同. + +所以,该部分: + +{% raw %} + +```jinja +<a href="{{ url_for('read_item', id=id) }}"> +``` + +{% endraw %} + +...将生成一个与处理*路径操作函数* `read_item(id=id)`的URL相同的链接 + +例如。当ID为 `42`时, 会渲染成: + +```html +<a href="/items/42"> ``` ## 模板与静态文件 -在模板内部使用 `url_for()`,例如,与挂载的 `StaticFiles` 一起使用。 +你还可以在模板内部将 `url_for()`用于静态文件,例如你挂载的 `name="static"`的 `StaticFiles`。 ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} ``` -本例中,使用 `url_for()` 为模板添加 CSS 文件 `static/styles.css` 链接: +本例中,它将链接到 `static/styles.css`中的CSS文件: ```CSS hl_lines="4" {!../../../docs_src/templates/static/styles.css!} ``` -因为使用了 `StaticFiles`, **FastAPI** 应用自动提供位于 URL `/static/styles.css` - -的 CSS 文件。 +因为使用了 `StaticFiles`, **FastAPI** 应用会自动提供位于 URL `/static/styles.css`的 CSS 文件。 ## 更多说明 -包括测试模板等更多详情,请参阅 <a href="https://www.starlette.io/templates/" class="external-link" target="_blank">Starlette 官档 - 模板</a>。 +包括测试模板等更多详情,请参阅 <a href="https://www.starlette.io/templates/" class="external-link" target="_blank">Starlette 官方文档 - 模板</a>。 From 36269edf6aeed87edd3e1ac1aacf2a15d83a365e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 27 May 2024 16:19:42 +0000 Subject: [PATCH 488/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2ac70c0da..55b6caf2b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#11620](https://github.com/tiangolo/fastapi/pull/11620) by [@chaoless](https://github.com/chaoless). * 🌐 Add Turkish translation for `docs/tr/docs/deployment/index.md`. PR [#11605](https://github.com/tiangolo/fastapi/pull/11605) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/static-files.md`. PR [#11599](https://github.com/tiangolo/fastapi/pull/11599) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Polish translation for `docs/pl/docs/fastapi-people.md`. PR [#10196](https://github.com/tiangolo/fastapi/pull/10196) by [@isulim](https://github.com/isulim). From 54d0be2388c2decc4a2cfb94d73869488859d4cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Mon, 27 May 2024 19:20:52 +0300 Subject: [PATCH 489/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/how-to/general.md`=20(#11607)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/how-to/general.md | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/tr/docs/how-to/general.md diff --git a/docs/tr/docs/how-to/general.md b/docs/tr/docs/how-to/general.md new file mode 100644 index 000000000..cbfa7beb2 --- /dev/null +++ b/docs/tr/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Genel - Nasıl Yapılır - Tarifler + +Bu sayfada genel ve sıkça sorulan sorular için dokümantasyonun diğer sayfalarına yönlendirmeler bulunmaktadır. + +## Veri Filtreleme - Güvenlik + +Döndürmeniz gereken veriden fazlasını döndürmediğinizden emin olmak için, [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Etiketleri - OpenAPI + +*Yol operasyonlarınıza* etiketler ekleyerek dokümantasyon arayüzünde gruplar halinde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Özeti ve Açıklaması - OpenAPI + +*Yol operasyonlarınıza* özet ve açıklama ekleyip dokümantasyon arayüzünde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank} sayfasını okuyun. + +## Yanıt Açıklaması Dokümantasyonu - OpenAPI + +Dokümantasyon arayüzünde yer alan yanıt açıklamasını tanımlamak için, [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} sayfasını okuyun. + +## *Yol Operasyonunu* Kullanımdan Kaldırma - OpenAPI + +Bir *yol işlemi*ni kullanımdan kaldırmak ve bunu dokümantasyon arayüzünde göstermek için, [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} sayfasını okuyun. + +## Herhangi Bir Veriyi JSON Uyumlu Hale Getirme + +Herhangi bir veriyi JSON uyumlu hale getirmek için, [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Meta Verileri - Dokümantasyon + +OpenAPI şemanıza lisans, sürüm, iletişim vb. meta veriler eklemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Bağlantı Özelleştirme + +OpenAPI bağlantısını özelleştirmek (veya kaldırmak) için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Dokümantasyon Bağlantıları + +Dokümantasyonu arayüzünde kullanılan bağlantıları güncellemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank} sayfasını okuyun. From 59b17ce8044c14819f930bfb1e855edcc7c8973e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Mon, 27 May 2024 19:21:03 +0300 Subject: [PATCH 490/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/advanced/testing-websockets.md`=20(#1?= =?UTF-8?q?1608)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/advanced/testing-websockets.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 docs/tr/docs/advanced/testing-websockets.md diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..cdd5b7ae5 --- /dev/null +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -0,0 +1,12 @@ +# WebSockets'i Test Etmek + +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!} +``` + +!!! note "Not" + Daha fazla detay için Starlette'in <a href="https://www.starlette.io/staticfiles/" class="external-link" target="_blank">Websockets'i Test Etmek</a> dokümantasyonunu inceleyin. From a8a3971a995a953e1c3da8944bea4608847542dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Mon, 27 May 2024 19:21:37 +0300 Subject: [PATCH 491/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/advanced/security/index.md`=20(#11609?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/advanced/security/index.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 docs/tr/docs/advanced/security/index.md diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md new file mode 100644 index 000000000..89a431687 --- /dev/null +++ b/docs/tr/docs/advanced/security/index.md @@ -0,0 +1,16 @@ +# Gelişmiş Güvenlik + +## Ek Özellikler + +[Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır. + +!!! tip "İpucu" + Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + + Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +## Önce Öğreticiyi Okuyun + +Sonraki bölümler [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasını okuduğunuzu varsayarak hazırlanmıştır. + +Bu bölümler aynı kavramlara dayanır, ancak bazı ek işlevsellikler sağlar. From aadc3e7dc13be9a180374ee0dcbbc349901d4295 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 27 May 2024 16:21:46 +0000 Subject: [PATCH 492/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 55b6caf2b..6ea9ed7c7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/how-to/general.md`. PR [#11607](https://github.com/tiangolo/fastapi/pull/11607) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#11620](https://github.com/tiangolo/fastapi/pull/11620) by [@chaoless](https://github.com/chaoless). * 🌐 Add Turkish translation for `docs/tr/docs/deployment/index.md`. PR [#11605](https://github.com/tiangolo/fastapi/pull/11605) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/static-files.md`. PR [#11599](https://github.com/tiangolo/fastapi/pull/11599) by [@hasansezertasan](https://github.com/hasansezertasan). From d523f7f340275a4d6e446c04eb93397c916fb518 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 27 May 2024 16:22:14 +0000 Subject: [PATCH 493/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6ea9ed7c7..ae24ca8de 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/testing-websockets.md`. PR [#11608](https://github.com/tiangolo/fastapi/pull/11608) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/how-to/general.md`. PR [#11607](https://github.com/tiangolo/fastapi/pull/11607) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#11620](https://github.com/tiangolo/fastapi/pull/11620) by [@chaoless](https://github.com/chaoless). * 🌐 Add Turkish translation for `docs/tr/docs/deployment/index.md`. PR [#11605](https://github.com/tiangolo/fastapi/pull/11605) by [@hasansezertasan](https://github.com/hasansezertasan). From 8b4ce06065d796974c09aa8a93b67dac97437bb7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 27 May 2024 16:23:10 +0000 Subject: [PATCH 494/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ae24ca8de..906728b09 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/security/index.md`. PR [#11609](https://github.com/tiangolo/fastapi/pull/11609) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/testing-websockets.md`. PR [#11608](https://github.com/tiangolo/fastapi/pull/11608) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/how-to/general.md`. PR [#11607](https://github.com/tiangolo/fastapi/pull/11607) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#11620](https://github.com/tiangolo/fastapi/pull/11620) by [@chaoless](https://github.com/chaoless). From a751cdd17f1f1d3d3e87a3d41b98a60776236d06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Tue, 28 May 2024 17:05:55 +0300 Subject: [PATCH 495/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/deployment/cloud.md`=20(#11610)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/deployment/cloud.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 docs/tr/docs/deployment/cloud.md diff --git a/docs/tr/docs/deployment/cloud.md b/docs/tr/docs/deployment/cloud.md new file mode 100644 index 000000000..5639567d4 --- /dev/null +++ b/docs/tr/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# FastAPI Uygulamasını Bulut Sağlayıcılar Üzerinde Yayınlama + +FastAPI uygulamasını yayınlamak için hemen hemen **herhangi bir bulut sağlayıcıyı** kullanabilirsiniz. + +Büyük bulut sağlayıcıların çoğu FastAPI uygulamasını yayınlamak için kılavuzlara sahiptir. + +## Bulut Sağlayıcılar - Sponsorlar + +Bazı bulut sağlayıcılar ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar. + +Ayrıca, size **iyi servisler** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a bağlılıklarını gösterir. + +Bu hizmetleri denemek ve kılavuzlarını incelemek isteyebilirsiniz: + +* <a href="https://docs.platform.sh/languages/python.html?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" class="external-link" target="_blank">Platform.sh</a> +* <a href="https://docs.porter.run/language-specific-guides/fastapi" class="external-link" target="_blank">Porter</a> +* <a href="https://docs.withcoherence.com/docs/configuration/frameworks?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024#fast-api-example" class="external-link" target="_blank">Coherence</a> From ba1ac2b1f6689b1588b8bec33eb67d426d03abf1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 28 May 2024 14:06:23 +0000 Subject: [PATCH 496/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 906728b09..968dddf7d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/deployment/cloud.md`. PR [#11610](https://github.com/tiangolo/fastapi/pull/11610) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/security/index.md`. PR [#11609](https://github.com/tiangolo/fastapi/pull/11609) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/testing-websockets.md`. PR [#11608](https://github.com/tiangolo/fastapi/pull/11608) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/how-to/general.md`. PR [#11607](https://github.com/tiangolo/fastapi/pull/11607) by [@hasansezertasan](https://github.com/hasansezertasan). From 803b9fca980611452c58a2b3421717e7f5078634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 30 May 2024 08:28:20 -0500 Subject: [PATCH 497/846] =?UTF-8?q?=F0=9F=94=A7=20Add=20sponsor=20Kong=20(?= =?UTF-8?q?#11662)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/docs/img/sponsors/kong-banner.png | Bin 0 -> 21116 bytes docs/en/docs/img/sponsors/kong.png | Bin 0 -> 30723 bytes docs/en/overrides/main.html | 6 ++++++ 5 files changed, 10 insertions(+) create mode 100644 docs/en/docs/img/sponsors/kong-banner.png create mode 100644 docs/en/docs/img/sponsors/kong.png diff --git a/README.md b/README.md index 1db8a8949..55f3e300f 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ The key features are: <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> <a href="https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> +<a href="https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> <a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 85ac30d6d..6285e8fd4 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -26,6 +26,9 @@ gold: - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral title: Simplify Full Stack Development with FastAPI & MongoDB img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png + - url: https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api + title: Kong Konnect - API management platform + img: https://fastapi.tiangolo.com/img/sponsors/kong.png silver: - url: https://training.talkpython.fm/fastapi-courses title: FastAPI video courses on demand from people you trust diff --git a/docs/en/docs/img/sponsors/kong-banner.png b/docs/en/docs/img/sponsors/kong-banner.png new file mode 100644 index 0000000000000000000000000000000000000000..9f5b55a0fe8bc997f99faef278e21dfbc7a32b9d GIT binary patch literal 21116 zcmV)AK*Ya^P)<h;3K|Lk000e1NJLTq00EEy001Zm1^@s6&{3>l00009a7bBm000XU z000XU0RWnu7ytkO0drDELIAGL9O(c600d`2O+f$vv5yP<VFdsHQV~f+K~#7FoqY$q zWJQ(tIk(??6PRIU5JA!mte^<UfS^c5KqLu*0)l|RD&mTWi(%J*h--FDps=DSh!{|E zRI+3d$w83hkOwBuym{Sy>#LKhPTjt5@b_JK)7|%0ICZM({7<N=i-=f5yg~@^D~9+L z<9EJA|HOOX?%8j9&iCn_eg?=_dS>aV4lASitWgL5cF#cb26>E97$wZ*Sf0=*JJDlh zS=mOjem3ie1`XI!2Rhn=@ygTOQWiKmz%fTj2-xIVOIx5(7B&;R{=k-U(r?FuqW>Fx ziY@fC-7o4>UivmdgTHMT<`1nW69bs4M9h6x3ID3fjSpY9rx!gVD3cTtA5|3<$mxSt z#P@T0zR4wrSVI-_rt)KzIy#jA`wpI#fPi@rYuls{wA-OzLrQ9C(MFiH!!bU!Q?sMw zK%*LM;01j`#RM%AjUP&|rSmjsTjg0*RmB{Sc>^ksjTn^sMzE13&58fL>1`XrwtH<2 z&ph!cTy^dR@Z=-^fO4w1fzg}?E%O3l#c8k@Uf3u%|DG^B369$Pf8bYt`Z_FH`ik{t z5Vm(z8pVG@-8%o7w`oq;t@wY{iCOyX^WWx;pH)1vf=?(PS%kFCfADixXvlpSWHeNu z(~60cp(>3GIx=LaYoA)>ItF<Pqyg9z0Ew`MFlo~1g?ma@_FpMLd|Bg^32ngB7(7WR zw+OjrI()TyJk7o=Pe&Vox^@?Q@NI7snoVI|5Zn;Z4FNwuQ=?tM)6l}}6#|OS*W^!I z-9D|Sw~Yt?0_|Fce62-vbD=8NRs1*sU=!Z%qfvnwEF6(0$g;4moUG)!A}Cm8=n&Eb zVxv4r0y)xHael~R2~-w~psi)5CIH}M0x$}AxkI$2GF>4gvCH(QdufnV3Ew<Fir)#t zNXSEm7wfs8^2KojLgrf`V1r<4Wz`!@CAz%`iJ+d^93T|5WpIHoW3}nH%Yi#VXE?we zf4UB?zxXP!3tNC<TwoaYx&Djgb1B<@&(AjBU>EqeHD|*GH-0~jS5#43M;xf)XsJU_ znr58wbfobpPZ>O@CqnJ{>g9rfl0pgCd@_9*^1R~#)0ji1o0zg79j;_aeO$OEPQ3;8 zTdLAA8RuZ#*XNBsz)UrD{eT6MQx=-{V1En>o+7^&S`AQW6-JJ!tsny>U_j${@hr4h zJ56ESMu)Ep1_5XQAPc6Hg4*-6pr?7Qpp7_AI%x7A$G4h_^o=yldxbC$gH~x95QY{& z#AexTv_p9%WC*2J>jk-K?@3gX;1=1O1anbj*(b@G$b!-dZxhC$Ibp0E`Ifb75`H#i zMXVOIC264iG;2pEx5)$aeLt>1%QYAfIj}*<1!TbSLR8BQ31%}0=JHT25U13-4mMs1 zk;Obg1u+a6L-KeSv{bO*YrZN5-7R*S4I94Y-(ddBFT(FnKO0_r_IcM8|3AQypEW_E zpuq#6-aBH?|A9aK<!pHNrN75})ZewF>5PbQj=y;T`7vU1#O4n@ulo@{hBSR$(C95x zV!1kibYumWE<nO6OVpVE7}Br|hU?OnN+)zB9cDOHL(V6KDJ7)B)d)$&O2a;c2IoSX zQ1e8$fq>UQ+rYs!3L6b=%^O}t!+#Yah2zj&+;ZPvO)#f&J?OwVR|{R^S}_el-`0*5 z0dCV0X-m68D`PyMSrPEH(BGDKyfIPmLZ3GklQcF|jW+=w+(Z}QnS`uq-#jrWVMwX6 zB!Dc8tHc0I-pVY70Sdw5HGE|_KeJpQ28NW$wN_QpzGfazw*v?h#|h9<wZW&CD+=P2 zH)N)P=N*&)QqXIHKIA?U&C_|UvXz#22H@O&20Ol98~_3pPR2*)wX?B7yn{v_qf5&S zYp(Y?+<xz^Ve-@}S|opj>n^^s;70)-uL2y2M^4cwfx~~#19Pp{z5#aG@^JXwHD8D2 z-DM1L#MMr;CVCMNxGzFq@>S0D8Dw5mNG_|IZ9rCb`rV+`1D4&01M|ND7V@>Oom?s9 zD(F3Bw3<wq*lRYFbuWPZinrAhR|O_qRRy|N>)^=bm;ymoHGQv}f;uz1yh6M7-zHdA z2rzBec$Nf|!m6qDhDI?(S{M}4D|$AdeS7+iKfc|ryf!ds(p7*EjvwzBNY|*d6=0g} z45d}q<UzB}fp#?8*kYL!^|p<Hf8`kru!%nt!@ZE85nb^tl`DgXPK68}T%}}5+I|)w znJ@fT*Va}Q0Lh(%jx2OBw<_^QlS39~SrY}wZYh<bURgs;t6F;oK;ds?v;YjmZP1X^ z(-1`U<XBMAMi7DK*qQ1=RKLE_l8vTP=!$&GmK-FWR>q~wGdCNukX8<<8jua0+$U&4 z51^R;tE@HyUcbqDVT<iH!9SgUA>4oG-SFZw&szh*Uv0nvIA~c2sSV&5M@H?j^+#du z{5f#vBbP;MYA7bEVJHGfABO;kBLC_x+m<{mWXSOpmJS?(UauFsWGEUTH4Ey%uAv~j z&X*Z?eBVJv6Hw%L?X4KO&yY+mL(5I$z<^xmjo26!C_ady0y6edh$avrRET%A4uXgX zT&jG?P*ZnmA%t7BW&gcZur<>H44PH{sutTU7fP)eGd~BwZa`2q1Zb)UO0J`;16BkK z;nl4aXyIc4wvLt}?RfXwz#2+$!dL4v{XQ@$8*Oa1w@LE=IJNPqrJht*!-5(Z7fr#g zvk-LBtEfSzm*@L|;|%dfE!kA=Vgd#Gt{QqNb-ZvE;a6#F#Dt!HwMOSavk)7U;^3vF zCe?N&MNr*XG`BH}0~4h=#^D8<iP>P1Fp0xT1wpD0oYn?TfSV^H$87v~OW&Pf4^V;! zK<1mQ9T2`%ST)8lvb^Ga6$EQcvQoSjD_??{N|gxp?0U(_ES6Hdz5d4Q!P|D;5|%7{ z5w5-H3b^;qzZuJ1mtyf9o50byk15Z<{N~$JC$9?oY<~h=a`X3K@v?b<(ejAV4;b!r zLQeweQO0sCL|vf5D$?aCZ9f7G4o`r7w`R`}3xDMqxwL{Ck=`BY5;=Jmf|G4xS7;6@ zgT@t)VRd84z^%~e2|5z$fGQYJdcb&HGk^fAFAQ|G&|%>}Hxe@9!K(_rHp`?C?&DY^ zA+)=p2Eb=L0UcUa_gH$Pr%j+WX&;Zy22IAJW*GqOK;s2rXac3r>)KSbyUF`;%4qU` zTu=-Dg5|d&5ML2L8+>mY6RmA%((Lo+bda<{(@YT(K!|(5q5w8q1WtlUDPe9}dE(iv z^(SkDb6UJ3Jy$X3etU79YqxUcX-Ej=0IG7rI+KHqw&y@}E&;Iw)sR7xwPXQ}021(b zWtwWJKu|T5j$B5fDg(0?lgFyXEtK{&RxrDs%uVOqTMf`F!P*0kb01Wx_snt<5Yx6B zfDlJ*om)&dBU&YU9<&QgpRp2L`G@o2)@%L@OBOE%*SItyK*tppU}61&?z836e4D<0 zSD3ZNY`E-}A1IxDm^_SO`54FGFhti>2pRX8(wJ_j6J1yxrk^d{y5C1==&>Q;L>@}% zX)qBJQ1O6sfQ~f!%8tzlXq1n!y|U>MWFZIfocS(R5o1FT;FdBpHdb?Q#HI<<R1)6_ z5(}xp5M8;d)(hlSST+cn0;Wyiv<WnqHr)&3yIRU|)DUKlc`FiD1LZZ^(3Te3g!DN1 z3L)ot5kmW_rM9xh0jpNtgchr+t)7<t8PM{ZfY$^8f3@XnDZ9y+71G#JN71K{`n>Ty z6_RN)am15dS2v0Lt`gBw23pY8gjd;tkm3&dv-09K(`ohVeTqNuN-E2o3lM>;!aOwE z3#BzuT077-=Fsy-z^Fo5D4^~llg<WMrky(}ZzK!|`38W10}aF$aB<+51LVmP%$AS* zMAZbi0JSXC^A5>fr2UmGI_6)egC&nJa|t2GgetQfAgSqF@4O{$yyb@Q%8PU0oYT&P z7oL62I4S*W`7p0oLvt}{1)eY7dJ~YB=lkvW-*Erq*TJJt-x`SCAr)QZnd<erQ0R%8 zmlcVj=<4cIq@d1itSUd5ByR{h|1)SSe&`s11Pn6%)$EQIO$YUPB}QGG7Met0Cr*ku zhR7uBcn|@#K1A`NIo+pBLBNFL=zSg4wZcbm9D;zp)%Yq_g1_1{-4^Y#D9;O~k&V}d z86Vya=6>zBq5tB70l<J)0i+heR?J;bYBQhF?VbZbX>qg(&bGXv#U;~B*H(8Jv`}6x zt}y`G<J30*LY{_3T?62o7`Os(fOaLIPyj-^g;o4Ub@ykUfQc-C!dTXFJ+Pp2L0CT} z`Nl$s1U@G4aROTt1=*QUncQ<Lu_{RWBXUOfRjncVUR4b(!(25X(PsDEXOKtY{^9*A ziT|o8BbM487S@sR!-Od!IMB&x5wf&}1O(cKW`8GsD>wzLu#nWbi4_#?pVY3P?ybbj z1a6QPDhVG$=95?#2&NH00uhAVDg`9hj!c=h>ou#b0(-xIH|$hnaP!sI!5=TWoCT)= zNF^VVGhoptiPu)B0)QzC)K6=yvH|S!)??tjYrhC%y=7d=gh>;yJK77h<Td_f5RKPR z1dcjdAQ2q_y4@&?dzp{Ed_j&p*OKmI^DMA<XBN=+4r2z#<_X>^jaP8nIDipkwKj_D zi3VHEAkrZa3FPOh>xy#76krod1{|%)<!pS90EHF+ko8dmM`pNJAsBX0Kc!{7ZZJ6w z$c+vdH-M}~jPJT|&%=~Gx4~&g?H*em;cj#(Ed0$4u=wIT#uYU7Ju$yg_p1r)M!xZ` zHlYY@ZEh3f#<vh&eY0d6n2gizaY4LYlW*r)g9puawf!D9@ZADV1&I6$`IHuw`AMKw zc><wxU!^=*@Y6pk<mC=vSzRgYm4HMuSY1_>R#Dk)@K#3>WNM)pEoST}2tr=11OZG+ zCXh2yq)e()g7!&Rr~1vBaFVfMIfUF=tHObV8%qsyy>#6eyxHCrE!yLg)f<#%)dVZW zva}j(Ah=%uI%1<Ng%Uw^qeTU&h$LFIl=J|7CIkm5p-P~YVkeTY(oujgdCDZ1z11eL z)%LUDkq7RFKb(6Wyzty}Kt@i7L5b*7myVI&lojZJJjiqUZ>x<D;F|Av@OKdxhGBTp zNa!zH&Q0w0dr7gNe}{%6fK(&V`sk7CD$r71$mUHd9~=!56G_TYVj}%RUffC$gRO^J zJWC-0NW_bNY#Sj;;B<lwweSvWu{t7e`#=aoRtTl8*p&rhi3mg!PEf&pvTQ==a6p|P zqHi#VW`z*totW)Q!ZUP}8$Dp47ZxZ|(zh$=2vAHg@MWd1(+=Akr@n7zNPLS-p0vgK z?0g%$|EWUIG=-AYojN&}>jylxfd!5eM{%EN!dMxWu0e;d4}80g7Dp5KG>*1{&IVX` z9=Fo#_~Xki09?y4dVTxR+R~uO%4*V8ln(_<Gml(4XpE8I=?#TtYB2!xeJ+yJiUL%h zxN54v76O_dSYr@a2s8zY%)g>v>`T(bl|c^qT>}xdbTq;1#(;=?<4+!yn!#zw=!Fr8 zP=+L+wf$A*1E>ODjAdOQ&>Z|JPa&c`cAy6=Yk(U76=OrnqI|=Q#MVd2jaA7CAH*DU zvZ5WpO4*LjU=0I9N-dDAFtnS-tGp^M_pP^v0$9{oVp^KM+wH@%Pdo>=+;|UELzCfs zhrS=S+HOl2UAh$JKL0`#HRRXnfVj6RFiSvOP8C~~mHs(K^Y@qLKM8N!_#l|K_*qyw zIuBT8Pn;m2R0lZ?foO@JosmhrUjzv_LajVtizv8x$$ypRgS3bMrESQl5zFh4tsG-2 zRRqFFTSqM`T9-(ksvxVdIu&X*4tqdVfmIoJn@y)Op<oG6z_*fdpfk{hj*024s6dhu zlsa+|PI80M4S+&0dx4hH`gGs~DV72#0m_7p)`#gw><{2XwWXQx=9w^Y>o?%?yB>$I zba|@A)s^VU0!SrPOOV{rViGH*@srY}^?(UYjX4a)V3J^UJZK2W3^EPt3|*b6OB_GJ zT?70b$BOa!3h*~tniiSy#{p%k4>KsF{5}sP`C5XXqtja<=*mb#DW$PKFn5CrB7LC3 zOWB#}!YsEWnYcm{0BJu$mQ+fY6O5@3ZJb+ou<$S;mG5FBaBWknF%c4gcx57uO*iHw zz!B8g$`E8zG}tT_{$v`how_0lAU_bGvG!p34?wZ6CGo|zDGd=zn+6v8vFUhVkcDpk zqsAKyV6_*6b*{P$eV<E{E2|373oL2A#Ye>3mEs7PVKebJmJ{7ab6;K%?!N0`ocrQJ zc<Z*?h7TTnBrm01yl5FLTC$9f77+mHq(2tcolfGh=Pm8|cxBNuu<h(4;fZJNAOj#w zm^fM1f^*2B6NUIt6zd(VCQQPrPpVE|`jcgKl?D!~^(k_jMph-Qq#f&(09^depj5HF z7=!Y$4DyPx<konG{)ZhhJb1`N%Rz<)W#uFtEnYb($Rc%wpml5exj!pWm!zL0M;c!8 zKz@@2a*~_O&=4k^XFOMk6FBI9x4B^Gnz-TXVeF~rVC<pCVPw`?Y<*aHRK?ILQ=vb1 zK8!u`jOA?#ZVwpxHDsyR?!G}R0nG#*c)ESN{X{pRp6M)we8WPs@8Ae*mYXbtreJRf z7Y|Iy3Ul@O*$fSSH1DG?A4`COBy4h#8HrlrETIu6^L>CG7zU~^zVrXdVFiglA~;-K zMr@MHp4>FGb(M~*uCV5W#2{<rAqi5=n}-kmJ9E}d`1r9Of%yv;h8LcH2{SBef5_5V z8S9ymhEeE=Ge9fnR8xsTPp>I~uHU46t_H0w^WT1{@GaP?QXlfY)V~?Hg~fgYA{dV< z_Lrxal`EsP;0zlKCbW!@D`ANbM;&<py#C+Tfd?OYjCqcJ8dhon#NWH_vJLFL=R3mf zf4K*<jmiik$ZW9|MW1B7>Cq`62hU0ChOx2bFz4}q!kstXiyORYb~yCt!*P?%Hip>8 zFz=NGG1(9U2Uf$fOqW1}N2zruStKzS9{-k&&WEX!UJI{#&4%#O%a7uOYH}FDi8vA_ z#8O5=CzdfhG6_4wD@D)Gn3%{KH)1dl<pdQlwT}q2hPZAJPzxD6I>Nnpj|BG65C!37 z?K;IWsOJbgIw*TNcwGsIy9*`cA-%yS3MzP1U=~=c4|$s-JEYXs2)vZnIy9?sZoE_f z4K>_Rg#d*H7&Kfdm<JyeX<Gyc46XVa7};P09(Ub2&%n#y{UxmWg%5+c7i)q@@!8d- zkoJPgK94{Cc$hwYI;Z*am%j{39DnY+@4m44=9@FEPd@o1oORY&X~KHz0-XupV!;Gw z@%UyWpz@&F$e)CRrD^a5n!ND>x&eG1AVbrNIpT;T;DaChU{MtPGk^Ykxagvbxa|!9 z7#Ea%-NqxU*S8x6{3<X2+U{{^0<3joNc}1D<{ytg3Qs-tH0-?du8@Rt$nss21=mbv zX5h)~nt*aBqWZ0Zx`+~u=7zEVQ6j5a@_MsohA({KGx*fgbMW4K9+28(<qrmHqZ5%_ zKI&55P|mW#-ID5NnVH7Hx#ye))22<sr=Ok!|8eYRgVAfe+-}>g!he1C<0ZfK^WOU( z#-IG;Z20FtpG`N9Ir=c%V~<_<`+N2~5~M3F;8}n@02J1`aYNfEc$UX*4(L)5m2<Zh zodVi5?twj~pGST00GRX4^YDlBuSzb)+I()*!K{>5@XlSfh5g^N8~*S|XA9?K>0L1F zP7XO6Yi7M^2XWt%CeK(B;eiYi#^(;)cKzLW)Ajd;*Q~w@9`TWn!r15{`0E{ig{v;T zMuaQ5iD(&89b*?1e%3Rg#LXiz>A@$ihTY!&X?SVwKVad4=Wx=*Y0=K;Vt*_G1}$Y8 zrhs(~qp_q;B_lonuf$S$k!1*5L1gjp=0xNbv*H^Ky10Ubd<cx=(E_TV7t_lMt3FXm zEFc;sk|-;(cuLf=QcEK6vcUt{ZqfN9HZ{eAgvd$&lMkY!Xotl!5mJCK-sG){Vlcyy z7hVnU04Rk8wmolv$^dX^8L-MHkHgMur&GgWQVask|Jk{)@Rygu%7^Xkh9AJRBX@_z zm)xEvSQvEcgin0p6S(fW>++8XAgRvv)>{uQxZna#PvG&6cf7+&E`)CbM9|ljaj^iL zfwnaP2OIz^V?6j3;MJ1fPvk=Aj#D<5MLgJPr=8%!3om5Qu#4`!=RNO%9e3Ojk2>n8 z0+d>4EWo*?z0E}gejz|B@CN5P^YrEm^QVff`STaTJ@?#`lLT-PejA^*CQ(VVxCJDO z+5?{NM<djH`26|pZ+#W^*=H}<@J(+~KqvuK3U*d#(!7J46p+BsWS|lk^hfeinNDWR z*nYdW!(MysrX_6!-}u%k3?#t<#xdE<S!>~T+rACju5IJ}L*Bn1?7QC)aR2=eF+Odw z@rJPNHgC<uIjn$ev8dJU09|$YIs*oaFDMmIS1hPJ7vqnXhst>vR1it8s7+(PKwQ~h z9bD%tTTlbJdbC(2LMx#zQ&T6H3U+WnP}pXEq5%k-9V|h4Un$2AFvI{lcKRwLBW;v; z?%c)U%+oJp9&EqUZ20ym?}B;r=EB)O{~f#(V<p%hVF0Od3{r?5&04PEu7~~rTfXsN zxc#1=hv8}>_J+n_C=AE+vE3sh(5)9kr=CFeK_tH)8?~HQYUy%VnKD!=Sv<U7giQoq zUB#=Q>ME8*C-+JWrJ`*awEMkcD<tOZaV&(2L~39J7u3LdWLU%_f+M1wcL(Z{IALwj z-a<C!h>R$hafs809zCdou8tERp)pbm;1J*woJ7kMhw=!6rnc&ZMxjNA(v8xV)(Z@r zwAI_8Gvl=&(fpbP#>xlp2QPo?$Dwn@Ex6Ji+awdC_tJbDTrz<(afN2ws4L8vF$1o> z_S*F9$Rm%88tqfy25V}g(whXIJp%_ez6wp3W}^wGHkukh(=4kHq-}s3T7uG+ywNWy z?<YU`Ng%+qXO!;y-~T>DpoJT5xFK0#%{Dda@qBLbrYO6Su4y%;cKdQd$T%fwl%1-X zZn4D{P)6x852aYWhYBsaAPAf#>8%7=$C&tKj26KTVlqsdJ`HBgT1TcbsJpkpb(wBe zu;n#q)=QFS2wCk;#D|PVHb20(iL)Pk@Oz884mo�uf1MR*~z1&wb%*5hxz!doyRQ z1z-K2|Blwn%5c#Izks)Fxf?EwZZ~L-CvYpfGSH<>f)J9i5K0TzK}P}rd87;oSfT5& zI`M<bAuTy;B$~<kT^T9nmaK<BM2E2*-4U15Sv}Sm9XBC=Wm5)F9e@fRY*ECZGkb12 zB%Imzr7j{KMB>J|>Bfh`Eq{I#H{4`a_;^%M5thK!S6mM_UUzHE-?6<Cs<((GGJol_ z@Zy3;VS`ya<KuH~h6xj=L%&)Yp`wpN6DC1#Y%~lFPsAEzw|N~V^69++(lI1_oK%eT zLuYt|Lprn=x2_}L)ICH74Qlrg2k4{kCIV7mkQyO@A2aki!_e>O0bP7Da3z*V&^1=k zM$u)s5nE(0M@3ddMbQq~g2<t88nNU;qx{_nTAkX?#{xcx(S{^}RGNg*h2;mEP5wN< z$`w#PT~j-6YWOMb#K|z_UHing#cGE;Y@QJVtBEVYYmPk%=YH!)Fg$Bb7};oDSpLux zFz>YAho%OLrRLqV1o-27-}@eG<aCi+iv*`#bpON?Po&R6nA1O$j;t6eo7`g2f=TyD ztB)?Rl!t^g3F`$57Vz)&qQ&#w?|#?ZX?#WC!k_>A=lnft)JW;mXbHutuY$h-rFD?A zWWe)%&;(L!SQW8NNB|P85CRa9-0>o-B)YvgF|~t$MuC<<nDg9y_uWWVjnzwe$f_Z} z8vWGf=t{)vufLvoWgtQ>HA=5M#8`LALm>Z&PaFpqUUX5|e6!7QhaGl+v(Nq|Tp#nF zc;Xk~-h1zh*3`u;7>+pNaGW-6IzRu!amT`}b!WkXXr-KW);W03z4sQDV{`$*amRfO z){XIt`LRu>oN^k>p8aN=HER}}dg|%QFqMIE7|x!(3GDOky<oH1Z{|l|_&m9+{t4%t z^V>pT@36x*aOj~2u@JoR##`W5zdFwWp~%ziwtG9i``x=UKWM!C=*MRQSrOorb_J*` zoa5j0DEL2chycia_dN)2e)C4~(PNH)Z+`0(sUVwPsh{t=?;*JP=D&y#yS0h{xH5e8 zD+D4_VcYHA3YTAgO*tkM2OJvk?cH~O2duNsnsCNXf0Yuhv-X;J&;jp;tNwTcJn-P( zt(|yaytneoQ{ZQ3{#FSJu=U%wfOqY-Q{?*;Sg>$0{Qmb>a2}PeFfFG4_oEJkTW`B7 zmb(VLeXGsksz2QXS6_2;>I*;Esr)0OYipggUIz;nFM;zfy$<p?2S{t7Ttv!cm#+<8 z1zl=P7$GZ@X!R>QctF+;Rje2=STUG%I6D3CqtD}$|9BqOc<svY#*N+*4m|k1c*Vt6 z!u@wY0581o3UHuV%cVk}c=0ya`prkfE6eA=vaxy4i>5)<841-;Cu-*tqs)r}J_`1_ z?m}OW2I&*HQp~;Iqc8`F;s`VoaCl+`%VR5sB7k&zQT%ts`UrhqbQ@_LQQIN9v9O0j z9fHCbJL!tsjp8%V>#7A;)6!n{TOr2<`tg$hMqGemm-rB0Og9wEkMWy&tcRi32VFwV zXME{vPXu7Hu8jsDNs~12K<BUb7DtQQLVIvP8|7!!q)C7yF_=_~X+*w0OH!@!8klkH zQ84e+Ghy=fTfm|VuFmE_3y36FLV1NRed$YRv4CIv;um0X5xdSj^GtT@v|V&R0s{-W zDBwc;&E;>l*=7YW*hRwD+-A|@NuXudb=O@taL@AtU|_L<2j7MkSXhJ}Jeok09%(v^ z!i>L@(6;<1opcgJUI7Vx5_Z&f0t~X&sQr|O0Fyu`#!yoKQyxldU_o^gf9QS$n^ZaR z!_rat1f-NE#-tdmX3Ut*zxUnuJ-FFsvl);tzW8F!`=u|P2xmpGxbUJ&xB(wL{ICcD zn-X{+<)!jw?J$dhVwYX_hywl3+|pSQG_L;B6_MvN;f5P;f>|-|qkq3Imi;tK6#|eD zk}}MLl=AGb!?vuw(?#F!z4w0jCH&Sr>@kpjbky=^BHf?0?mBSj2M&TAw%-;$^3mf{ zX`lP=6X5fo`%k#>&$mL<{@EpU=m!pjJ@+~Y@4fHAko!Zr5itip_S*BEiEm&3<`3cA zb53V^$SrmA&3EV|D?@N<bIG)il-_sW!|B<|Q>VbVW6ok%YVd8m(Hrp7pZX~L=C>Dz zMT-{mj>>Jf-V#4`!ZA$4i6?yrOou%Aq!aMUtFE`P1t%PTG@kIEN5h;s&%tfC-3`0% zwj+G#sDt2p-~Ty${|7(gs-{LjIR3b!;C=h=fon$qp|lS?^ccqk+!*G@O`SRgFTL=m zuyzEG2OoY67A;x|M;^96EL^lCr!9wi!<JJXi(M4la<F9ekei2NAnfEJz+e|v6pTY+ zfmGzl=M8^>rEe5fFTS!2U%2t_agN^$TW+xd{O9NPf|p-<2ClpI);Lxkjmd_Sh4aV@ z*TWm%v==<`^cA7gU(POyx<3XJM~0x+k8Z0700biadRhD%3uGz8=dziPMiU|2<cYFJ zBMSZH9a(`zhcpI$@d$xV%_E{C)^*H64eCYPq{Hs3Aa<8DnMX;V#YDw%jXsZ@ilcP> zpbjbq!Ah(#pg0H)kA%+16bwt3ie-qpI3caeQHxVtg*>f>pwx1~eVV!J{n|-e#&(yL zAMs(OUEYIX`BGST;csEu!AAn`QsF)Fx^XD}H@w!`Fm<2kd;Hn2wd!*JMAN!yUJ)EP zm`s;h2;~^X1RkVSQ*hbZXx0P83oPJlnaLkdU_=+CAq$5t(rPIkfsI)-&2kB_{1qC( z=?3U}pd7HUl&8sp2;~BRBAxFS15^^`l%A{(65a%^^k)_U34Ll?q@O^C0fIn<0=p!* zsqMx;0|zQE@+?_ubP+hw^ZobVKSX};GXf$4R9f_K^2uKoPXzOGTD0C?&tRO_7J_pN zS-R=)!yldsCx7K@e1F}@`^O%8D1ytOaN`Ys=Hw@S@pB9wyS{VJc<&}2-0Mbb<&N9` z%%GKYe`on!e97f-$t73789zA{4m)fn?Dnqrcs}z*R?S8mZyC#2#PwWx#UG+Iav*%> zvnS$$g^MD%ti#~(<I{c?KJ(cx5y^ps@2xjqh2Qx4iLmG1@0UKq^bU@^>@5B=>*J=I zZimaSxSFk&nKRdpZmjoW1dsuq7-zgLzUQ91q$eCm2j>OUbcyKzX-(EGx8BKPWslw8 zfxkQNVovg|ckRT9cHey`1`v9_@y2fmE3Z5iZn^cZJnqP9A@I2BsvF@WM}Hn{@xm8R z{5X8__#@%=+y54=j=vQoY`5b9;pqq<m@KgDaU|c>QAfOw!Q(4m`w{%&oC`>c4m01l z0bY34H;q}r);+NM#avm`ua)#F1lKxkYEWOPtYwuIzr6p0-I27oiJV$Ppi7fTmyR+t zS`D<vf)+qUf!ZfeN&N5bJ0FF6{`wfKw%RJN-vRr<2mgICTzk#!aQ#j9z))0<ql}LZ zulcb4oA$u@iyq^AOBXMI-tr~5yt@>--Q}>nw>(-3vAzfj&>fAI$_NZ~$3o4nrA~;k zk{H*B7C@)RF_607r>*Q1$PX2rpM}wa==aS<N5^YLx`#QwMhgRKeoJCsRg@q{S4kjU ztuta(U*d5b!yr4XlHfYKv}oD!WEh^Ydg#x8+13~9kYcBpx)Ot0ZW0+uv)3k=j|n*7 zD2B1SLNmR7ftB|=2B*B^y)bpp4?zFrmtpZ$mqhw2wnW$(;qM*(K53h+VCs8zPXgA; z2rhu`wDp1j0}r~qd&%15tpNfB(zNN1v||fA8z}g8KJmm83@Vh?Y2&Hf*|TS3OS!?^ zSIzV-0LzcGo#@gGWOtt)Y|=$5&j=t0H0Y0jG19>c2?*RMJ>93@B<Pi<FmK*G<{1fU z0~~W*k%d9DQQ36;;0HfQX{fx|{$y#;MbGHB*2l>RT*yKpAPFH$kF(A?Tij-djV5xo zBx0U?@~H?sUsHN3c=D;I`5sviW{dB$&)yNl{v7{qN+aWmC!PxA4wHNtz(e{+`vG(R zc&&-9uYUDAv2BYqoDJ~jXl2k9<0c#^`PhH_JO4iQ)H6_RgJ^{;f^(vqYy0iDW-!p| zF;^?qQ2ZjgzWDdKzdoNI@+XjGvTJndtPC1~51uuj`OL9+>JPt;r=IdPxcGvz;FzNi z=lf4T{S4fE%U_y|OkoRW(XzCS0D?s8Hrs3|ZHg|i2qy58Gk!&`EZAh@H*(r-w%&p> z-g?_#nV1tk`C(3f^2tAtsyHg%fggPTY`*`#_w6BSp*HsS=U+kAhsZoINnc#}&Rw^Q zX`Y9lpZ$lRzAb!lw1#VMyI)giX2HgE9Fy=T6paNJpA!qDQdd(5;&IZ&r@RAS*SPY| z_n|;bS)(NqK$p^Dj4e<=TRnL^US4^55&YuJYhrt^j67QlKK;of;S(QwFRZuWM$lVn z2&T_^J-lVtU10W(JHWqfvOTOeb90!!+WIhg+UhWQ@)Ve~(zGz4GXf(KJSLF%jsQUB z4lTW6cT#kBksGZd;GpxfP}Yr+#S{bo^htj)M|6|Ld-P5cI;>Gva8WvS&+$Tm3N3QZ zt>;Bm6+f3H%6x_#baW#nWgm)Rg{d2EiejBrfaTmk<DHGON@E~}c4i&mt&xTWfG!O- z)8K^3VaDMn;?SBi$?e8HJN>Xvz{@}UVhp6O3X|Tpb(V;j)Ml8n_wEpuE`!C<2diZ^ z-B|;Ef4WF$nTAZ7Gzlycl;c?}ZI^RZ{p*<;R|w^5s=>!0sbCF@4SgBV4id@f*k+AU z9K&DKeiHa}UwIKCAfUOMeE$;v=psO%`xg5lt1NzJmsWH$u~k8qNd)8&pL0xvz=!gz z7h^#L)Rd1bLM0<v5##XJj-qfT85G*9S*a43tpUMXXNa?A&SYzb0K_q+0n(U2qzHH? zXb_QC9Hrt(RO7)MDWYYBu<53oL<?;peE#z%SlL`WStfK*aGnIa@H=hD;|@IJ;P)j0 zZ@TF=PIA-Dckn&3Vh%ZYKREp-XDgkV8eWaHZAszHx7-28e*E*$cB#RU1gg*?eSi5C z*TNoq><q_$5-_^2_}Tw{?<es7gZ6>lqcw8>1CPMg@qPpwvTm4mvOxYBtqJ<8SbHY~ zso8x;Ah6M!Hc*ssN}wP6AyK70h_KOy>%;jMTxAXtX5=a>PmXd@z3YN{sC{U5Mp}6l zwClj{MlhW_{}dcS!?N^;x)&mUvRjIUEz+_l+4s}8ft8ezTW^01{<=;dN`QitpX? z?XYT$nY<L0;(uFvC72YJ!TGmOfk*E~7^@e-*z!*Nqa$p1850N2$(<MDB7slmt!$jy zMm{-gQI^rtqdsFHudYJ*O6#*w;yRo!*rNB;b}F>i)xcy0cLX?TiLnO4F}bA#d#j;g zc*DADz}!mSj0G0W(1j;ptL3s%Br%ZC2<~QFC|6o3*S)JGP3Vam?*bDy-3f-)SQl~9 zL^<t?!ZgH`k*P4_!~YHQ&iDoltu-^ct=8lQW{prfYUP9WgKnI3V~_m9>MDZtN=xD5 zp{2UE;)sM8SpYllyz_Vg_wXv({=gg@6e=sen&}%n4UKkrVeVri*aqg{z#d$?NPv?@ z?_6a~HyAGv@GG@^StR(0cUBL%<HTwR1{COkB>|CHD|S&GRF1!>POUc#paZBlX}D>E zk02)$(FN(6Nra;2pzXG$LX)%)6Q1c!d|7&V9?8Zj?@q%^BNV(0=>ZA*b=FxMO4}t` zD-jeH%wNEQG=wDVk{~tr6#>wXfAlSY5;tM5z1|6@|KHi3O?>_OHy1D{k@Y}swEOOV zI6Uyc!^&9`3AtS&$pxpCH#UFa%B!x!_aC%xq<<}-pgIA?!bs0=es@U(jxCsn+s01< z6`KYzAkOYP`axcK)RT~@ZUT_C*Ir#=6iVJ=W?cFP&N9rO?68_UH@Y6j{Am;+VKgU0 z_0D7sK!y>g3fj}`J&`+sw>E@6uQKK{M}T7tq?C}Bt6A9D$nScpV;*uJQ2?8w54ET} zRiDqFqIZ8ljB!8=bieT8TsY_VcfjheTMgd0{_3#o<=4RjPxj%3=N^aoFV2A_3toU_ zOBX;ly7FmNR<FA}mf4e+N{PV*Cai(i?*@&N^HGQLX4wE1JTne(u!mO$^C^in?|`>w zHU_N2`TPWqgV2+Tw|oFYW<{ZPkQoz;i2?WrAAA(t9N?*Biil_<5=fV~XVnq|X;>0T zpm|N%$_y^JZCX{e@@g>UUB^d?YToBT%n^ly@=D-rD4KE84?Pa%o%RiQ&G9EfXVp~z z-7v6GHzT?R=AQiR==PcijXI$*Fu`ahpFX)-NO)Obm^AQa+RzAA+kFy@ZRIzFH#F{# z2TslVzTSe*jeG<2YTtkd&#;1cP@}KBIm1Gn+)`K=JRHkm!B1{DYcGKXxunPnp=V^J z&@*z=8J`UpsCac_ApuVW8*YCIoT!a<v<}h@*=vJkn#3ICtxUWS1s>mzR!C9`L||mk zPXb~n`i=z&rWlmHW22!g7>;4yXClgVU|~xDu;*R}Dy^7R-c+}l`ym-K+ikm*xwjaA zw%cwiXkL_N`t+3<B>eU3-&_bc-F&-&DyXzJ<HshZV_POAjW<n9aSgi2+8|ffcmDVP zIK!1!UI#~i=n!6MW$_Oy>;4D-4%@{0bd;ZH^L^1&W6>LJw7v)*w6IUEA3bAIS4#&h zT)3E5VHux@%-*8;(e>YTEk|pz_CLQ_oZ}&w6a&|J!Q@GhHvslQg3v+VX+c*62icn# z3!pdyQC?RRW9CU#6NuEJt@Bn#1bLqan*pT3*YQa=h9yR!JGLx5J-P^=eP#}9@cPwY z?bSAg=jM;X;#Z!4#S347(WMJvth)?)-BGN&UFi3_vC1AWkbtNz{c0qJN0uY+At7pd zv7UaPL50tY=a*ImKIl-6a~Ib)>*?Hv{PHJT%$^3Ujd`>a8$`Fs^GZZa9b-15PdsXZ z(z-4wH*BTQ5aUy>B_>iqi$E@V4ZypOoGVu_v6{L%Oxy39v2ha9;A3C<ytzeV9mw$x z`W$-Qx*QXkclvjrUNS28>q_>?Q2Zx;=jFYhJ{CH!nbFkdS>Ux;1nkS-Z@>N04RU3X zONK7L!H$F>#XI63dQI7-Y2!r!Hg=y@ZrN`t)0Vp064sV-d|U^dlI+1FGy&Y6H^5`S z*J9;cnU)t6gh==kfM~oYfm$Qj&d;J{!3B{uNB1SzjeK9*m|R~}2l0=7Q&|*zxAxH= z)feyC*@uqJxgkx#orQgVD1ss+Aw<N_pTB_JSBD*X2)nYh{VYD{ND?cCd2RTBx@%k} z0OpF6lqO%ZMx9BIzwf#C0R{kycR=<uaT&81AXFpvb0*&Vz#;ETMICbJG2z|&918Te z_dXwhj~)Bj^z0)a`5@q+K4Bj|IIp9oiMn8#d2;EY+p0oV%q_Rv37<aU7>;|81wvPh zckr|CfA^&5s(Kb4h^{Pa;H|gb#X<FLws{K&bps32I>tVBXAn5=50`=5^UNyrnc!74 zqMBA-ZS}UzVCvMB)U1w4#>Qaf$rGB{QbY*Vq|@;l6#NSXB_y*W$jP;qiv8*$kONr~ zbp$FFQe8fFr0#e54T7N_i$(MZCIW2&?AQI!>vy9}UmkkB2pZibIJSIo7+tn78cPds z+2VO&(SqmUZ-2WN)?4Rg=q;WI6KZl@&4<xt^I`e2h0zLGLSPfC9OHMRQ=mMM3oC-< z(6U9?r=WTSm{<Yt#fa!cC*kszNIPC#PHC^X+5Nt}YL<Wo#hL=yk5h|2A-gIAG!;(a zsaGX=x`s$sZ{f@AJ+k>~idlu=`i~MbAJd}VB;34NX%iB0;7E-`%anI~8mg7nNFd>Z z<DfzF3@&mWOn=_ou;8p8r!;}n4@utmN3oI_AN!CIZ}hE5^A4mz`#l%5BRv8JX~)5Y z9a$z69JfCM5nVwQ0LCkRa1jCJH{hW_KCL#gKWOPLSD3$-Km#DV21Aa8q_izom@gMy z*~Kz!>$hl;1+o~3KC&#R?X)V3z}AA_pkQNwK!8iYV;Ak~pl1X`XP<p`8Vgj%$tR!8 z>Hqe(zp)h<%g5u6I}Y!<>n^GXp=fs~`C(#B4V8v<f~_cnGBHj$^)v>LpPq3V?6AZ3 zu<t&5;d$qs!+Sz3rG`JyjsiEP+k%T@kNpU2zr(gT&}pdFNn-}m?H~X6r@V6NH|PEo z4*kFZxap=FMQdVfy!^7?(jS2fVm80hBqsM1UA+40@~e^DU4M>NMT~)PAYJ#6z(*s1 zgaULEQF$k(eCWzmESAY;TAdqKc>o$%xZ<ko)XKOM=FloGO-F7lig(<~)&~ZYCciuH zQU;Zu{p4G4!29;XjW*f<4tVdL@Sn$jh?naAE&>R^z^Ypl`%oNUqag5uQ-03ibLoX= z;8t&)4ZH5Vb@==VN5ZZ<ZI%0(OV#loGL+P{z2wO7g&x;xpV+UO-bK#whnmj_Axnfb z|31i)Rsx7I0*#n2e)i?BSCgx$OMnwWg;qw9wGr<}km>f8N14A2y1k{*o3$KAqXn{z zKxD})uzYl3_~&yk!qCXQFk_`1VInQOB`bx%V{{qxyOei%APc15r?Mjrk-q3Y3Q>R~ zTOMOQsQNvmW8kYE0ZA0p6b2FUxi82#;uF{VjM*r!p_Nrq!e6!1QBO5t{G=6Gw1-5j z6n#sGS>zEzBY;I$o4ja5%=tX)&`yxnX)3uY6)-uO-`R@;fos!<xe=2#{~!#lzF7i_ z;;*mPh^@M!HP5fS42!NgpUWKk$HQUKMZa-*k<$cCKeXmrF#X6wlHeRi^ER4zvQaF= zz=8zicfb2xrq}P(ZeEn$?bL3XJV{$`%e$g-T^Wf!4-Sy&Mknm0L5PLs3Z_M8t7O0` zYFamDty!HU_$f9-^b)ud01|-EQsw>k-@oaSLtCC3`Quf{KwxVCV|7s-^qb0|i<SmI z{`liuKCQU=as(G>$im`6X9$#IHoKgXFqeytQJ@SLUwj#S<tyLdBT26Q)1`3UdB1`g z5m0OumT||~7c3E}yi<Sl6QB)*-~QHD;EezKq3UW*kq@Z@^SDq=cHyGMu=^edgi9{H z3Qj-mf8my!u7oQtlg)N}?)`oaESmvB<kNgS<ly(Fy(j1X`VYpxf)(ffhL7SA_tv&s zL32o^4zjW2{6ij$9r?wg0`FRkaS*;oZmZzZUv<^>a-Tn~%0O+x0}ebU-oF99`<)Zv zs>^>FKflO9^#cz653Mo{?W_nH%>dpY;cvIyes?(LV_)F!=brsNIQ@rT#y7oTJ-GV1 z+k$p9W(&SnASQ*o2Gfy~d8tl%7K*$UmQ9Z+f9oihW7H;)wCx3UOGV3rERdS5jVQe9 zF#?15i1uwnE2KxCqqG-;)6|ll_jd@8#28JVoLD^=8(W6GD0n5#u?#P}_=d30KAXcM z|F{I!T6JHX+=)QIn+baiAa#%G>M}q@aN-v_h2EH0Cf%5ptdDLlAZ_NO_V?(38CqsM zCG>}9V1L4E!}1BM<MN@^VXS&>jE~QVZJ)vm8+hLbMLL4SIP{f-Iu6-739=Ku20Ne2 zBoW7aA{}gC(Cw<xW8f@m9eUI`H8>%RSaiM(Rxiw~P@HkZ^*Qd*>GOBczvU1A36|dW z>+AxcZeF&8_k}nO8CQDezA$CCeK>E3K`J?un9AfgrNH7#uYkpuTp1cP7W8<!^PCyn z?C384EV+g}T~KQJg9S8%wSLzzFPb0;)hM(RtzrE5Qc+I`Z8(|wqFMjAzsKuKax;;& z5H)ae|6vPFE8<ge&y!|fB6xEeaxu})aMd`Q$-HQ>Geoo>ESWf9(?WmrzX8(P^mt!a zdj+m@{sO%EPnYmsj<>yiCx=5Bx9N+%P>NSfEnKiD%#)ak92tcEXbl$u7y61o;PhAz zSwWPS4q?n=2(8Jw3;-MLx6OT`0jBq(NF&_~uUhg#gQuuif(9<Kc|wa~p&~9oeUFLp zUBCnt856jKBy@~l2tMDm7<ZaBbqXw8yd*@IS86C?>KwGyJIOo%T5;Nev?Lc@FUQnt zt^GRo(a(AQC1C--P8D45q03uAvcW_r28{$sw^f}`4-fGhq((+MFliWJn1pM$it&g} z=wS!>?c}_a*G|MmI#iJ3!$X8T^gp|adf9YEecwhEh4rKkbfc)QdhvN*g5o116X_H% z_^;0$5j`Hq!|T^RJeIT+UVQFCn723rOrKvRC~*XBT~&=B4s~QVJnaOp*+U3ko8nf* zzX?>wP;_w(^*P=@8Wr$fY*S|}LQJ$?hN5MI*k$?Ii88rjnOd`ajt`?=-w#}TthyUH z(!=362!^2tlcVlFAp*y8etTkwf6>H>BADLS+t(LO_4zOuvt)=tLo0F(={Oh=fGJPE z%B`~jNQTj(7huT^KMm7A@B<`w6rCJN;6T7IdgrCE_>Z!}gvwj|#|xn|otF1*qh*Qk zwMr+vVFOqUSDJtYowzoC(}0I8fZYU!0w7$m0|zI%3E3j)j9edhm2$~FLw^3Y%g!ch z(CO=3kzQV0O<-#X{UX@jAUd_pzLN!^?wg|Tn}8O|MFE~K!H)xP>CmUdhjQ|!_K|+6 zz;X;V*AYO{JVFwP%u7?JRJPNm!NU*x0G#}luTxN)@6De5=IGAa4u1K|Unhy@+L_k# zlHy0f;HSuKB&&Qv_O-ddc`iVjXguI7RRqZxP>&Xe3ZWJSq?}^X=8)=AhL(IrJtt`( zGpGQ~+JPD#sAZbbBfIHxvk}`sT(%TzalwkrPeXE+=X9}>MKSmtL02~OrLiSFseNbC zFR%w)jqI9*k5>XPNsc+sydX64a#JV=3v)vjB?v0XQGigHgGL;cRyY$u!kP~Bh=Q+6 zG1iLS3NFA?=apEfTh^6a-ZK%yvN86c?~PUKUiybuxDMf@kzN?>QQV-%F&17`MOF4m z=yvcozr6wuJaB(F^Jizkwr@EZmaeoV)T6h-{9bfr)n-9a6g<*GTT$u`FQWxs<)yTQ z+*{PSm8@7`0nTnO8Z+$L3ZWzKFz2qSw6iki)lz_ca;NgL0aYB-A|VT{?g#a7souf6 zD&>7+#HPN`po$4LPvZ@teVJ<#8juAvxti<?*uuJcY!NIt|FaNcM896}5_G1m&Q3Z| zNA#pE_lA1@Tv&R?<!Rt8y5!ekXw8{8y!P5&dQopd_vvTdV9vr428AfP!S4ojDXhJf zF^&~c2vBff(Eu0|mh7r&yYyTw4-&!Jk&74*(5>_|tsKXXf$!Q^g~ij-4uI1787Qa0 zXMdqf-yAD4zeU7z`E=|8&xg8<=cPVU!W1FUiU}&vO$oQEm0+%V#~rtaFMjdA;PAr_ z;iF9G*<ptr!bih@<$u1(>9cUbP`Ig(4?P8u3z@wNQAtB~Op~hZJ0?UiKyyl#c3lb4 zT$(f{F}Y-{Q!*%_9u<!nS1>U+ByJ?gO?*!T0a*Sfj;lo_2^!Y7!>2@K&d-=rC)%?j z;Rm}PWCkRzaaEqLN<`8aME>(3<8nV0RI@<KoRYp(<4pjQyQjiB=rUQhBBGX#@(x1a zgW5@T=<rb@)*_Q`{6>wMkEjiSS7Ox!Hf%2FPIjD7^<X)SL=AnpYy#xfS~6Vdv|U<U zb??0o<No{q2b}(+)8Vi8eGfL@<OEnS_Ys&n(hc*LES950_<%$@{k<oL=JwRWk_~`5 zPSeUm8BV-VtY(qh4-(6!msWAGy$-xNg1UlV`N6MC>?@k^n%_ufFAbR>l_}S$Ej@n2 zA}@0e=Gm$-jXbU&fmf<QQi`*`-3zJkDlQTFKI7n93U?E^pO)Tn3XI-&KF>J<k7);= z0@dV6$<@U!u9$w_8J~jQi%%s%KD5ef!;Fu77CWn~!q3^I70s^sKRq2rV}RU)g{KSJ zHD<7J+;G1@^IjUzrC<hZx4c^GrOkHk%qhNTuY?{??g6CLwKNWW1wD?&5Xz<0R)?o` z04$rl8>h_He)jD$dK>)ZPjd-DVXOc+k(~*ZrL)d8k%XZLdoU@OR}MjT$%HJ=0cmIY zamRfWW^ejta$mtc_ufxuV1@Z)k?8ajqXSb&*6LNf13A4{rL(;x5Fo9A2Zv!vD?oeG zU}+U5LRDz%JH-oLSbH%^do4S^n<O~Kg_JW_?&}m<6%l+NBss15g#{t^0i^O%hgm=7 zvJE%$L3*^CId9K_fjKFJ`5~g1i<yrsw)Nd76}yt8k1`)a?)e11s9rzJe2@(0vJ<={ zQ$f$FidYebhmp^6rQ<t*Jx+Yopl+B;V-J$!l7%peg`!wVX(!Sy?kSz<)rq2bv=*Z3 zyqtN$#Fe5zAA-@|LOAICd%$&9Ujl#q%U!VEtbJhSntQ@S_kBCoJr9;fSAMN}W2J{V z@~(6)2U&RreF+sQ=QKL$uys0Ak&fu4^Sb&3j%2w+k5h--R}3=U*yK8N=qUFXdx1_j z3Rg<s3-wSp!bqQ*AOD7<6G{O=629&JY8;AXRnco!F))#cCbtzGs94D|VzO>Ha$f~q zDolqwqMn7-G5`jIgdb=sy>wMo9uUj!K9j)1l0bjK3sArKBvk8c3^F$j*(w;GwJ`w* z+F<L?n+v_UFY^j4-T28@|K(S_fOQiDyyhO-Xhs~cqzX+72Q8B{_#2w~01vzsK`WS= z^|%Y6!8`XoCu$MijlKZSgGRXnWwrnTdj2$clG^I&z!uO9Az&kYvTl6Y8lQ0baFskN zw(A>JusS;VOrDS>azc8M4;2J2$@L;@<5QpdT&kYZRQ86#v>HVPeL|8%Xi|`=78ahh zp{oflVQxOe!CW+H-uNyNpMQQ7ng9%LV~O%1^<+qDyl~$(D-@#-Z8u8xvjrOiA=6AW z)w%B#6vZIXR;B2S^}W#qg>ev6$cAG61A03xkJ(BNT+)8P#4Ix}I@13d%m@K>m#0%= z0%EcYbn*vG3V@U?7EM|Nq*a;^4{FF<3Zz`i8wPE<>mEzvs1U=8kjc%(Iy;|)rL<G{ zodjz=JQnKFVd&C{wV-ZeH->3xZmqKJ;)||^qd#&8{N?t)z~fI{1QRE$4(rT12p)Ol zv@oHX5J4tt{dA<RvQSJPR7+jX=#sIk<kox$mNb;zU_@BWyXJXP(uP8Q17Tk*4_UUw z)JIf9S#`!%9QO?`Ly$#wg+MV2gj0n89i2v%jTXrJe9{1K2n(;RHU(^+29wvYsmy8W zCC?RFH4mn#tD`AXS<#8fmM^A&x)(a3n!c)z^N>>4^IrC|uK)+5(+fDgiEYnYglaQ= zY6~>3hBn`3*@RG9G=oy3VG*?OwXhZtOG}}p-Jyjq1yB8R-<%cD1Z{0J8X7z<_?Ly0 z0Ei|ISr$~vB$V;MUn{5kNgBsP6Q+<9L-g9Q2R)-trJX{x)i0W>D^nX%39yxoSDILM zrzIx3r5k)O0gF1_APSg-q^mK*ZWjKSbzc+ADkpP*TM0}PBcWinHW>I^w^q4x0GuKv zAgTQrGLw^NbxM_zoaj<=m6cWQBlM7$ln>65=t#OfDgf#f&uo)>6@~)2g=7WqLgUgl zD1)=|2bc(z06D!NoR7MSh0r_2d1E=h?g9({V?sG9(%yBV;*zMMldC$DD(sH-X%9xi zF(<UJGc-AV=|I1`gfwjU_YWTk=bn8A{{7)cp%Vk_TW<0tSg`2t@XS9i3nLK_Mq!j+ zrz@bqhmL3rM?fESB^7@|3HeCWf)%QO<o${+r4H{#??Q*-JQZ0V3?dX+Cr=L2XAgTE zc<)7vM=X$`Xmtz$o$*WGd68Nzt~FW#MwSNw6vtMgCBg?dvU1g<cnXh50+*App$Qjb z-4FYQz=H1L7_DC%;vdC6n!;23_G3#R(BJYUF^IGnU~Fkb@CY8gE;z|6NH)4O#J~8t z4C-Y|0Y;alavVKga2J9txR?cGDN+bIFR*oDpa%l~yV;&Rk&-|ks0$H&dFVcUp2Wk( zghkI^E3f$-@?<UeQuIy!?gUNI$88FNr=bZRp1+<B#3Z2f4-qg6Nv%<yrNpX0A{1i} zvrsnSWPMhpI<NpLbiyme=|E*dVX{f1oyNmFt&ABO6n7#ztrSA<zfZ%~Ktk)r41S3x zR+f|Ci5nR_iYh@Aa}kLuW#u6XQ?)pivBEMID#_~7`jaLPE$%MR2u-d(%je)21%7<V zT*BNwwK8*h!)DB#m0;ckH0B|MjlMV67be3%tR$__(UG)}#7}DuHw^*ucd=+qN<g;s zXi&>(wc3p~6jF3Rz$*d=(GU@&-;eIAv97ee4z>|WEumOiCko;~N2&KIAcD)sy141= z4dAXj|H=Y+!Lr9-{h5bCH!Q}5OP_|}&Lp7CiC}ZpthO{J=|kN{e8h@uJr}bm$VNln zKuD*5^di9Y*mZ>!yRXP~#lLA6OrPJbNMRc~!i0{19|CbGP|OH)x039-<Qr-8BEKJ9 zgZQ;)H=2SFoVF=FG>$vPp4lHjYk=1ar_jugNkhrjik63t7XEE%LUvmvq2{#bVuJX5 zj+R6~XmJm@&vak^jAp9`&}lm%nb5iT@ycuAX`&s<EBN-~07ghY$HP|I?Vi&LQ?ngk z(Wh(nt@V}TfzcOSJNTG~P@8{L`2&7^UgOGGC1Gv$V`Qt%x4Ck@cRyxSMj3cy$!6je z^D|6>R^*3rQTS^Wnmo@SXq{!ugc6{VzX(+d`Tmhq_Kz~6=!cNkl<D>o>33^@1LIVx zAx9V(b7?^U_eaRyea}z(2&n~W4D!Tcez+9{(ypT05-~EaOz>fDZyH}gMRiCF024m0 z8z9RF-eheR26Zc@eiQN(R062s7lQa4GeV{LA9x>$9s|PTlQtFh^-tau7=oiU{YN{{ zLoNH)u^)vdot6&6p-*RYN!J8=jYo&ym0N{MPsL?V6LLI|PqcmL!GFM;H{TMbO`p!Z zT(amHxbM;L!OXSygUKtc9lHIon0ErEo$-ohN=|Ag1?nkyPOHZ#_#wxf&|l0Gy0KaU zH35-;-G~YNM<5bgNtQ>SPe@?{hbOPN%EVQtFYO9J-iKZXTg8Q{M#)hxMi=K2<&chO zJPES!MK6TF319a+Y1!Ze3}T^WTNw#l@&GKX0MnGvPb^0axcbxJ@O45%_`19{DX`Iw z)V_w5;KskIpQUg`-)>*8r>)VZ#KWd0kEKSRc<agzjkXxLCaD=p>nVgm>!tt)%)ssY z+4C+1VjKO{R(^8~WKi&$va%CF%K=TBgt{@$Q=Ke~P_`ja1$NiI>rhavK!CLDSKU;C z6lhk05^b^xAt}8^UvML#0AHn6$dp-DVR6qIo~5+6gq*^V?V8N=qNZZbxe*8GGv{0> z8DeUepPRwgl_h`9>}t0K0+4%1=+_;|!C_S412%dzKV}%KY!qADF^!j$221+DjbAI; zAT-H0`w5VEiwS$Ubatmv)pbTo&?(_$lm^7a`ZEAys~}nyJ=!@=J6J{9qFM{|%3OZ! z?a=TDRud=Ta168$cld>|w3rJ=MuuU%*RKT++;=}$+wCoaZg(lXVf_!`+?Q^{-q^xO zK@5?HzMW7deGY1UaN~n8fdP?CCnSrc;vap&uvk}gT@6XRgZJb`*A*}561Nv0oJcRY z?eTHL<hmN-!$^V#&!xe<aF>rW;m!-PPD+_1LrAu5$yjJ;O-UO8Cm>Bb(C_IJGg!0= zd@r=HF$tZ3O=-QgVVX4}dNrjOq)=+`=xFtI7)`+e+rT}aw_%|qOUGMDmIWJtf`b5I zbQaIR$&8RKFVFMB?d98pSj4Rcz#t4N{K4@!@yU4Xz8f7dUOkO|(zcYc!|+!ag$eLv zzZM!ZO15h<yJ49G2nv@K`}++;ebp6LfhqwoxyV8YP>QH5Zvto-Q8aI($gs&VGI&EO zNqd%5wFRp4BX2ciObV)1hcsfO>9$+g%_IFwZnb1_6u6OrF1XtYw%WTUjI8{morly^ zV|ys(zp=s3aZrIBoM9~PuyV{5Wv7W3GJPzok|ij{LO$%!c$L2CxXFX2&d(K0#fNG9 z;PadW5Q1pbeD+kbT$nyN=EQ2LC6E3VumKHh_j*zP?~Vb#TU;4cv-gJz@5b7@ari8c zV{<gd1(wF|qwzkyov;UY+;Ml<>}^|Wa6Lv4q80Pp3)jM&IoH5O8=ny479+eHp281e z>yn#_g5J@Zi0-MHmfi-kH29!Ff`Gs<U=a;os@vn$uwZ*VI(>N^2wPLM`v!FXISuk5 z1`Rp#3WHf3yz8Hu*6)M*18A=x=n4nSPMBcA7R>@N!REE`QoD4Q6D~<;LPLOKwh%lZ zS($}DAE3}b!Rigp$8SR1-*?(Lw3Llr_=8KB2B8YTM!O5}1Ax}&;6TIi#nXdWT5<jp zosdp>Jpf=syKLNR(h>&AknfGjpXzLug{8$-v=d8(Ao1DG#sP5FX;m2%n7}p(hoGn4 zTHrjFUyw)wHCqw}1Bqs#LzkK&rwy5ZCa)9l0TlfoLe}Pex%RI}+>9PZoBDb~CMvte z40wVDQneXcr|fce%}Z9E4IsCsK1=D$6pO#0vs)nZ7RBYHtPyr44_<0O>hC-v`H?JD zO>@VO>Bjuex6u>?*T-1SQ@zI!8H|6@RQ*J7lOz-h6<QMmpdZZOWr=hEX0pAt1`VMV z-24xPAQJvsoK@Ln{fcb0#JEO<eB?=xzEYTF&52J-i6z$j{-)^d8j`mO(&DIIptpD< zE*tH_%vtN;=;%UtZqBm|O2nu63-5!8BWuEHuiXk>iI#{r$haojoQUaMFW>_c#jmBN zp{%;%<p34$3@39T2Fzvu2fYrR@d5b+Fp7IbSfUqY(R<qIb-I<RmX-KCrAR%GvF77o zco{;FH{8lG_zbUTeO@_UmMTORKIP38Ar@TB!3i4=5Hd5pspvFbXaNr;aNK%*eQlOQ zOIy%u-I_Nz8k&|5c$zV5ww~_PerrS0nM%vf^P&wPg4PAD+~C`XWy~Qo{=k>-zoP>T z*QUffUzclZ6UaTC)<3ctxDfnF1SXm)6+z%*Led~pEujPmEef*6ofr}<>i`c6zN$9F zb*Pg{Wm%@tq_Hx?9!pt>D%8P5N?t_)*#hu=D0K>3%uOZ$TaHN+T7Ha_GBTA1N##zX z3o{$o27m-b+V*5kHOpzJaVEz3R1L`U)6?XLvNq@bMl6!#`CqwvxklF7Av+YzoIpO) z!*y~RLcvM;0EPj|;Kp3{b1wa5YsLVgHcNvO%8??#mXJaN9oOD>agm^-jW!Arqa-c@ z9L%Oe5PLBu5&!xTCAu*T5o7BxHWpxcG*m|8=U6u?^J5gR2zc3r*T5co?;-C=isjL9 z^;FiQ|M)44OneQjv+jXFRt8bo4`Z?F9tB_60^x%n_4Hf$-qYQK@iT_wAqLDtrQo4f zNR4WJ@!m&y?*{=$1PwlfQ5<?|`Regl0v;i`uF$$utU>;QHsZANE9?AFx=;LMEbdtn z`^4;?Y7=NatrtcEX<UAABef~my>`@`cszf?po^xUQ=g%>y9r<(AkwGR?b3U?d>UVd z<u4W;i~|NKo{<P{xW7W_IxGCP&3YPqECh<<n+GTl9G<qsyT%wvQ`*Z=0CN{%k~mtq z3`d=*IuMlR8d5^ZoXZH1ER|3wDE@UqJ`|Sn3azfcSb=a7#p*<dfTsUa5{a95R%$;$ zsUR3&dAttgL`nar{>|vD+H42|GXm4lbl{iC%pD=F7Xy)joMJGkJXYY;n1GonKA(ZJ zo#$pknPn}MeJ$Xls(a8btPAv#w3q=YJI+E%qTp*%8|2VL29=P)+FF(MTjE418-ldW zY7ro*C0eYd@dHsPfsYh15P|geCU*D$LlwU{P+VWCgvL8Hud)&gfsS0Kv!c53kItc@ z^G)dcSRXpQ8hMv_yuW1OVwkb&>afz3$sjAKYCc?%K;f@<e+6E*#yen*we||Y??EAI zc;5zq>>iK5dr`g<VDuO$Lg*p^41Y&C-HP5*LObwlH7AHlI^4I%yVl9#h(UhZffzsO z6nKtrQ24wK8myA41weS^m8`^K#?`83@wl)BY8*uW5;)<DgDY;FTIdET7XEh=fS8jG zq)h_K*8>e<4THklr_F`y5Orwify&?aSujm1pE%^8zSimKghu<VodvHNzyl5bq=g5r zzQjXo2S5?H4+YVX1cIlx0Dfy*D1+XKhL-*UUsg*WfRoNe|L2pPLDkW!Fk#J!B6715 zF{aKHk%c1I)cQ~?N|uN|G#o+)%)xG`CT%y%F_CM~TD0c_B#JF+fUf?$h#;_g$B!d) ztrOpgJM6Gvm2;uwn$dH|nK3E33Nf&ag@yrnmKZkMoy`7BUS@;c3yC&E5!3FqOSMR= zFDY;3n9d~UN)rAmJy48SOI-PJ7EEE%p@HB6p#TYGvrTA8tWGdDogo5ZIsXAl*<~Hf zO$w<sX(WXJ_FjuzQjjf}0w@J|rXC4;u%J!Cie79)yR``(>|GxmwHH%;!Td$x?b~gR zf4lQ8*GF{q;JN2-f;VmWaqM-M;Ic)JfsiM1+B67E-}~%W;$yk0T3W}icMlx#CdXCH zFvWgm3b9AZhT?BpVobX^Iw(E>1`i9H@QY!^Z58N@ALs~QV)?an4hHM-WI_HvrDhPD TwDzM`00000NkvXXu0mjfCQmq! literal 0 HcmV?d00001 diff --git a/docs/en/docs/img/sponsors/kong.png b/docs/en/docs/img/sponsors/kong.png new file mode 100644 index 0000000000000000000000000000000000000000..e54cdac2cfc3ab17df39c24d20c5437837a7643f GIT binary patch literal 30723 zcmV(=K-s^EP)<h;3K|Lk000e1NJLTq008g+003kN1^@s6xT3ws00009a7bBm000XU z000XU0RWnu7ytkO0drDELIAGL9O(c600d`2O+f$vv5yP<VFdsHcbG{;K~#7F&AkVp zWkr!cTy^eylbIO=kqjc4A&E*51~VB~MMTkcb;ax&S6u;dS6y|%-8Exa-31JQi5!(Q z3`szk0VD{_3^OnTOwRA!Q(t#i?DO7W-2HzC?!0?X=+j+YRli?Vcb|iZ*h1QfD1Ajr zUom|zyYfG2AB27STaTChd7u0x@Xe0t`S~7NM)z3WEti!`%NH#F<P-B5d1u+*V3V!~ zD}aAnfn4u$v6hce8kergr)Wd-nPqo6&@@dxu0@vCrgF7_A{?z3nQY2&K1L7)L@Kvj zf8yPITDeELGx%@RDihZZRVd|m{{MN?cY+<K?*dEaFMylRz7m!%TnztDHt(}P{ZjZd zuYHDljvq4~KKX`Ez*$$H4G%x@aL}U>dZzlyiY_{iL1(~qmV!Nimg#*5s!OqATp(Xx z>3*=C%08gBq3%8PS`6jKJMv}Hh<I^zLB~MlLaRH)o9KCQ8+k{B(aPleVz{o+O0W`Z zo5Ouoxr_0Lxff%0e;}O&;Xa6VD~k2g-ALgFaG7jqV0KoHi3=%p(p#b$rk)w3E=DU- zsht;?K^F(bPK-N*tWH@b6E~d*`yBT|7#>;;bMO2e+;iov@PD@bUmEY9aIaT9|5dQV z7CXRqFa5S$I?@2UKofL0ZlWLDnIrWRMlDb7S<VXvx1nq8@W^}D`ywc6eZxM}q!9=_ zN}(INdAGvV_3>sM#O)%mU51RNK>(;SjXh!rSju6PRwE~`PUCJ)%2J1r0Jj)rbZZ#y zC9*LG;KnO;^;TQiU89VsuNT?9qT_(j*?xdB1JGM{&(HPT>Cj#1c`x1pmp;A_ZanL9 zSoXxz@V~PC|I~2#bcAsUg+G4$r{HTB{0A&uxuoomI@Do@rV{?MW`}Vb1&~HNcSG!Q z1Rz3i0-ftBr!vw$U{qER>E5W@hKz6&0ae#%rADbJjHKgQrtBMu%0?~a%HTdR7aTb^ zxXcoIHe$Htre-WPqT8L^7)ynVm4n!QXrVe5`8S;hQaU+>ZV-%BH<d`mkevfC0~e+d z+J?cYaQm#8@~7Nyi`}+_onNvmU~fIly7CryV8&hWSKIzf<Ne<>+|l&)W&6AeHlFk> z`1y_Jc0fdn{=;ba2MiB7*I}2Dj-vN=O$R}{NZPfp3K+XvbSk}c!D(GD5QT(TS%i5q zt$jEz!g|$6t$ZwVH1y43sL@amRAU8KWrs@h3-bE)Y&6yZhJav}Y9}h0Efvd`xp4>r z*X?s>Vf!03E>#g~nvt3%Z51T;dZ1jVtud?QDntj9kQmj4l=xfkqjg#N)C!pMn@4Ez zqf2q~9i9s>d*?A}Zwu>Iu7S1b^Jj1W7sl%j`wyIkqv(xqk1t*T#~%24nDyvyaqarG z7K(~Pu8=}>T!n9j)6rqoS^cYhk7z3CWojMu+74AW`|4bW(TLH(5ySoL-m#APd&=8b z0eWGDu$}K4q|3D7WL4#TVp%~@%z{DX>=iFc&st1o$5z|Q*xlnr+6!2DUy*?FW=3ua zG7CzYyAJ0^V~#W#F(d>0KIM`s=5|Aa&h^M`RC%&fka8@Mh$RNc2r5tkGzR7&_f3~R z_l3`coe$j=Ry@5B?!Npcc;vVD!=JSM8OHl38}1)G<&Q0o&wJ@UhZPk5#f?9SbhM(T z(1|s%PTY=q&(Y9wL;E)b*HX*s-t{d;jmhJ&QP06(WR=o&8nr>*j~#m5ZPW%hem4e@ z`!wZ1<8iP6Ef#vIA!~z1rR|=L&{(@h>Kd|z)qbs$Yf{B5s@PYIo6WKb2Fk_{ZZ?Q+ zYhEt^&1z!^a^2{I_aSB12u`=8Du(=^^xiwsO9=aNxsx}W0xvple;61;aL;wOz#W&} z2!C+<-!$I8n&FN-C&$7cKJHXF^TIP=>8d3ofCb%~*YPHRh9j}y4H|y8T&)m|k|5iF zW7rVL@wHGHh&hH%s~Lu*VWS1%8}c;W3T&uxU0xq<T=d<jXDLU9aR6f0S*mQw*hryV zfH~RIl9?McW@L>6u2E}Luh8i)sL_+p2q0VC*JzB(Ad~}^QTD%p@fxxOoR-lvDpb@q z+jqT3sBdnT8ZnpC0PA3*;dG~t4eWO4Zm`8Jo59ffRq(4H{1TQt{uGSZ{vR6epKG{r zd&xeB!xqol2F|_qzy1(nTK|l^Lv4JaZlj@~L}|7DZ^&@r85+<9%;*e8W5@Y#Fa7=u z0E~u`5O3D0b>;nOlpsE$bEom>C5EpcHm!)u&;!a7vFrn6Qe9O=B1?=P3<)h8_mgp3 zHaDTH05PMjB{rd2!D)zbH)1$!l;Q-vqGeY=Ux@K78yR|(D+n#ELUuY#n@OCLIH4;3 zHZlPi90*!R$|kWBhX+s3eHtFQ{ZU%GtdEDDcoZD)n(5`*1rN?KQU0mhA7#9V&sa7h z{sH5~@Y(S7`Ll4z0yyl2uZ8(f&xIu`o;HzbJya>1?C8MRj`yXtC_6|MW#zFkG9v8* z;FB87jet9HNjHXi_`s*=lqx<muh7+cKm8qTEbl8xtZ;IKb@g6a@d{DpQyFM%qh5zK za?9@uVf9=9a03L;#x)?+x;hU8sj<2-q9d5}0y*`J_lQ17ixGn*uV<XhVb?LjiPu0e zKDl+3V1UqP#q~(_Oj*5}80$vH5oDJtNK`KuHK{N3f1+$LNSU`)OIIaBei#?rzX&$l zb{jhCy~p9WjmE=@#mivL%GL14Y^rR}e9~Xba5sEy_xj=fFbwntVejW1fOkE7tDI^E zNMcm1giUdTB(^8rZ}m1E&VRK()py&y^<1?F480Z*GuByrIN9HF5`R~Rp@xlGD@)f} zxq?GH4s24`00piCbsBvZRhK?!rAHAzsle2gA$vqu-O>n85|JmBtTVX$#{C%9ac<jE zG}_Px9|s0Q#fI<UzQ>G_MrNh0UZG831|^01z2nRs_0?*=qh9A$r`c;`1$r;*WQ*bQ zPjeh$W|(+6PXxwV7c>Xjc8_gg+DrDpHLDiGZI@mT58iPPY-szVQTG`S{~^Qu6R!*V zb1Zz)QJ;j1Zu%k2S@@tCN>GmcZv-d%O(Q2_#4U!RU0Y!F(J)QQG2`tPAo{I8t@EE@ zC<(Eim=Y`Eg+k56p<|r!d-ptghAej8RJmfZ$<9&3GKEwl_J(KLLqT|IAW;S`bTf`p zZmCbxI9168o@uTo%upsy1ilc)Zz;Is@*5SIy`d!MSM?*Pr$?&61?mLoQ#Pe`VH4DE z+@nCZzjX3T@bF<=N_~gq145YK2wsF;vL{nEn~M7#@qBppHXFlD7hY8i`RT_O`91#_ z)P2Uof4bp5<24&Nw)YMPz+TTg0DgG&S4Evn{u0WCh;0;L>fUp-TuvuJs|_$mfS!~p z8a7H9Re7OcD>t(}DX?pE`q!*F-Z&PD5mCd%-SaE&Fbax8Fg82HY92GLjY$W1CRI>e zp4Qk}(#Da@q*UF9?-d%W=WABDGgAu8X$UfT8R3|)Xa2&K(=lF?gBoSFr6x?|;5rzL z>P^A8hm}i8Mr1}7i7|SgVSrz`F0zIWTL3d~ha#<eV+{*Vm-c??Ua;eSJK(Z36m`jW z&xOU0KMBvcJ%geBRSox<?&IDUPJG1&VaBY>VD6#^qeJC0a+kE#y+k4F-}(C}*=2zs z&bP+ndOm=+svI{RH_{2ABStuosvNA7&?UcO-~c0MVr>9PN6m<B;JQFpwPI0;8#^07 zLq4ITYD=nsN+VN^i7gjnCkf&hY7>No1hU8hg*r0FH08E2W)Wi;Izo+WDaeftQEviK z!77RlZU|;ws#tD#CX3*3I_PRXNy;a`v=ppEXXxIG>)8Y+XqR9|5j5Uw^cU21vii`} zXHS7ckDrd~*DZ(pZn+a?Ui>Q<vEiR+gj$V1_L>cq-z_5`=(d~f1V<k57Wno>r^OT4 znviXn{CZK}k~@s^=R2FKbQkEjYrA0AF=j(#`C*O~0s>d%2nxeUd(?Is{KF{58I%%6 zE1+xCmEm?OCA%=_8wR17^@;&uJVC2La<7OoHY5`$I`Oa+1;as00->UKrj7AD6z4)3 z6U$#YS20tJHyUgew>qkV)!Bg2r=N^IK?J}lxi~n}s%ZGp*~zh>%zhUPwF%1YU4qq0 zt6<C_p~5v8J7FB``l4N6+95l`qIvV-!teYDo?5W*&oJJ<%y37g@uRgZZEt+}hv31- z?uOeRyw)9J$+r;a6{v-g^Y3k=@I{SHjnMC#6^>{W-KRRHR-XzTmKx3(h3$5c-xNvv zj{MpU&*>Zmi7QwS4aQNB7*v@e3g)U$eEHru@t7CDk}v+8h8HdqAvNku*f>L;jO!mA z492>ML|K0I9AvEhK{4KHhJ?{;@Xi`>Pm9f6z#*=TNF3P}Y78H%Nm{EQA!~xQF)ZS! z>i}^zR8=48W~sZ?3qySg(UEy%dx#o!Y_cH4SBJ50*nZk}u+K~PPUWw`tA27J{O&h* zL)`up<Ne<-Ts^kg##_S)FZ&35_o7o_?a-Rq@uoI4Ijut3fZKXFG%}#dh}1@bhX7k* z3h9X*HPlXpNW8cF((^}WyLwVpW-;`}@*O4Tl82E#<Lz~iufP4|iuR#0(^29Btc9rt z<%u6foXM|$2~K_6tDv{>Bp83dPS}5PIrQf*Df&e)Vksa5V~qwDEn4msV#%POwbHV& z25Uz*PrII^EObfY2tz^)1}-wxYGp$(Ba2~y)Kb3K`RMixl9@NemNTrzX8ZEj#9(y- ztm~vQ0*FLG9aXmj#ds+SUGK3h_0|2iJ%9`6EQTHT+!K!fz?&18^~*5Snw6`d-a=o* zy@(?Xuj7zZ&ZAQ04H>T-%llWaT>%rvO@U`m-3I1A^^hT$Ii}t~s1DZs>)(S2tRKzw zyS@btLQh>{9MRDBVC=8R#wrl>7|1KdbuSa*(G0>kIbubJ>x`J6LmT4n(epIfy#=RZ zN;+XIO?~(4aQyzeq+KbK&?Fkuqw;<ExietpPi6uLQUE|@pHWa$$CQEPL}kI)v1SC0 zGT=%~?s46??0O0=gS=DCIEq7P1l8q+#8U1cZxuJ7(_IVYJ+?<fZ}%Z0+t5!K`v}eX z5Sep|{e&1CBRiP{B(05+ihN0x5WsT`*5^Vz&|M1b_M%<k#YY_o^B;ZyuK4jU;nDkl z4=@^P!Ul}4dk#GFIf1&2V$A+~?BIBK`_Z3+A71qZSdoUwRNCATJuap#`e%c0bwq0C zgUobeAvV1P+%48jTO||YT+)7zF|wWO@viOnU;3pef$BJVFQ=`g4XlN%D^VG1b>irh z+3A}za?Tu2dFOFB;n01G!4{BdY9n5A+k>$5tCs<-T5pAGIX>rkWF}gh%Svy{^T2#t z*T{>Ji2fTP^=UF#p@E~Fwoj*UN@4LnRxgjG(T1$l_{d{dH(Y=&f3t*|sw>Hmk2()4 zL#rstsr3Sg@w2%mFh>^{Kyhq3tcB<-1KhjlGUW=D(NK~$e)d#+`5Rsey}=f4z3Ljc z_QESnS4PpX4IAbLj|0?Qj&*wgBD$47&)@mw@Z2r-f?r(!6)PlT2jxC#WQdabDN)*5 z4czgP#hf5UmyB18qYchn`lmKhFvCSK8ePS@6!9<4(bm};X!4i&02my+>tH94k0?7L zkd8O(p2LQQ(pGO*K51anjbXDde*z47i}B_##J^`l?mxK%o;u|`=r3AsP5@*4l7E+^ zRVO1D6baOT{DfenULJ-_G?>y;XWW@@pvD&rH7bq`Ck5jWeZji^;g8ZT?KNu*232<E zq2OuBCp0UJ6IVp$K2glj83Vg1?ST;qvMRwAZ3VDulTCTGni?&@!f^I`$v&{_^LKze z6m|ZYXThQcPXKh<6z&W4j?oO)k9CdI<sN0{vi-XwJ_}d<=4@E-<O4j9yk+u<y|G19 zZI%QZunt`~8Y)N?&)XvQ3i?7uV04YFs;T2FRlEyqn6ksbNRF|-X+l<HS%yx*=P^)V zXI9Bkg6VFCxe})C>;46ZSvYjZErRSN10LA)S*46I+iw9Iz4`EBu!Q}B#)`=8nl<p` zNB@V~MJv?NgnLv=4lCu1@>65w{xm5=y>w6!%Zv<y)`xfju~Hi86U}0GjikD#r<=O< zqCkZLcdF4e+=q>hQC;g~^46$}!o5`%dV4z_LYh#943z~LD!LTHgXC5r_aKoc*nIGC z6PMRk&)otJIr<=&xKRVwBt*XE!pmd*YUBL_hU>CLvzbvGxEZm^b*pFZ46k^>Tj3{H ze;(Ekua!{?N{OHW8Xo9z$5Wq^tQhXaN#?XWp>DsQ!<iCZv_nIjU?nzst6``=8J)H< z;u@7r&ed;-ED3c7*H<P?GzI)sKVbugN&q8dIRb(8TDzg-wyY+M{nXp!S-8=wUj^*o z36}rzYM5~7^I@aczC_SCo!Ap(PRF1A%uit5?0H&`zyLyQmVO<2=ppHIa5=JU*>d>W z*U!`{TB_&$?|(N<oie%nnmczMoO8~3><LFsldKfL%2D((k8UhdgjjYP>O1<CJ=Ktq ziPF_v>KgD)m0uJ<EG-zi3~d3_j)lwaCLJMu4~_+7eFtDvd<eBtCu4>JDwANqVS)tO zwB3Th=)x<1p0(M=u;a8HVBbUbfUAD?OStDZzlBBfp9t~}Rj7Vor(ReabJuV?W$AXr zf$xE*mOciz-+yVc$Yit$+j@x(w>SVekm}wJm2N3uhdKcxpOr(PK^h(&PQG*i+J4J1 zZND$R6ckR?i~DGe<RYk==s}TA*OZPgK(<*Ow?>^)Yl@a{pKq|ixzM!XSynY|4cECb zW8KkdoBWnH!GwcfC}^8dcFAIR>N8)1jb8IIm~i<15(|@1>2&<*rLgcl-*FEF^*A%% zuYpre{sf$Q>L<%R=FFK3yX?BJotBTEeDXi0b3Sf$J^qBZ!bKSY(9l=V%)vfrjJ6*m zeeR$w1uZkip-<%DBaN5Fy{#)^WVg~$-GNGN#a00zgaxd#-6e>8j`xdOn>tnq&X<c~ zxvGUWVTG2qL;YCZ+4$JK)Y1br796T9-C5Lk)RJkZY0twKy<|UFwPF$c>VnH))^F|% zGBUwc-?3}Bo&7;qpu6SW8%@|0jy>d~aN&&qfK_XkP@=+xSPb@hFiec5*bbZaBF`Tx zh?g_g{cPZaW1&CPW+P@VC?9pK>de*M8G+UWuOTfPam8L+Dzh50FiRMUGJC72dS?CE zs<Wdh22IUKc}2&q_p2UlsmC1u&3Gk5P<k0k9=HGgFg|^tpK+s?Tv{4~+xS^9_5E*w zWk0->*4;ZN`|KpV>=dyaC#qKT7@{F>rof~073kRUA%`4P8Sm%+^$fb`qRUOU9l{ic zn52ZZN+!8DEeh?@b0Qb#$~BG20_{KWPUd@&BsN%Z$V|<`BTYgvb>(_E6mqE4wn_uc zXbmb|i)nN;lA<Uy5wK3KfTNrCK?qq$o2!i?fra2~N`r{%Vg>E-q1g|^kG_6B%(#3u zy!tJF2VXw>d+^G?IT9vL-UtA(M%`$<g+VsLBpXNI@|Rbysq=`Rd~D^~B{1vZYvHB) zy-gLV^uqx535QcXhcOu^($Eml`t(`1jxc{uA86O-Mx<e<ei`Q^6wjKo(K)Hr@LytT zUg}h+rnXmC)`5g6IiuYq$I%Q7l=E})Fkj1`WF<`*_AN#9n(Xis-7kNWrSy2jV*r#3 zR{Xo3%pt!~zSo(uDt2Z^T_#9?K~(ATNrxSk;)g~|rWHPqFlMLc!Q>N;#${jq32gE& z?}6TClS^4`N@6Yh&SiW(scHC=I&}7xsY=*H%V4|hwt??{=WDkAqKhtr&wcLn7+n_k zw%1;J;9h%96Qct)H=H}~F}PvI%>h+`jy~!zoH}(%DR0*7`*7~u$Ka@=US%k`eAx<` zo%YX}J74Qkgf%%S<-rH<4~fQ?x-DC}0xrGmYJBmFUqst(vsLNhx$_p_%$c{bO!bKy znoxIJkw*cM8m6q?H(7Mh+N?M9n`DvA^;qUz>6LgaJ(XqB=suy|Vx4LswuD0D8suzV zC9r=t&ZieGNrwE>teCL>OZS75zx--=`pNn5!*Bi<Jh9+$)k;%*kVl`H(^6Bad>6QG z7#m=noBhbOu+ugN!p`aQz}%V1<_1zsoYM?ED%6KC38PVFQuY^9$DtPU#1AQ3n3GS; z<V<#JtOzx56?EWcGi<On=g_eyE0S9(X&~gG!}6eq0?Wmzm!{@_TVa<2MAbMwbiM<P zGV4mu8O2-6E=?XV7oG6J1EDwd*=a|g<Nb0p8#A-_2`_(fqRY!*@fUtTn|}7)*k8N^ zmVD(rYM)wOCXDFNk!xUTX4|S~9SJYut<OL2tYpO7mR*@z|KrC`0fq>l-F5k8Kf~z> zr8l(ANd|h*ix0ybTjzVd?|pv{ha7xhIrhUJ{S@}vb9dM?ed67VQ6KZB6l)hF#%;IV z8ZN%@9LRs;d6!&zb@_YLk*_E_e*EKKz>PC+1@ydxLxgQ?zo;V4LT23o<$a_}5Jw6I z<V@4?EY==7L&C;koa1A^VF=;4AT@rHacIk_srM*)#{Cod40ITuN6#fGeA6|zm(Qlp z*#zG6Pba6IS_d<(z80>!;L;pan*l38vl}*!V<pBm3fdV`XK~&<`={{o7rq-Fef%yM zN(rq5vM_GKIK*|skYik8MO9HG`|4poeKNwP?3HFO#Qt>fqTzt2;W|0v66Zo}nI*hN ziLoUa-j=8_U0U37zl2{sC7}67Hd!{_B62M9Y9Xvr!w~}RpmGQ244oYao#T_Car$>? z{ygZfT$7BqDKt6LW2MRZ+35JAU|^dq;px-91B?IlENGuvW~qBNTu>gXhD@=usx9rz zw0W<+_AEb_CgVHo@YfV$l&P6z8rsoEAMuRFo44(f(Y^1z?})9oZzsO#xUTV*EgNb+ zCUvIwzUOV!G2XIe!&T#rMU$B#$S@<QA)^MD<iI$hZian0@}OM@V(3sm&&-*Z=^tuX zWJ{BkH9G;Sx<SJd4EWCv3`I%CC_S(%oRSNIW>h}wtLMRa|8*s7_MDyIE9ZP4-uH<Q z!{%FWRf=hncK7n9(9MKiDMOsNX!`WPsA>j@{JVS_9d<1LJ-+xsc<8ZPVBejOE*0nv z3?}vDnP-E8gQ=K-93L0sDYKpi5;g9P$wr2C7qJ@=nMv%LsIlBLKA{7oo`r6wzsV^S zx;@Zi+MHwTbeysSDJWc6PnqZmIo+10P4@C>kPWw=i!%g<4Q<#Npbn^Pe|d2{g$8l2 z^tRX*Ccp0Ou=3~Mhm{xn6ehp%Z!;ax$H?$^o?Zf(R!{l6<8aBB{|o5Jr7R5qeJg@2 z`!i32syF%iSpQ6Kue$O=m_Gf*w(lQ5esV(KdE5lB)O$MTKszUArO)}{xmNu{4n7D@ z{?tdx_q~dd;)rNFBXIgyvf@4Oc^e#^=`?_#EmP8Id+ci0eCm{cg;}%iV}Yj68{ha^ zc;gALQ4!Y`sq~M@r>31r#Sqw1$Y6Ia_I`x!u}EO3o4jn$kXQVNLmc?Z^<tPU1xP2K zHU==dgVjPp_+^R~Z<GFCy=rYj<U3&IwZEmE_u3KP|M5@3s+B3}b?N0W`}R9a&Lok} zga_!?V(?Ni2G;DaaMwE@xCD-!ehSQcayBkp@({pKOTF>q6XFc#Nm;11FX6+$*z{+R zpx<X<G)?qjV7U$%t7UH}=o0|4*h?-idFEcmzmg7ONN)S$0@^~V63|MkG6PKroQq~J zM;Qx~2^T_N$Gd8jqj+!2RJyD+aV7Ct=&kYlPRB_{zA5qNaWMJB_ra3yok6Rvyc8$C z>PRRtaQ2Wb8!<2JO1s95hbixU6D;}i_o4sP63f7fvRHD-s52iIu;*>clqr?*-gVb( zIOpthi?uh%ai8W1^SQdsNkdE5-*A%|#kSjSW5@Q~YY%OAlu4n;H{N&)YEQl?p{{P8 zu7ZTVTiJ!lcxgtuMms&lz*U(FYQY$t9M?8!j0cU&Vg&JUraB*=oh2r04xnOSRXYXG z3sgJU=&96ph90G8L0BC>c2{7hfzers28;SMF+~Xa6c#LrmHY2~6dt&L4m@XzXVHtM z9}e$$@B8ucUt9op-gXx(czj`3X9Z3W?4d0!=U)^JhWqPa=G|w*L3{ljTsHGdFx;-k zF@xh%rg?47@|L=nf08rH2HXs{*iTl31rG_qIiTkoN+TMUT4Xz5PE>L_O|kV}8a8cv zV)O0>$|OY|&Ps`~;+|BP`B%QaP-@V5S(cm%$^jP8y0Ub?TaSvHDW3_`Uk4i<`!2vS zlS<aPnY<Zn{Em;|nj5Zx)#;OJToPK;$MQX&Lqer{8*c(r-}5GDCX822B$EzWY=_bD zJkz%K-qX?;@H>ICEGk51q}v4}&0C|>)L?W)80~&cL)GEMK+nB?H}-A(q3|OLL%*d; z*A2+m`2tuh>s@9}v;ssT3&`RPMY)tXRRJ#6$M}ahCCOY-6pmb^veou0Ehy)<5InKh zt(+$;OL7xbl~w#w!#Por!IH&G;rh#Gz&HQxEZTIlo#E4`e+fSMFDJuJyY8BfC;Hor zNrsW=Zf{%~+Z_v;`t~v{MWL`MciT(n<nx|f@+iz-bT90^)3Gp!V_={^7RL3az@*;B zIH8$L<9i#y_%Ty(%)sPiwu$N{%<JWQq%u+lIr)`=LWw~VWI3~3KD~6#;F$Dx3{&s) zo6jA{aL(VMm#KOoEX{!OV<{_Vvs1>KN0E4WZBGm~f6}QmkTcQ{JbXl6G3ux=+U=T^ z4h|GxaGPl`ZrV#=qodvf6AyVkk5iR--o2tf&6Ld&62BK#UiecQdg!4N1LxtSV#LHT zF-ct9+j7ek6CdfLvexAo90vLGtH8HRmGe08_1F9JkMlV2UW}sJSOFlvj&DNdAG=#c z_aKS`x@(rJYeu6oEnlD$Y{S6-J}P^^5m8yY%AO3}(Zo5=obL#1DD<b`Lj+i(Hx`+6 zuQeZTl$}`-n1eE^L9xbCBPuh70E0j{dv2i&K%}_U^R7Y1l-Y8TW5^P+C0*|&QyjpX zue}RS|I82I*H_#FZ+q8!;nSZ#4UT;EQR$p<$tcD_Z*T$(<iEXa$YYD)_KHC#V=bSt zaNomM!`7Sa16ypo2Mi_y-e~aIG-1ppG`^XdjCcx+O~yNx1|@DC<j+7d&StPo>PVkt zcVd*i^gWFer{gI=9fLSHCOMJ8WO2!W%O~$2B+AFL6G*y0IFNLHFf;U?B<gz17xU5L zG<fY)J~t074J7CuC`m4)fvAApI7m8CrxTiPh0ZOf_cnblO*#H^yig-CbEYb}6mh#H zq1T7O?RQNEegZBz>rC3@gP+3YSsO!fD{Wl2%R@}#4%iR+PcOyQms~@Ug><yNSU`=7 zRE+qfcYOeEx#^k`6HiT4`MmS~2M##kWw31d%A!O0%H_+Jh3haB3nS^6Yv%~_)@M3b z$281<GCM5M^~s{c&{@J*)j;Vd$GPC1%l}9Wpa!WvN3DsvlQm$(Eo24{fK1;*UCySB z$WxM1e}RSFDO$@@3{jaJDq=^^j^=ncc>!YeRPq=pz{`qAO6|m6Ngtp9RtE-NC`lZF zUDRb=$uN2_*yIU&k`M(>3O)7ID)`=+7niC`f5|@hZ(lnMmM(b;&icW5@Z=MTUiZf& z%}W2_dXR;L<~VW~cgKA{gBR@fM!4m-KS%~O9*1dNva`W-B(;0oSXkd*K}|chWTA5@ zL~C=@3M|joC$lt+s+4DDVvl`pV!L^QVZUT<`%sW7j{_xRZ+fXd>D&PrrhbytP@X4| zLAV{JY_LrkGwGK?QX@)2s|+H^<A$5jk;N4_QY)wk5U^jEv>9x4^vPHzUg!jjz8GZ| zaQTjwZ63G(%Ts)O5H9`BSAf>6t1{7CM(PmBQcpPQWib9_2MM%cL<!3sjI4RtP1%Tf z*oe1GmrwrG#{-i@SenLSy<q~%K0ISv9zt>h7_kv_oSO)aE1JX`u8-&8C<T>$`rK(Y zWK@Yqj;kSrXT3DmupBQ{VUJf!PA<UBQ$8_3EvJe55S?Zo)<7L<mZ?@o@|6z62BP^J zeztNG;%+`4&3GY1?kGiy+t6R6x5-&u$vpRv^((1<b}-2(dzoY=6BvXU*WX8He)S5t z^Uf#X10Vb#eD;f{!1R|MTxjfIig7a{52nvRqSyQx2TNBkfJI9mgq^m3Ss6kaH(_HK z7(1TQ2gZ$^RE%xRm~`!!UINvG{e$BYh$bW-9OS<VZJUI&n2@zMc3g?2$ECP=%)od) zHaLKT>3Bx`fy@pHgGjY*2VrdbZ?GAQnH6CAK$Flt5qhKq%Wc|6iGrt355|^#y*%xc z#aNP9+@)ciuOhCZawqn40+#kqIr7ucOxmIhWEDY|RTNMLvptTN*L)IZpeG)20`#Al zPs{%2+c@=IAL9L>@m*`@=WWt)N5Jr7Pr%Rvk1{}rpSM{9fL&x3)ybLVb7Ai^l$2xO zyuJVZC&AsbW|xd}-j)Ug-fORE@a7YbH?2A3-~;T~(qe%1Sa`S{a)NAhUy}DOTei}E zA9>U((%AIYp!J`&=dM*@MF#PCxFhap3@Pr2QzNXd=!PD06nafaAdw;wIDNLL3PDfw zNrEAvDd!T$#)atdlTJ954ZJ2i?Q40!Q;IMeZBvJfk-IfxFzS+p<z!TLZDod1%KYTP zl@b}s?547Ar^J?diC_<Y_uxW!G|}TNHk|~!?7lC&Atf0vz2GvK{o8wB;ljlw9?mx? z{xaR;;YByYL3_Rn7O#B_R<B=@scur&vB@Zt$+Rh+9!#-wJDi%4K8aCK!RO&T*Am+P za9LWMn>R2xmIlW4aDCc8m;k9ioX*Nqxu8$k7Y^i;GScSZpnU&?sEJrmj(QV%bNVF5 z)$LF^o)LREXRRSSR?bgnV%<-rv^W43a_JwVkkmP*zx7EOG=9G~CmOtCDwhq=S*Gh2 z8)qwtH_klwmo9>SqBs4ei(%zOKZi-jyjBce9(7vgnKY)oQ{Vk2Sp4~KW=d_UiWd7R zXm&OkD*fEQo`J_4b3~bymABLX?XxA@Ja^7Ky7=PD@%`^Rsq8=I=)=lqwC#sKJRhJ+ z496B4QyGn3mwh+Ryd{knv!TA{U2laAZHPvz5p5=YIpVY%Y@U0JkI|^P=8)v@NODl6 zriv05xs#Z3DS99&>5%)vGVQ7_GrmHjH6jq4RyC2(o~x5$zD&O%Q9>e@p(S4AD$x+I zjGZ-BXM}N*h$lFdHxlG!2$`k=Admg>g7PxiA{%g7tdJv$Cl{}UC$4{he*LRi_<|Sg z1Rwd-QDvsrHNU<IX5IZz4jF8m`2L00z%IKT1^3Up3<ieQl~ADVuTP1rfs(b(YZsCM zCzW4={XDla8Cly7<v<}XR7${^>M(v>o==tP(1)Qild8m)m@dkv(Qq>Uyl97$&;8V% z;o_Bg+4&9iWTshPh{}4&mb7`|W!lr{oKluc9t-X!s9Y~<qz%7|K*#R!S{%P`QpP+z zlAJy(T}GkQ<yb!)ONp!1*It~Bw<y_~8-ER}uf8l$Z#g$-ru)L?5_OsSp||HDDXc0h zbHO_#5hBbiODOx!cm0DM&9UftKly$+CmAw*{TttfXWDL<adR2(1%13uI3`ZcA!RiC zPXB-F%>O2tmGz7pg_aQbB5?392A$d#H*G_B8+K(ZDfht;jEID{W1*laHIiD?D?po9 z=%D$fXto$N1eNRthoa7bTQhcSPUIB$EcHdO459?o<iDY!0SGoFjceV=1ddcUUV>0E z)Evs?giuK;rLo%l>5VB<B%3lhA|;W^6%G9M_J`oB|M7FU`pSpkn7?@qobi>@;D}>h z0pq4@0uwjc8rrb{t6(YYxa$$H`S#Obvu$^S$(wBtlhd(D8*c#<(s_fErsCkZNzfZV zIr*mv*o>W&5H!)|F+zn?A!7z6!kCmmOT$m8ib)2EN+<qZ5H@F;EhC<sWg^!lOP&*R zP03KF`sO-k#{z@-lX(X*Gv#YiUzNX_2qYT0_IETyF)Ft4n=S+#KN0+qIKZok^6wrm z&R=zX8qa<5QAz(Z7i-t8#{R;&YGsDzlVAU49J}BC<@(}CrL3}6SQh)Qf9Mfd_LU!q zzxTw~_S<ilr%aapi5AnWyYJDIt64)C8%BqxyYIe-5;ZP$*m&wx+;gwpSrLQ|=9A{l zo1YS5k5x=$+O*wa<EfL2kg`$Eo%<Lmj_kST?v|`7*Up`<^OOsn+;iHlwxm%l;$83j zTR8H_mzUo^{>d*>%yx1mZw%+k4*zYfVN2wCSR>t&xwQpm&LM3|2_@AYEYw$LL-Mq} ze7u$JCYk$OQcKRn{DsI$eJLwpk$cXDr<il>HapPpishMcu{RE*Sv{0VJgDX?6La() z$O_xfS=^MN?TzcfM&l7C<xK4QF|cO!AgqHy8ZNV*1`B;And#IfPMYG?6g4J#3S($! zXng|9)tDb1lxH+$LrL)~<c#ql)2Go+J8o7e@uk;32<!SA!`9pF4bR$q7}g~eUNmPZ zEPZMrtXQ@XR;_vp)~#8bDDj%~cNq*1Csa=7^oNJ@N+l|*g~v{SvEwJwa7vi1Pjq*9 zeL~oE!wJyR-vr?ax=R9V%rL=(^mpR;^+4kQRwk8SzADvyZOTlqOZ0nPN^nssp&3q1 zN=ThP*|wSiwy}QGCtJ)ADYN$YXbCP0O$H}(wz=dXP@iPL8QJu8^)2VZ(C=@9@dq5w zPMU}Firoz_nuBX^yAsrR^WPPTO7}M31_rj;syrOc%ktS;gU@?zN`mc+>u$LVg2I-0 z&X1;#hfnH=>=8D2!wvkLEorSz7by2mNhX?c!_CagMPn_;i)Io<*YZLIg$}8|!O*N( z_nL$Ad$DJnGI^sE3$MTu4|i=ZZZ34fDi9PS;Tu#~?FMRfwToi^Nv?`A&Cw)?7eW<) z3!-`sO*3Q|79msZBf`yXR>`JQC*q<tYd{v>p~%I?tThG3ex=doNc$m(09n`2(3)wp zt-RM{S5vaT8NEu#)}W-Y8y!&<I2Q#-b(wk7gLvDWkHK@ccs9K5r~}~Hn@)yB{T}SF z^#mACYvAX%Oo9i0i^&F8!20zAuzp>ygoe4O?BepA<V2&Bs`g7YcwJGi3@`DVr9ro> zBKX3?OFfE<N_B0q^~DRCw*Vz}zHT6MaOKI_N7^t_lz*6+1zjUnC7^y;lvpUT5h3A6 z>mR-q*4%n7OnT)9VC=4k7W9wLz8X7?CyKB8&DDA>;kq@j{G9K=)RR7lxbf6N=}3Zh zuW|C9X%HWPs<F>d`N|1tJ6cP}qCQv($+eSozNQ)_h+gSHGZ9tFsdsS&gy1|Zjs<(b z9r4u4>#zMKJkvJsu>}+mRy``a0XAE8DEbr-TeQHf_cclC9F_iRUy8Iic;$3Sl24u< z*id}MDM>SVY*t7Q*c@!~p)1?OT@kOO5<`9R$)(V)U+17Ns-<7T(h}my9^OoDKY3r4 zHS|ow+oFW|QLruAYZmfi8BfAv4)0jKN(^2W-<M&b@^q7QI0xQsN+I?0>`8=$i=KkB z&%YHm-+VLJWyj~hnx{91dmin>!p9$mrHfKxYxyEryLu@Mty>90>(?aIO~~0FE=kAI z?i}axiYdw<q|^TL^veuzC{~HekBHk<uI~FjSso%TNx2QUUoRO8$q9h>Fxi-({04Kr zK2l=g3F)wpPS|M5tg8O<Ct>x>@0ELI3f-<<13turHgRL(%T9!WZFd1jxHQtWbV)Me z?*Xk|=WBu`7A~EUmwG++gsLmZoFD=<MB?_5ccG%4VIArRT`K0Jf<ki1j*j808n}Xp z7ER$E<#*fqMG3j#eINLz4&3@SW9F^!lb`%Tt5=Gu@Hc$X`i?Z8E`Z9DodSahpe8$+ zF1INmlC!H+Ml1VlP1(0K0j>aC$W_I_3@&f2k6hsJie*Sc>rCukS^Ys^32Y1pDO4Fm z(+hA=c|ix)u4To{JIhM9{7JktFUaqwq*=-;wf&)FphLj)y`L=$Gg9{ZiSDLj!~M1S z@jA3V8Rgp5%V_nAMKJf#-@`T6-Jas*+u%99lyP3V4puIH1XeDc535!@na_juYga;l z{n|vI*Hd}4&Tw`RZDFEqioa?7dQ8V4dxmrqHs;JyGlee3EGPo4jr6qn;T~<yOy}b* zfdZpgJ+sl`u1vEBMEEvwBXkSaNX*?R{Zc#^lc@&ep+SWKt+@D;(5_s>wy|zCthwcU zm~hD7$(qfkoL;ilDH*ZRYyJV2{r9J#UG}u;!SLhrY30v;gp=R=4s)!?^Y~zR-s8|; zvlc8<N%5H_m7*GYF+)RfW>jbzS+>Z-27R($hi%w#X}df&mi!c`@E8zmyeTfSFBbRX zAO9S0yz$mpLBsHQ^A>=l3H13_2Ck;YGO{OqW2;a)K&U;%C$}2E`e`+*lF2tBKWl^? z4YtcyN%<g{Z*l;Ibr9!K9{QG*xNSiuaG2r+DT6R>;(3$xQKNR{@iiQkXFK6Z6a^8u z5;UxAj;Tk>dd5~iEGw$|@>@quhKo)Pw<*?4lsRR9ad3D{LfEzW&DnV8oln5Q@7M}{ zb8{N0P2jY6{n8ZoE>GyYHu;L-><Gk3^mE3sIEH+m!PP4$$KZ+WrrjyGFqA@;e#?s! zvg~Czt;|u&hMNxMr+Ww(W^bA&&LGp~?4;UK|6X*MrL}D}6U&TP4WSCC(DYt-sTi(s z^PG2BecLynU9nK+va;e0&z~*la$P`dzI54`l*yaASvKH!pM=DV*+CG=7$6Hgj|W%7 zHp(d^o+AlB5iK{0W-L%EZw%iM{a-5^Mud~4C|-lvK(uUTqHfp@oTLvPP~V4h=glYW z0EqOc@%qaG0diC|W*>_0Y|b}ht9YQ*M1|DpR*oQK6e^0$+pS$*OUok$mn+mEFdO9X zkj5eAeT0C6BW&Y7qa31;k*5-9W`<v4&CEtix~VN}L1u+P9^KHjk!^lbWIm(cP@hlW zViG!IM&S$$eeSt3IF_<n!^wCCn=!C9mx*hV!KI|pzyLh9U?B{Sc@Q?9bSNx->S0<j zyatEXt--d8C$+k~RhNBoK#<V5&3De@!YR~jhBNy1%Q(0ga9N0l!WPS}4Bpv~wrt=% zmwwTmqSC}8Or_5<enJao0M-dmBTvx9unaI|#5aAu%yQ#FN?4yL#ggCiVF|8^t&W*U zy-jy0%S=R32`suy2L9OZKxmyfh%}I~@g~WzH$m5*;;x`wvIN^DO95O9S+fuw6nFx` zC@Ln}5E5IJp_-0X2n<0!j2x)3q%W%X2gDn$>cU;=fyNa$95aQsx&=>Sa0w2(vQM5$ zskQXQ{nlg!M1Mt!mZbQH7)2zj!5V)6C*Mbn-n|*wq>my)QW(~U0TgxUmDM^>40Ax< ze2^8M;~R?J%VdD{D^yE4rDgenbE&<90}0w196Pq5iD@KeOq&uv>l<1(G=Rg|$(OOy zp6HT1wx-ume$d4LF=b7eVk((nkoscLtFl}#&t;~uW0Fm#5!^n<)`Mx-XX>O0aMDRf z!WaMb64-u=gW>*1zDmniuEBLFvz*aaVsr6cIRxgp&`_QTHJF`9e)<Fn{Y9pFdE#># zYDyyjgGoHSF)a)?Ev-rZWhiB<duxYbY|04@=5gqf$Ifei^YHfi;>a*(p$AeJkn%|b zIC8><GgGqwrFE)OiRwOir|Al5P{fLgRW>-K?uQr5Ch*u=J-OUBzM7L1fq|ASk-Eq= zPFAT-O{zwq!GO?92nDDD1NoByc_mCxd_A!|GPt#=X{bsrF?XP!!ZZ|qito_0yaE*} z(JT)~!+_>g)h*W5+FE_pf?HnH09Fb6OVo8hp}uP5=B`4MgJS|C%Gy5hNzmBZZ7>@o zvTMovi6j6A)C6bA*%GP3NPa@H__o*|G_hj}sIgDkmDyw-g-L90s8D8oM{}=)mpors z-`H4^Jej*uj_R@4P|I;}J|nYf@fc~)hT5@h3Rl-dFQMn~aKFeU=k8W49j1Z7aro5Y z8(_-B=fb8NAA#+fUzGdzTYIn_iX+QIyfVSHtoCJM(~@QX%5wNL_=U7C<#ve%hx?gc z=hJX7(Rf&&veGH)XwtA$LF3}%vgC)^HCcMG%#G%EBUK&ef6)yKM4q~qT+{wsIQK>M zH2<2bq13~WK}s2cIHoXSfatme@{AzGOSF+3Q*5ftN(^0-nvLLeg<{?~6h8%ql6rrH zXcS@ufH6{36F1-kyT9q7ux!~;+8{`SL8yA8dKe2L)qrTcI&vGjusTOCjeYA4LUudS zn`OdPxLqhL`Vpk+9CZj<qE6~8?U8s1*jurTTh%KBOH4o{|ISg&7fMD|B$t)AXj{v9 z9f@p9SGUBAFtVj{f~d>{#FB+Bv!)79Mb2I`FpWvZJDhE7-MW&9N>rPZNqII`vabaT zpMZl7*b6Sd@+{bC+vCzu()yI&c_N|zx(u#7>{)2Kj17@ACQG&@9c$7#t;G?QiJ(Q~ zJS8$89?n!d`Imt_D>I!lP#hjF<S%XR<xkEZ@#+X_^7FGK{>6}WHtmoXAd{^=!5V$Q zysb{Cu8@Lb6YW<o8%4_lJq%!k8jv%(@=PH{OO_F%SL<<MB!uAwYMlDgU`z6q9*eOp zp)0dFrl91`KEb|35s;K^mLg38gbqTI>TwGm8#o-R>RR0`CkBdUU@4=>p8+&mj=``s zvuSw^6%WOZVym$0NR~2zlvd`YOBY9);$2+tF&`xLEUvu_v9#)DRHo!r;25>^NNXHQ z3<5aEQe;M@tZab8NxAz4SCh7*Opr(hn<rAFj8QsmefdzzK2v`^mMM^Ve@bR0oXy`k zYn@6Mo3hO7vOc7Ya!E)H59I_E<;-=S@0{l`-#zPoc;WsBq|Ea&xP8`t!e*PjBGqLo zP98h9tQsoq$XV|c6X!Y6g<5C2K9t~eXo!+!mY6zOJLV^Glq_^fYL%p1aRU9ENY78= z=;vwU{qlUQlJ+%+m1WQerVf&IPi!Iw4W9|#+LxEH`Y;)3g40HXnBtKW!(%*Df8|AD z^740kl_#G9=nyX1U-in0Y-nR36o-97{Ae0rh=6vU#dT<~tw*GNdQZ^hfJz;0@&=k> zYDtXf7?2yVvK*~ww1Z%TdVR2Qb_q6V!9fo}<sZw@>&39tXw+`h91YJfT(0rAn=J6E zH0ctMxzKh~u};(*g2(Zomqgz=f*Gi91g#!mbOc!W1RwJf0;iPEI)OFPsJXi2mUtkH zc!U@vTUt<;QAh@zpjD}sMAq1R*%-_TsT_M2bZpBtJdHIk+|NUv!~HeMXg7g1YnH(y z58qQ}dTsyQ6Jg<kI}(LW4kBgRWnfQQie(ZZr<YsQFrsKhThclCr9Ju0TA(@cwqKIe zloMXPY{bL{Tb|k>GZC?;Prl1Dvij-jzAd7O3JAf7Sh5nKg+5h8CAC?yjtgOuBA6-{ zL`XBQ55hVs^oO8;_MBh7vAcfqDyrd1JgP{hCn~`dvZZmbP;sg!t7yH9^$`ST1@-MK zE$z~i3Wn{NHC38k9aH&WrQrdZL<mIIbcbM(061NbAg>NfWvwPgVhcdxGUO-vTyK|) zvU(@IsP$D?)p~OzOfvI_A`P?75?UpQFOxIcR@|}3iduaSQT|?rTyp%Gr)3bYS7oHn zR5lN$=9NN;E|&=$d2GATV$RqWHk<FBPaRkfIo=&!v#wm5(3j8c50{j1M*AUNc?1_; za5cQ?&2KE<AD(joEPDD5*k-%e!}>JDJQl~6%&|TXJb%g%Q_fOnI-a>P*A1A?x5i8g zAQ$6J*A2JDunWBeUIUEif5kZ^sr1W21}f=2h(;B9N+_c{enl2k?L@H%+t_=vomxM2 z3}5$DE*`qGdZ?2bXD%r9@mM#|wSeyE3a=Q4v5tBmtni7X6g$^Me2qTF+ymDO%#Qr1 zDYbfLJ0=dLWW{Ui2>lSuT#!#gV{fJ(18{o^Wyn)J#8#YoD}brxqUiw_$ueXyiTJfp z34eSxm1dX40hk~<UYRV3hvZ`8yYVtoF=)_v4<w#nlsXq&MsM<54IaAbvmq4zS*(Bu zQ$=Mm<<2io?eheSww0O^l_%Hq2Fg6;w#=<a4x!(dX}s)6^6xxzE0?fx#Y$MZbRF!p z^YhZZhvB}5z7IG!0XE<I$dq?N7~hNso_z)7Ud32SY+U*v*<*GJWiGUg7xnp`d|%2= zDZffD4}4*Mx_nAnrA$^5&2YBtRPRK|8~KaFW%_28ZcbvICMs&<m`!-=A2>}C4~~@* zt6O)MjD`RXqLyi9OKs3}222^%aIDZcIRo__AaYj%b@loT89RoWX_GoPR)S}zy<VXq z6xgSV1dLx|eBY4CLtT+prf6nUF%oH)VYyM{Zt$+BSH8?+daJMf1#^kIIA8PO?sP+0 z80(K1ZjL(SUdHQ3#?%-uMhyoPcPaD@b?Y5C2qS_#A=rzO`$!T5p&qukT9`)oBS*}U zv~gr1cwTd2>@2by;B`xor!b{ZwU-QdNDBk7d;vR-HZO{h8D4qJcYQi{?|pWHJ8ruj z@@$f2Ykm(qZu{nh(yL(E>bYr@Yg{tM_3X4YX=UAuI<J;wS|V_6UPw(D|4m7${AkL8 zx@kBmQRQZU4LN-<|D|3^#x?zt_Uf1HG*mOLY?3+g1Jx}}D4a^jn?xTG0j2LGV3u^Q zvO4q3XmUmj8iuNcu3QEJ7L$X)HtK~64#E}y4Z=WDOO_oYebR;VN;d)+F_vly1mcvU zZlENU00ZnQ1cA+e=3tIOS*o|{3S%`~$s;Eq&1|x)QPrC49DYW2pwZ%Quv2(+3XII5 z-xc90Fc&-Kf{#K&JuA#ilkminZxsaVWhD>Ez@$KJ&tTGI0C3`p1+N;HlQv~&rO@1d z8NwOPe~Y~cB_+)~=jHP)_gkx4D>I^cW#|a|WxX%AF+1Hnaics~F0XFN<3SBijLLeG zmoeUV??W(cpBKWEsZ)zYR;_ppW<B^Hu<cf_fe910f}y+szZpXscWZtDWL6rtp)Ij% zNx~)QZ_5<SewkTD<$>`Tb%)Zm$!Ro+(xZIR_cnhr`tn2G3qqD*r0Au!qvdS~rf7;b zj5FHf5Q0Z6FNP+0)4N!qDl9NE@z|VBrU-}vQDG<;n*tSSAd03RpyNaGO3aSNVhkbC zGz^?ZI1S}5;i(!1!%|li1qVkzBt<5OwGZw=9a5uK5VT(0ML>112fBF~5#5#G`1pLN zZ;=8JI9<{*tDovF)o%&2D7zZ%Ds7WbEWseV7(tQV1G-2b1pw$%Rs%u@;R&3V!UR^` zbvR9u7ao*WHsU9AR03S%%5Qg@JcxmyX@m5=H%P-dTTHEV2WPp<+>dldua_U0GX|P* z6L3s#00!hqAi0b&V+ZlMJ8TK}%$i*a92#Dc63we&mz~}TPd+&_#nda2%0fw=0$J+^ zfyFxFQ0!H534MD-<oRuhDLK`oYa4zEU|voOc`0FekG7`j@|-e$Ejd&ur|zFZYysUj zBFHBqcbVuZ(L}9lz>Hh<N&iRhbw*EhvX;FSlBtymV<6m}Bnc5v%q`;Q@vab5MTu$c z(D-TI*))yo7wD4`4UM8*kt>#-Z%HyVfz`UkoP&*nb&O(!tZ;1vgutCtC|g=7Uv(y& z_6E71AqwOH(HG5mr??a2MHUnima5(UJ6xy7)IijIQs{6&b5zE~zZF=~P})3)g~?LB z-_RCHkS&Uk<1Lq&XEqhordDTn2|~*Yx48m5{A6^PuPge|&r==K5D&-4{CWYNo|z|b z<Ovf)<&`eIUi!f5WRC07#d#LgFy4C0ov_b~ULYo)BGvWl;PHjOhI#X@hTV7nSUPtM zWE5=`^(+gX=UtZ=HticCSzN&jFVgRZ<KA?i;hbg0Vz|g-y(Q~h3|Ebp@)WzW@~OnY z-3}JR3;VeD1Oh-~*v97TRwioRTq&)CiKCsoB9kB(RZ+U8GZ~jLpRX-|*qBE*|6crY znDd9IO)v{p!z7BXNYSB&8h|Rfq;%f^NFoGuS`N;N4ct4BWIMFdqWIQU78i>Tfy_V* zo+{5|&I2LVJ=m7j145gFZ&H-)bhS7^uP%1(?X4sTj;6}3q1KBTvAnqf!6GrRbhWZL z(yY2BxWKFF*|rKP%w?%++35;Es2;Y+H7`WTuTN>qxUrN$Iza%$kP&#n9K!HGo_U#u znEGuttCS=LSeuew+ibfntW9IWk3Y5mbntrV@>wu`+?KG}vk!p9Pu?UfpygqnGO46E z7*?8s%&iQEF}2RGW5{>!^;$9B{P3(YY=mX_s65yL#E2Wr@o&F8nZstl$!cjpG-Goe zkd77nYc(2YgR>5|xQ$$m5F+xpq=8)Y%+<MrSnQ0Z`a&wB9iZ7zgFe{{<SE)1l1W*t zF%rmv{N_q>I7`;XoaktpiZ(J{Qm}jTR8WP$fyEg12t26+w7pRtYNLuY93*0>XrRvC zLEw~8^xyog-X&Oq%Nn%3sBD5yRg@$jsUsyps_%Z=;>X>$P!KAD*UvN3DjO8Zq4uSa z8w<(VYv^_I=vIMsjHp}^&9WR%;#^*Zr{}e7UY0OGo@9}i6Xy7{tR8CfK3=9c+~)Zh zkY_RG+*TS@f_3?`o?kDTk5T$u@{6nKh@+3-RaQFul)gXk(Dz`>xJ}aV((zcHT~!uf ztk1@Xc@jxks@d|A%@WU3eookMj(4#je^ZVTKQ^{s5IB$fmYA1aKp8mdmxWpU`rSr- zl)jA(i~<>wf}uvok1L`DNJH07H)%9&sa<{i%2V4gD2>27RYl8ig(xBDgaM@pB#MQG z{-&n#oZ?WNG6D7;K1yO<*+Br6>H+{!#{i)NNg&j@-pFPi>0l8l4q2iNb!nvD+5%1( z;RX=`V_+}WM$hF=2|CHy;xA>0hC+MEI!q3ck1?}{<mrdChYa;m-I41xsi?K!*>&oK z{kV52-^0d%sSZ7gV`<4YtA`G$<cnHCG|lhj?6LCtVmu|Q%o9C|&bR!W=482fMhBF& zyXBMU?AoFHD$)Eq{T<HxvK7PXl`C=MO`Zc2CQV=m06hINWBBdA{TJAL%a_7)wmc%8 zKU9tts!u$Qn`tzZSBaMolmY27RMan2IcJy)`sT+<@uQ83GUbF^nQ2*Gf10O&q=-2o za7kh*P@pQP*edIY(V?<6_M#c@IY$KHFT#-!ZHNb)_UbICiuWM;u#+DS#xFkt2Xu?l zx)MM&)Kd&xDK0@hhd1y@Q1fh>NH+mJ#elMyft)MbZFm6RotFrtGGPo(&hH4`5^z(s z18PvVU)gHoh63pK#p)hf%}Um&r+L22@)V`cjl47+u`1IXud+2F2=J?Y4|*To)p!;j zouDav>mVFe?FKI~$kW;+=OBbQ0m!w1HJD6k$}VmY7oeWmsJSp~9y>-|7dU`z$qwh1 zW*QAV>Dl7#WlLAWfrso1ciwh~)J>Z`oMPe`u-mR5NXf00ux7>YrE9gmg;5~NM<z?_ z15tqAY(`?x#W5i-oGc_e)v}kDFr+<$c^;NN87|U6REyML1ik+}x1@n#g-(_UK_O3M zp$maqaO9$<K#tBb<RpLuK!K)tD1=rm3-Sc>O_7QZ)5l_9mGVZYXsBo-$r=gm5?S@b z<Km(Wf)#p-Hq>;%w=Pa~jKaL7J1!6dQOq^!-GN_<reIfk1;WfRFp8~WsDG1k0%N4D zibZU}4NwXrGFltRza_?GzIWa)NE%VQ+zrETroI?uM#g%{B&6kp7>N;7(7Y`}OD%DE zJabFlP*(JSXGK}bLbZiy)Z#7YmPsEi4_z_J>JT1R=H9#Sr^El|SdiIKQcl0j;##xz ziG;+b!j{{=F`@MKc|R3n)rA)2BkP%S`V0m0$|I-po%*Hb`QKq`WpZdn-ekNvS4{)# zYp96`T%l?(Eby3E{j@BtL(5P@v}fr^UZvDDO_fCfLo|aqg&9|qdg-Bic#Km$3lyoL zJLs7UFtkQ+M<jEFk!nw3i7W~T->In618*^cQ3R|cr@qX~G(<p)ToLOGR1gP6uNZD- z$swtavKdkU#6XBt8mP|A_Qhvu*(q`&1o}Yo{HWm5D9)PmVOy*_*o0(q6ZJPI8~j@I zUv`dHKDa^*uH50+NDBHd1|-l7l{sk)_tAcg(zI>|Hkw}XLq0FNmGCOxVB*B_DL!5a z3l}^N;K4w#inZ&WPE`A0*nOYR!Qw^Nr7`Cf#NE`IC|PXD411!Ir9N$bh(~!ozD%FU zG%}~R_&M0T(72#)9>k6>6cB}RYb6cWNYV`6L8Qy^iuQPaIAanE;vTmSvc7P5Vg~Fu z?0r{N%LR|NPY{ahPy=4LrC#b8S5&>AST0!G#r-4r1PN)DI2J(bej<Gxu1;P7O{|7S ziyC229E%UDs<OB|oEbsI{jc~JxueK2)Yk5$L8I4+bSkBEF=@CdbpX=heV_T%?!*lV z+bgkah-<Jd9}Iyy5?ChDI0snLjF0unA1ua}6x*iV)9Tzy5Tq?=oU7LIGis!sEhDiY zD$j~0Fk*=c_r?sAY?Q8`PLE#t%U{!RZ+;`h2_!idZaJ=oMNi!d4?gfs*k#`@rsUSM zQKozXBX(Ylz%g!Hl5PCSsGD0nT=Hu9!6C_5+ww46fbyWn9)IU`#`a)$?H!XX>bNPO zn~)xt)fy^u*F~^pOkf^XkfSc&{(7PebYX!`1Q9J#eMg8K!Jt>Zqxl_HfAtgL3Q1s^ zlJc&21_a##L*F<)i``r2ttA;00e5ru%~?d1RYR|Y8i$&BT`>$sPGku@0E<(+)1n+S z9zqAFy0MZvz%U%+A_%{`^U`g1L}J?u>b$i*YP}Q;myF6vWmU0NEN#3572Bj?YAi?) z=VL>>7XY}9mR*{y7Nh6skyPeKw>+*KJes^iI2n6C(`jB;Or9(&Qz2>f>eaY@xPgfq zO>!zu<OZG2oICF#m_Ppt*yZ{E24lu<X7v}RP#V-q(w0|M@mdGM6onHfs`5J=+BQG5 zpee86EuzXnalgFKp*hWgRIw01zbjP^e7dNjf*2}k!}2Ob)fVXtR8@CMV?`i1SJU%( z{8i9G5V^s?Pn|-uK?g0ufTNAIBHmsUx>|DQhA&>-IB2}BHj3;%XuhiAv{W%{zddl< z!eWmQvWw;OVXd{%WtFrbxX=i!{Da9_*@1Bk2*!vJf>FlAr9F)wl7Eb@Xgh*Kt{hls zKL7SPbCuJ^P`*r0v;0!Lc@R9r>f5~n11fTHhppa+Dlh9^Tb-df0|I?SIJx2H8st1u zYrWHYwRAnYtg>3Yay7i@;C<oll+5bnKuna2pS}ZngA-w!9p8#e7hYRl)ndH{7`i<F zZ3MjXL4JW-d6aIEUq)Yf)R0(v6Pp5|cZ3@0ORq&RSpBVFh=dXmD6=7uF;)mMtzbG; z<(TV)h+yT43N<vlXgX2#nkXAe%&q&JAqb-vUMz;>LXSFN#jBBVZFuqtGu4>X&`K%X zR&$^Y?!`>aL?{M#;3BfyDf032Vq91x1ha}JE%RzP7TOidwKBxDl?!}m-#xHuwIY4+ z8)YlVRT-~FD9owFVe?AAwvBQo@Z2H>Dvye>B+wK%EST|wyBPpsE5cp`RZMO?wYNOx zv79H#DUu`>f<7>l@5<-M{AwN^;^$tqy!4MLxicra@9qa+*S+>hC_K@f0HZhPeDjR< zzkl!t@c84`!p<-JG7OB_sOX~RN=TMk0vjr@Z^#Mprc5lOJgbBnUY%8%)0U{AJlP{9 znN9=i7*sR>jPB2R&IUD#1#Z0Y#<2P3&w;5^H%{NDmPy`uTf2503cSdh>H?B*DHvu? zks+QyzTC|~6nw@Ok-91^QB(%Nhl#9Q{q0D?Es=_Bx7{{4Wy+ND{$5pDnOS8@DRuGt zQ&3g32N|gHN8^jA1kxOe?r+M}$$0*`-+|@JSHgo2J))pVcDCrJ6y`%@CWSyBSRSEz zfNG=p-)*+p5++aHDBp`h9gEsdnX(Z+``Md7e(g*84)Q5)k?<CITejJH3z(eF$=kYh z>!9l#f*kb9zyiP?jb%0&v`kr=kqs$At&_mg1SX37{kYd24yT^{0r=U^E_b(#u>;sQ zo$-ZF;O@Kbh_~GKTM%cVak<knK%>BXsVs_+n>k(P`b~b;WSIJ_iSYa1J>d7EC=aI1 zOBUY=<0ovBkoaw|^oeWIFx7g#uPm@Kg210*37Q3APbl3`o^Dw*LuO)uqyj~FQHPWj z%b-CyOI!QpFMkOhdg#9NxfdRM@E&+5eV%%9KKwrYe(T@98RTT@_Ai3woERXrk=k1p z*HL+FfgeI~0`6NX)CTY@GGaI`tiVnx8r0Bbmz)P@e)A05o6DC`Ck%0^sTj%goUCj~ zY<R3jLH<}JJ+K(jR{7mYrqEL+PlgvC^rB=~liYJdFkZ6y+A=P!r&b^$z571H-*WC7 zjz1P|yZMsxIq4m5LT?X`Ywxl9PH^kY3*qJ)FQ`8A=iZte%$a!L0nazrv(46<(@ise z2{+yF3po5$)0u6AJc`vsr*NCL^LIvKflF&NX??uAz~@41s;r!@@6ski@N)iETW$^q zyl5YY^QVz4v_(Nz+&`VO_14dk1Fd3R83(3T9?V{zZ$mn_nunZP(gzCgLS;Uo%;viB z%A4T8mmVs$mJevXTdPkl`~G|W6P7Oh9c;DhdySETqDv_fbYu#HAovwzxexMM<MN%e z-Le1_Y>A5)oX^T{iK=9Pm@#umR-~7|;&AyK0k3%Fk#OC0H^BG4_bvFq2i{lAjmxwS zwy|QW__2p7+9}23%Bylk1A?h4iIgw=z;*LNl?TN5Qxj)||N4dhfNy^5`*r}q!6aI$ zN!YB@zo^YttVNWqh_RH@U_wCp?H#{@BaV0(NPT1V6kWIv>>E__V875rX5i#0G}QSF zW6B$jKgP~D{IHiml~6L;%-g)j7T70m$#~)XbH7#o3T3vFMNOG(QZ@NZ($eNo6mE^G znA20;Bblj2IwBUQa7taBx(cWjZXO~Ly_2S*I2TLiFCbhm=*wfpGMh`X)ddp8Sj(7p zzEH-#i$WHIH?3N^ay30Me+lgQf_=dP05jyymiEoQ<DX$&e+agj_KzU+lrI5onE3~O zj$f&opl<nVS$C2bXP`Ac&``G~6)BMu>7X~)UpIrY(aMMZ{vGcw-#>loKQZM-SNN$@ zr{MP6ZJYm=d&wjT^G4M=@IaLUs<NpBYO501Zu@O0qZ$}$s<D~TQGU60ril5B{Myiq zFS(MKk)okiZeOC4wCy%qsqrY(sc6fY`F%(EZG?I~I3wsPB~;oCATe0o!P{)TWudy- zUg-xk1y28LwbkZ@3X?l9c3FW6kXATtxx9l8e1Y8~f8TnWEm7-=HQj{|fApW>fP-G0 zK7T{`?_*-fANkNb0L(j@y0~GGz@4_yfVZST>@4BQx`BFS3It>FMw4)x)Xt4^b{BZ& zqnD;GgfPh=eI{X)qx6pWuCfY=w%$6GHF*-4Ap<~V)J6ojI;7?#_hZM!x$@GtE$JF$ z<<oe_%)8)#mmX|oJ>w^Bvv2=rSeuM^>%Bgqp#qwyGO`k<F?j_Qi4P%}sE&%tJeX_V z9n45D#Fh~AL*SX<0IB>$2zLWe3_2U>_S<h;>O3{Y$5&l-F)Ug*2OhZpuJrd&`0jVV zo(-TBbI2hthP7*+hGULC(mEqwyLR=H@c#F`Q_;T^zhJ=waQf+=wO)J6iO0i&`S-(p z_uPsL=Kl_Ent2s&yWQ4Sy~{2=4=%s#r;sQ!-ZN_^eCZ3Pm8Q&|bt7DQ$+<kMFIDoM zSu@~U-#i_^^o38u+&OpQth;Z3S$AEJC%)-8*VH7pqmO(Q&Uxexxcj%)!kkBLhi`u4 zOK|pCUx$k>I6FqUMXb5)7hZ4{+<C{Z%Fb_m?F+E@$@_5IZMRZbPX@IWT=0wkhC6S+ z3hw;PRdB~|u4F@|GOS;e=7cvK3%`G0Cf;$|74XpgH^Q&4Iv=uwAqdV5btp+X0>O;; zo_p?xnKOS=zQ5u1$AE?@ttE+6u{F_3ICtIxIQRUE%l-oo+)qM%@N+|dgK&{N^X=28 zd=T%s>*|WY{QcWskMkaxiP<PYoY8TwJp$%Fd?O~ORE!`WJMGjD!mK+lgBjPJ53|$X zFMsKu5_{R)?)0I5cpE<Y;Pvq7Q$7H9-*G8idg1ro_)CKrHS^4@x4-o`n03dcIOCdg z;qKcnNip*KA#Bu!g%I3!ooO9tugF3jE<Xp_1;yjaMDu?C7;Lru^EjFHM{f5dBVIGS z9=6)+<6uG|esPI%{~}cqMdIJcb3LFSaZ^F52!g!0YD4FdP;n_?vcZ{SerIpq@~c0y zePrX!$otAy9s@h?vNycrr1!zG#~cOcpLb5tyc=$~F~tVUVEXif^cIwjI&a4ub0jDn zPe0_qjE->OMVFN-9COTJ^zCnd1<pC=T-a@o{o(K<k4wq4$#BJGKlAV+op{K>2b8bx ze$Ph}@}A#mSUIh<_voWuRdyXb{b)Gqm^YU1U;NioBz8qii7)u!Ip50f1%{)KJ&~p# z`s#AdQAfVgWC-Aiv@Ft-Px%78<!@Pe&iwXSaO~f_HNWuN<ok(#d>`a@ChhxzSHcHA zcuHXiU;WDGioEl}sKXC?8GP+4pNAj+<O105MTf&{UibGUiS*y!|4;9@K!tU(ME>_< zAANV(_mlH3gv+kDrhI?rNhexgkKBkXc1?dWE2vc<YK#4Y8t>)piYu=xasBSQ?WCjt zj(^=z<?msyJXjeC9&o_E3E>~l?}aLk=d@G*0bc*QBjKcX{}a4;`f>EpkAFU$KON5a z(x(_9TSw4Wy<$52^XI-&K17u=mTmXlcT7h94{-0j55gPX^Z_{Hn76^!3Dq+iLtrQx zV@rE<!G$5Tg^>IyXy59XF@P?vDE0r<g*U*l2}}&w|A-G8aYEv~KW?m&AM(tst>GjC z$Gc>~JkN?Io|mP4BmZzLr)&)4QGm#4yS-oPl#%w-Q$GcN`?n{;*=PT#wDZ_wkHWq8 z+7mwexi7-?H_V{?F5k1y{xN**>t{lK@pk^?^DeyT(qhysN`$w(`2@K8?%BntGn!|S z?X}l5Sh{Q(Tz~z{@+6LvKlL%Z{)U<G@lSl3=FFK#X+OQ|T^}y=_K<@QG|<Qfcf^se zhjV^-9^5eF=DOlU#<S<7^FH}cpDix{pE2VW_`(;zQfP86FQ4$9cmG|v=ES$WHya(^ zJ?kEL@B2Rivu53A0xGc;xWk(@`##8@yyd^ySfj$7`JJ=j^fSI$UU2r~pZo$YyX@C6 zZI4|!A(NE$;~#qu+&J?#IOWq{gn4u4m+L?Hp;KVmv|UmX?1jqpB%%Q0>jxdUAF2Uf ze#NzL-gy_5@0o%hbkGYde2Lp0yYHNmR{N#n`{7CNI3YQYL(Be|H{UL@a+)kGRgGOl zNO;e^52S4O3OHc@eajVFZ?#1-sGZ@ao9`&GG|CL+gVOh#ZZ2>5pk&OHjrTL3{m)d_ z>rxE<IG+F0OOr8w5)Mq|q_Qd#eMd6#|N6oCaQT(j%e`F*v)teQ*4HQJ@C0NhaMLY! z&^`A&04KfclO^L{++Ev-m?_Vt?tAR1!$~q@i|I1yqkziw!csu*oqzxCxA()e7wrds z>UPg>J_D;05^uTpKWce4jg8EcXy%#M6gTW{csRYbMDoc5XzX0kl_cJ(gf=|1GJkMr z{R(_?(YzA-UU=ap@X?QbvH<*{(+?@<opsiaq~DqHeeG*!mRs+=_q1}ei!Z(`5AEbw z7N<_0g4u9C_K&AfM&_fBKB6?~nDlqX4L22S&4!f?dfC$D@a7Xwz&D@x27F8U?49=I zZLdA|&^}FuIZqp<fvgASq4Sq7Ti%s#xqeD=AbHz!+OFkA-pL`5vW{HFvgOP5Yz<1u z!aGvVB^!#FiI>c;9<9(Yea$GGtD4!wv~<sG5N~|L-@pm^bHd*wL))dCy2rF#Y#OO1 zhO}8Hyn)$4rqA={%}<VRIn2DtX>@tiY9Lj4`<Ksr41RXrx8bMfejEPzw2u~JPsRiv z{>Z;{S(Y}7v`O03T-SRN@*Vc7LyN?-A!npL|7Vw^ebY;snHF!IhNI5^=_N&%4ip2u z;>sIJ(Xx`al#{ntzTyyw&+*FlAPIIY2OwKEwv52{{_Y`~``F`JY0~S!o2<{OLTeDo z3}lOoTd+5RF})VuF=LmYn|15=_s)fBFW3kE;MR$Y@459fSUt2Jb~xnQ&<srEh=^ol znB>h2GCLYMu~yC*FnuDOY=vlithIzO-zcVNgTlSy6-OwC!K@^6=FBOAY9%$9lpmQ& zBRIKBN}rH4Z+R>>-~YPnZY-TS{a~if`I;LNx@LNu(fFJno?8s|<DWRS)Is9sM57Of z{ONA#zJXWDzobmXvh)B3!Y<yx6}e$SL6$9Bp+=}hn?sW%KIjY0z-VVwd>u`9^I^A0 zHAPK_CUeXPM;!jL@)^-aiz&^BtqhHSbA3Phk#}2VxxAOcsi&O*D^{$moX6~B?90=> z+<*DHd+)s;&OPrEO6Q46Q9wJ^U3o2PX@ko4@++@}kACQ+^02wrA9oa9o@jNZ)}J}` zL&^E<lu&td%=ftImfN*f$aP)LB9X*<u0uBdsZ%B~!H8HZ6d2Ga&Zs|`lAOf7_dR4e zGm%l%2Xa@^EUi|8=bSjJXgNq`6_A%a=|e_}P{={;SHHNH-u}tA;_Sb_6aLig-ekl( z@B1;>_P~FK$8P>8w8N`d<{BJ_aJMLO`fos-s<{wRE?usvjkTv;1S7T^UwhpRpnwg^ zE5Z=h(xpoivTiGvxyx5n1KE?$yZ-tcEe_7qIDg61`Ymrcp`h>7gh+XRK$}9JzwwRl zNk6bFY9y(Hh*XF9_2y)wLSvm*91XMV$_iByQ0frCGKf-M(G%3EMq!-P#OBGuP>7ux z3?x9_DWColeEU0R6Q2fQ&5W|f+Vb<*uV%CpT`r%vWfaWAOW*ykAH}YO)BgF(iLU<! zVsS#n0Dv$O1#OSfYD8O1am5wa(LaCsBY1o=-b|bS{Xf5(9Rejp#aF%Z(3Cx%SSYos z*76mMjG0v>BW6b-$;FJ+ORv0MWTL_emEb@Y!wGC~#l~BM3~f?106=Eg#LTt4lscRq znUU(8=>;j}Mz$SVvuX_vj+s#AN3UA368_ZffjiHDp=s}iZKt0J^Kbqb46S;C1s^~& zjv6)Mp-c(&F*Xh^Tw@*MBo~lvf-lBnf+3fiUv%N6W&iZ)2ZM6V{N>dg?-rCTN}Vz` z7p3IXF~=U65cP<XsLET8NAnf$fB!r4_mm-?SI*D0IK{n*ULTIeAw`u_7TRK(5UPNZ z*{)G_H|%mtwmY~x(dRw)++DNh!DCrL=%tF4hW#Pzs&zvVIPA@xGk4x&l<E1AhnMkV zG)9g*>_lOXNBkU~5H@c)lYGXP&xF&{NB_>AeSbN2#9=QL_EooAbfTgsEmcz?O(YPT zU~yr}%BC1L4?+F?+uv9abmmRBXJf+i&cB$FQK$HKzl6xw+x&ogg(|=Pb(u-Ybmvsw z@vq}iiJNi^-Vqwv^ik?o1ZO7akSChtAt}-CQoS;1Mp{)jM<?a@3@n+y!S62;7$;3y zfsK7*D5coPMQ2|IN1pgv_(L0Q;J=4we+%Y4{7cyKz%yWA!saaKXm`pNN@5FSwTVxp zH%sKj39N^VKRPns#Vdgo-=~SQ^8LE&(>U?<GvIsQ{YEm(qbOygDJ8D(^wU3Il359L zjsIn|ojPSoDKZ&;xnG{@cyTi3>4zMY(Dz2YU%BNszVY3%|2yCQ&rGjNmiSZu^bxps z_RVF#p)cwB0kn9<B@%_|Ux_++lYaf^$3HJL@8XMohzB3Me;La8!skzhgI~Nq-$R_2 zIy7yU#>fZ1_(eIU#WEGKPCp1=ad%Q)C7bq~e)_i(g1!*G_SMhj<W?G1*&=0^-vhVb zc6ljJuC-YcsZMmH(Cy1Fza|;&x9E)YVI%$)op=6)<yb~#9@gnnOAVdW(^!3KXIG1d zA4^159Hj&kOiRhDoB&fFmZ)?dyDg}ij8gQ3C>c0qM9$;Q#~*iO$rk72)ki-3juL|> zV}}SGq;FqnH7=&GA98G6jP>77KLz$k+3=hZ|M$~RF3iJRt_>Smp_LO1gc3Bw()H2$ z(ZrUPk$*jS_d~Gbw7oWHpyVL7!R?V*XToE@|0Qhw;xEHsHsVHYj6!8l9_;RDshwvY zQ0R$V94xd(Ej3<UpIeTHEGM3H()%dW<DZ^?4yJKnyz0t};G&eY`q;-$W)zY3WJJxM zOq0<l85kO0eDM_mp=@B^_~!TEUGM&I8b>}bjsIR*4EO!-I|)AViO-~L^G#q@BCbAW zQFV*Hn1R%6DYTbCJ|}~6);Y&m7hm|pG8Vk&wB0xhjU`?Z216JGQ>gcu-#H83c*1Mo zx@&#`QzzF5j-ifTG2Wf1Gn{hjmy*G~2(J0nPvMT+u7r2J^DS`7Y5&F<ZI6FT89BqO zMVx#71;KCgUmZ@$+dJR!rj9Hun(XX0-ZBbbaq$_;OP`$i&Ra%Zxtf-hMB43;Gu4S5 zRP^ZY-}!OMvGTv4@oBhe#xLOfbH7=P_pl@0!sy=ZJE|9yc(sXczU5B%$j3gH<88R& z(zDX%f6C!}-=bEnzk0LuR-Dl#!$tB^ZY#JLY};0D%ZyxDiiX1v&VCqnf5G1Hmu%UH zAHMG_*z(2y4r3=jkEupTL$R$kgFLgtGAMEaXkx30^PxoAoyqm=MD@Ak8oog6Yn0`R zImXFDO&O7vrR*|M{TwSrR*Acr)yu<2f$69fDi3s5=1kkAp`QF@j!^7y%o;5^-mP1` z-|E1NF{Ba%VPaJNk?vO#F-w;&ryH)j5SOLzd2Bf53otszB&Xc|yigzy8F70wbm=e} z5C8;2<x*maYcV^L$Nf~Q&XekiPvE|lUeo;nT5QIs$8{m|qk2M}kivTydH%R}mAMl| zaq>n<qN@%k%;9UjCr?f?O6Zy8slz_1AHjoIE>N$udn>~dW6Fy!makZylcv_j*cJc} z4LeR7>=8qV0hx92ffhz)FDmYF6UXE6A2=Gm{NYc-pS*R5-=^EV40e9uCt=yW--1;O zW`NMja{C@)?=)6*6uabx$rCpUjg}6U#FR^08io*bCw2zEI{<AmbN-Q6ujK6W+O=y< z2IVaf;7Y9Vu$vUuIPYts2l5t|e^ZAeXEE)mkO+0T3dVLAF%H@4B^2A{2hy+XB)<9e ze}muLepiZ5=TlyJb<|O>z&t+urGNWs%Hsac*G_Rs{A@Ro)B2(HxI86uDn_FY!z--b zRh*?}t)X07l-e{|dj~qYSAjcOClWxgJ)Jp5p#m5MA;xB;M9Z=|0d!;<n}HIeqo0QQ z6nd92IiD=m%sP@CW0I{UAeGW055UPo2virk21$a>Y|go?bw%F*qodR0tUGzC+R(PG z9oO^uK7;}K#l^Kca9eC^cxV`(n})L1tXc+7EqDU{l5O?!N8rhMzlQA({45NPoeb-q zy4z%x5x6xuQl$iWu@ZNbyf}+zOlp?ZdR2X1)p24Rplx=LLq8v*e@0dN*ctA)5giRo zUBYQKI(t9ywR&<eE%&N^S+LiDi?JPfLP<i~GO=UEjklDnX{OM5(#O%Selwv1pQ3=F zBZ?02S6w&46X&c0bdiIu`#0@Gir68FuMkNc8UY<a7#ew>IaU@YfjD9etFu-85}j== z!x7i$X`K>4erTnsDi@qCVl3Zm$gwsu{t=bv)J<&`LNYc8%qvM2XGW#~-XgibF~vyd z<$llGa|hUQ@6F+yFMkLA8r!%@Tf#nv{{YrK_A6NSyZ;e%NEDhoIXptu(Lj{nkPsXV z+z6z>=3>>Dm2QY`VOMzy%9=n76sdyvvagXYlR;eU%pg)-teg*4iSu%qjLmi+H?+g* zVO~d!ORSjFqxoQ-nwdVO|7N5(G{vG7JA{Zr{=@D-MpeP(&Of6>R1~(hS)8Xm-^+Mp z6am2qi;8GDvMbT*DPa?+=NU~-6army+|rJY6JRT;$G0Q#)$V`>Z7kQ^5ma~*WaJs6 z%KW4}b1I>}BOHm3J3;UtBT`Eh0xO8QNkg}-Xr;&*e|O4T;F~9Z7FMrV1%Hig+@!5w z+RMKJuwo7@o%OA3z+-5HVzIi1I(9+PjNSG?Fq#-oI?6Sn10dKds*qg$P>?vvxM^x5 z6<KSHnt$jsjic6e(N%ASs`cJJn}i^i!^-8sp1B@V+Tb{_GW<|K48e1aE@gr|zeG;! z%*G=|NdbYydDPEYw!W~SQ_xiJ0XF}HOadZ+MyM2+!3e6wb&fE?H+mlh!J+$<5TZh$ zzqKQ<kq?E^P=Qb(@3awp>7{zC?nWDKBzM5txWFFEW8fMP-O5(lUft9dPlbCLMEF@M zxoHRNfnz2P!IeM$CH%SDh<2rI#{)hIn{9QF&JrUR2{?yEZ;X{?77Acb+5l}0LP&T- zgZIveu23OTABey=HL|H*MG(BLy<-7lkDstcs(4>O^9u&3SnEbGUJIc}zlY3U@VzE5 z6tE(()1ZJD)>-TMT6@rTnQgJ18sdY=rc}6bkLKaCE3J5aw5squDRw>q=o;*5R+8E- zXfDc?T-xG0<)q5Hla8SVp&~mS2;rkES#Cy4Ivf*}h1b^yx~yCIE~|&+x7=Cviagl_ z5NlILY(XXxgD93he-iavN%4i;iQho`l&D@B&`Rc-OD;9^{@|I@n1_^heZii3{h#$2 zZF}hEFT#RHuE_5}?0v@6N7v>;tfu0T8lfxuNGBN$rs6;5WZjqoiq*GLr0_QosCQ5Y z5`1077D7}lj);P1?-(s7*}&Pdo~M+uY)xa&@d5B0h~3|Q$6P%>@5pq)G!zj!WClXa zjG^8tzv^s3;~+0-6+29XKp4~y>+8)S3=QbNG3-&+UHLz&Id`5TC8};avnaobYEf2V zvIZ3+LJgmk{di0tjXHE1g0l}^l;e$&g2aoHPwCW4%pj%m;v$e@h6EuxRR627AbEum zYZelnxAte2@9_Fzc+PfP;_%QKc<S**@YmdyK7JcCV9pvLJhRuip!r=2?Wr7tG@Y%? z-qr^YfI$0QWPqKZ9{?awT~Y`r;}h09QW$~bK{%I*0=Y8FO})>(vSOgF5ZYwn?lw-2 z{Gu_?2Kythyra;%99>khDBLl~5I97=2(msKyw~j@yI*A^BeVll3KZA^pzS1E`sSw@ z9D>tUey6iic79Nu&NU?KX*XWG7h;GU!1{ru+G?v~=c2rmh?zn?rW@b-4WX%F)sI0r zFF+83Y~|6gL|}CjdJMjPNc%zzj&xNXtD=dMGsuq0u9D?zV-$?V2gbS>f5m^X{P`&a z<=Bi1X28qda5VgHY?>W1ng&*980qcB;|ArA{71UGb%kX?#9;z2&&_AVF*FEo+{neM z^l79Z=QYO91%SZ7oX8EvDO{D)h_%r*tz@2<hY{SE#gtuB-6!a?V#wPjkLOY-RHQVW zh9H*!tzzYdRsu_;bdgjW3EX@@0nyqd{pZetD^O8ErK6(N>Rn@pV)Wu103rk$8+w*~ zrx=sET0I$@T7m(%cZ3<KJcN>z)}sL&fC?2LKH^p#lsq(@`^|gF4A&~IeW=%wJ=N0Z zO>^V8Eq&q#w&yns_9cZ#7|vDQw7J)=UtEXPE7!olnDH>-Pgv~#$8KdDSP6l!7;u;Y z@w5`LV&GFD&b6NcZn==~0&OLC=yVGVT3D@6yF+Cyl&a;<s%|do-Na;=DIGaUhYs!Y znxc-mhaYIQ2n|8RT3lG&!>R+)G7PQtDnLX>bLuJ$JMM~xFoK_H{m88mjQZxSyb=}a z>RPu*uSrcwtBD=&srM;{Dmvl*gD}cbm9uj{@Z&*1SXU>ArZO;cv6;PrD2P!vcL89n z5^jOoP8WF0cr)F1PDj=b3L*$jS)FY~-`ty^shnM{GNJe=q;jhjOIE^O)Axi2?wAdK z&8@OB($Q8!tD3*cJ`8`vNFcB?bhNVlR=AYGo~sIgqYVoh=tKq&5K)<e_8)c7U6Uzp z+EJ@aq;5Gx^*CYpqOjm?t2)rWt4auVgJyla{7NeX?d5sq9Jbi`g7Tn{S{YR>T$7<t z{g$8E<khZFkE}pc>+l62p})Pu)Gtwacw^+s;55LPwt%hnu1QghPZMh72BVxocn=Z9 zZm>5sWX$VpvnnIj`w@q{dLLpUM9wPo(~{i{)LE$hSdAS$#bZ`)A(8T0RlTmFN4>E7 z=Kmg^^?TUoB?rM@drL{IfzOyb)wdvM?`dr$zfi(kbzBC0idK3m?+*JsaD*@;DB^{i zC}`pYaWuyW?#}Hz>vjr1v1611HWW~@GIG^|*lwwmJi1>H$^3gREX4aJsX)0Qx{iqQ zTp&5IQ8+X4QQ+ILu4KZ|Q6ddRWgo^RkQALxASPxCh!Hkxd3E9*2$Lxw4)d7Usyd<< zp>=T{h2ZSL6YExIN8Bhr%feBpYeYGO=%H=5jy`~rKJz$4E??5?P;3(*bS1hpO#cnr zB&#jnNa>Ru($bM8ZM+c<53hm6k3R{2txX1Wjk4&nF?Ex!dtm6`?ls~dYtINEQA=vX z3Pb~IgA^}iv?<Uid03vtK2|5a8XQ2RgS2)O5TRqyM4|7jq_A;&8r1jx@_j@-h1MYi ziUpvZABzZhUb9b<f=q^N(eB34Z7n4Hw3ddL4vUIL;L0Rc8(fxambe#zHRb2z;Rd-- z?IzT=P}kA!&cDg!+fqxhEJTIiqGSAgXbJ+iCP|gFXm768(c)@#5bVjIVgM4Gl3OQL zSE1inKfFYcLs))lD=)Iqw@MgX%gfQUwKf||WFW27$MTT*`<cI-0WbY4C$kz67%M55 zPGDuG(&EYs`Zb2C;yE=~s^Y7t5M&BxK2GQunKe+w(RgW{oFh*)F=Ye=5<LYRVdU;S zjtteTEVp*Cr=T+eixeyn+<BOc_<+-J<*KYAY)oKYk3xI=#@>u_R|-rs7+B>vDO3>E zx1ig$nVh4EC^TSj9)bOtIA!uasgY}Kw7p~(X#c2ugj$m81<GS_)Tva)C@K!}ADW7w zq=~qYj$5U=GsL^;JD?SWRCXi^CLP5Otg|s|GeL9BEE;l;Nh*gDqM$u!KHs91Cx)`A zI90cmr0#`ODb}rC2g?_)flan}HvF}=2AsHcX`hP7WaR{r6-bmt5zaeD{GzB-6t_A7 zrF_t;V&%hSw$&(=L^Q-e*|g9mD6WDKI^2@~LBPOK!I4C+QKLg`L!@zNCMcfT5KHV% zJp-VDmQN)^|6dhTxh`n(MxX&j$WGamVv~;#gH#{U9t#_v*vOX&6o^v|2yGo94k9{R z%ciSL!Jq3@y3X1RP%$C#&awB*X9GmQ3SN=DF_6Bx#QlYFWiQC&Z`E<DLybjkABlzP zGo_`zdUw=$A7a#s>>^q6F<;`*2<S9S<cp;5S|U<#QOAh#IBAn~Kkc~hrhDN9M@)~% z-xW)>ulv3G(K(S6Bu)TW^CN4E%RYA=uOecVB*PG%0_e}$)jkBx)Yue0y$|Y;K4(k7 zl>@!9K~E^OvW;#Og8<N`xdpMijG~Un^hJcQ8U+<c?0oPY0$(Bg#;)`oozRTai$POB z5b+}hNC$F0j!fkwPX^US<RgDvU(|csUXgNS4ccs|`dyKcodrf56VE1n#mb$OIzPz~ z9LCLl91qaSHTtV!7w6#WLF}Y7Q3R&AMuVwpe|fJi1QD_kwZ?xulh`T)AQz(en&`?+ z`5}T4nH*IYG1h|N2dxtUg4J?+<l3_P(OHkcw!7^D<0nlF-8j0zc8`y?H5R{k2Rj** z1}Q}ilvFKNk+gdUQ}{X;qu=yiN-DuvxYgOjsi=kSS14+(!-xSxY;=s5)oHjj$f<Es zfl@v&rQqL&SnkE#l@NwZiM7@)pr{>;I3jDJkOL9LRRq>sM$-eu3oefA=}n>YfdYP; z0lHDBHxcBw8zO2)AiuLVIMHCy>TwWE&aMlLN@`7(#Bse>c52Sk6_+1kZ-NJ#)M0AI z1;~65{m+J?FvK^(0f5P%-@3!Gt_IuZKAU@@wfoolO=Of=hNehfEZ*t_o}eKjcguPc zJvw_1z3|BC@YmS*B|#9pKDf@9<N_R_6FBWR(N}LHhNOt^E2m<h+N9?qbQ8Q7IHc7t zf*MA|m7Ng$hSvisK7p<r6fYDMw(F{<R9}LB2sveJW1G}b$XB${EtLtPe`DLxwt}=( zq6F=BGiG^Llo^9mh8dAM%MhniusShw@aRzdsR&(PcCEL!Srrr*mH0~v1+zFU-ZdLn z8c&f00ccqU&!C>3NRdMfsF-yZnUtKd17yo9f2Hm~R)QO`6C;1xMwoO#>{i>7U?XKb zN@X-`f}jC>h*^M{N4cjZBdPKtsv3ZIU419)@ciB2udy{4P!B8)6p3mu$913$l%aD8 z-3?1yf*~l(iZ>5yht+{9qU%2x>@WU9T2;{VrHZZ#st<Z&rTK^z)yKLS+L3Yjm>HdE zq1v-F5%joI2U1%Bat*}}{WER?cC7;vKuz7Ek(QEM0d{jPo<z|bv}$qYDjc6dAU4*= zQKmxbk=PR&f+l{>*80QJ39Byh{Jg`tG@T;XvwkF*Sftfxm4T|b-J_G!)qHgu5LUY_ z_D$VnZW4sqSg3VWN2M8PD<dvg;M1xYnY3mUsi0&}`TDi1*5H$KmeBL|{mYG57uNdt ztg=Cof~CPV(ZW)z6c}8o6)eo<g3)h21)*NVpvYg@6H(ySic%2oC0#hOL5dtoaV!>w z$_qnnq!@l{ueu6m*~lDkb3~!C)$O%*dTU4FfaZW5WO7+ibXZnCFOJX$w#h6s6h+Zl zeP9*W6<4g3WWs0k!MeU`3Drzm<qy`^;t03{-Rgj}uPlmCw02_)3QynwCVK)(8gh}q zzD{_FJfuuxbiWtEIj9&Ps&SgT1wqVKRtl*Fi?Ugqn>R&s^Y|IDOU!TjrABTvS}MWJ zfH(VIPHbBRF}nL#zs21S-WUGTtuYe}7NQ**Pb5<<?pd^#oEcq{W9$UV)V?ZCGIdk; z3lTV_%gI0o<AvR+X`b@|(<J`E&JYdd1@U83bae&QUf&8K0OR#`p?g{NP(Egl2pu#B zt#$-4^(QV%1edCM5vrOazJM&-CkRXt-prJvOi1PF9qKYJr#NbhJC!Duo3+76lnA2% zC|aTk(Z{dVd%4i4s*if@mO5Eo*M581HU!pUGK@t-F+_d+iRu<8v~t~q32T-Zif5}P zgb*p(qf0$Z3ajXNIi;1#iBy82lMEsgXU*8raKLT`E-y*Lr3;tPCR=R<<0egjzhuiZ zu}*8^J3Wb)*)`$Cg`U8&c7vvZMj#SKrxPq&g1x4iy@cIxmid@+XJ4$3O0|_n+EY0& zlG;2c*gJx&Ei2`Czuv05YAJm6<wc10C{?OCH#%z&bwe9TQB6RUfWH)Ei!LyX(puWV zRz7-t1g-ogCVgFuýmqK2Us2i|rr=eCAAc#!mVn0wN4zZ&GGcd;h$}pVzgH59j zHj3evL?dplN@P`cmS@VQ?}?Vim_skmGf+n?{h&q(UJLBDqo8{wS4MmQn@}WYfsK(6 z7<B??ta64->lgp*bqBKpU&$rgs->%Nw?lS^NACO`{JC3sa-4fWn|wh0cvP^s)un)7 z2^N3|J*9Thl=&Jq4z0EzStL%8zk-(x02WBtF?F#36fV-c1DN1ZbyZ`JR(04tyj@CU zlJ<7;ndQlsk*0Z5Da1LBR^-amrR*wKU7^VJL|f1yq)gtvBOXM{klW<_t*!VfMr`Ur zq^=Hv0Iehwku*|oXW>&<07OnQwf$}Fn9;k+JQ!5Gg9|b`Z-_wl9$t%|&>HDu-XeOk zBhn(Juqtn16V&pHw-qz3dKMc~96we?A^^*h2U7(f0*da)s;bYVCYQFc8n6{hsK<h6 z%kepPKTNwF{CxOJwt~R9+@|x$nntp+j3X{jsf0N|3~#u@z(X*^bH2~sF7JP(iJmt# zu=U$vKnX;Qpo<<{lkx@KVJOlxp&qEn3=xsL^#^aTwFjaQf+VCsQd%A4!3S-aP?LfI zx*<48^jfP}C^*IVzy-7lc$La?rHTR@as|gI-hjMnr~+}{!1oW1gO_irW4B=h(0fSz zJRb3DyPF%kg*9X-E|x6S3(i(3K3Qi_q!8%P=^`!V$%#Vu6<O7=VMI@Z8LlF*vo=>h zV?Gef7BPluq*_5$-&(sw7P52Vvo^whe;q7+;%WGEw*L>9D}OoE$okg+0000<MNUMn GLSTa2I?HhY literal 0 HcmV?d00001 diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 28a912fb3..983197ff0 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -76,6 +76,12 @@ <img class="sponsor-image" src="/img/sponsors/mongodb-banner.png" /> </a> </div> + <div class="item"> + <a title="Kong Konnect - API management platform" style="display: block; position: relative;" href="https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank"> + <span class="sponsor-badge">sponsor</span> + <img class="sponsor-image" src="/img/sponsors/kong-banner.png" /> + </a> + </div> </div> </div> {% endblock %} From 995bd43619a9a1ec545e376671bdb3ad5b4ddefc Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 30 May 2024 13:28:41 +0000 Subject: [PATCH 498/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 968dddf7d..633f8a4d3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -40,6 +40,7 @@ hide: ### Internal +* 🔧 Add sponsor Kong. PR [#11662](https://github.com/tiangolo/fastapi/pull/11662) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Smokeshow, fix sync download artifact and smokeshow configs. PR [#11563](https://github.com/tiangolo/fastapi/pull/11563) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Smokeshow download artifact GitHub Action. PR [#11562](https://github.com/tiangolo/fastapi/pull/11562) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub actions to download and upload artifacts to v4, for docs and coverage. PR [#11550](https://github.com/tiangolo/fastapi/pull/11550) by [@tamird](https://github.com/tamird). From ab8974ef042bc6d09ea64d4c72c0e7fd40baba3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 30 May 2024 21:38:05 -0500 Subject: [PATCH 499/846] =?UTF-8?q?=F0=9F=93=9D=20Tweak=20intro=20docs=20a?= =?UTF-8?q?bout=20`Annotated`=20and=20`Query()`=20params=20(#11664)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/python-types.md | 2 +- docs/en/docs/tutorial/query-params-str-validations.md | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 3e8267aea..20ffcdccc 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -476,7 +476,7 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t ## Type Hints with Metadata Annotations -Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`. +Python also has a feature that allows putting **additional <abbr title="Data about the data, in this case, information about the type, e.g. a description.">metadata</abbr>** in these type hints using `Annotated`. === "Python 3.9+" diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 24784efad..da8e53720 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -99,7 +99,7 @@ Now let's jump to the fun stuff. 🎉 ## Add `Query` to `Annotated` in the `q` parameter -Now that we have this `Annotated` where we can put more metadata, add `Query` to it, and set the parameter `max_length` to 50: +Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`: === "Python 3.10+" @@ -115,7 +115,11 @@ Now that we have this `Annotated` where we can put more metadata, add `Query` to Notice that the default value is still `None`, so the parameter is still optional. -But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to extract this value from the query parameters (this would have been the default anyway 🤷) and that we want to have **additional validation** for this value (that's why we do this, to get the additional validation). 😎 +But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to have **additional validation** for this value, we want it to have maximum 50 characters. 😎 + +!!! tip + + Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`. FastAPI will now: From 563b355a75a3d5c364e062d11a1081e7d8f18117 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 31 May 2024 02:38:23 +0000 Subject: [PATCH 500/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 633f8a4d3..19cffb807 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo). * 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64). * 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan). From 256426ede130cad32a8f6c08d6242f47f56c6a6d Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sat, 1 Jun 2024 16:05:52 -0500 Subject: [PATCH 501/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20note=20in=20`pa?= =?UTF-8?q?th-params-numeric-validations.md`=20(#11672)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/path-params-numeric-validations.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index b5b13cfbe..ca86ad226 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -92,11 +92,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id ``` !!! note - A path parameter is always required as it has to be part of the path. - - So, you should declare it with `...` to mark it as required. - - Nevertheless, even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. + A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. ## Order the parameters as you need From bcb8e64f6784d7357c685dfee8d88ca5cc065d38 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 1 Jun 2024 21:06:19 +0000 Subject: [PATCH 502/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 19cffb807..92432458d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev). * 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo). * 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64). * 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev). From e37dd75485ad083ec2755fb8192347e728d871bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 2 Jun 2024 20:09:53 -0500 Subject: [PATCH 503/846] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20(#11669)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions <github-actions@github.com> --- docs/en/data/github_sponsors.yml | 134 +++--- docs/en/data/people.yml | 744 +++++++++++++++---------------- 2 files changed, 418 insertions(+), 460 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index cd7ea52ac..5f0be61c2 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -17,6 +17,9 @@ sponsors: - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi + - login: Kong + avatarUrl: https://avatars.githubusercontent.com/u/962416?v=4 + url: https://github.com/Kong - login: codacy avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 url: https://github.com/codacy @@ -48,7 +51,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/74335107?v=4 url: https://github.com/xoflare - login: marvin-robot - avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=091c5cb75af363123d66f58194805a97220ee1a7&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=b9fcab402d0cd0aec738b6574fe60855cb0cd36d&v=4 url: https://github.com/marvin-robot - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 @@ -68,9 +71,6 @@ sponsors: - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: AccentDesign - avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4 - url: https://github.com/AccentDesign - login: mangualero avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4 url: https://github.com/mangualero @@ -86,7 +86,10 @@ sponsors: - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb -- - login: upciti +- - login: jhundman + avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4 + url: https://github.com/jhundman + - login: upciti avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 url: https://github.com/upciti - - login: samuelcolvin @@ -116,9 +119,6 @@ sponsors: - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure - - login: wdwinslow - avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 - url: https://github.com/wdwinslow - login: catherinenelson1 avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 url: https://github.com/catherinenelson1 @@ -149,12 +149,6 @@ sponsors: - login: RaamEEIL avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 url: https://github.com/RaamEEIL - - login: CodeProcessor - avatarUrl: https://avatars.githubusercontent.com/u/24785073?u=b4dd0ef3f42ced86412a060dd2bd6c8caaf771aa&v=4 - url: https://github.com/CodeProcessor - - login: patsatsia - avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 - url: https://github.com/patsatsia - login: anthonycepeda avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 url: https://github.com/anthonycepeda @@ -167,6 +161,9 @@ sponsors: - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare + - login: Eruditis + avatarUrl: https://avatars.githubusercontent.com/u/95244703?v=4 + url: https://github.com/Eruditis - login: jugeeem avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 url: https://github.com/jugeeem @@ -188,9 +185,9 @@ sponsors: - login: prodhype avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 url: https://github.com/prodhype - - login: koconder - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 - url: https://github.com/koconder + - login: patsatsia + avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 + url: https://github.com/patsatsia - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith @@ -209,6 +206,21 @@ sponsors: - login: Shark009 avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 url: https://github.com/Shark009 + - login: dblackrun + avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 + url: https://github.com/dblackrun + - login: zsinx6 + avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 + url: https://github.com/zsinx6 + - login: kennywakeland + avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 + url: https://github.com/kennywakeland + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden @@ -224,9 +236,6 @@ sponsors: - login: ericof avatarUrl: https://avatars.githubusercontent.com/u/306014?u=cf7c8733620397e6584a451505581c01c5d842d7&v=4 url: https://github.com/ericof - - login: falquaddoomi - avatarUrl: https://avatars.githubusercontent.com/u/312923?u=aab6efa665ed9495ce37371af1cd637ec554772f&v=4 - url: https://github.com/falquaddoomi - login: wshayes avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes @@ -239,12 +248,6 @@ sponsors: - login: mintuhouse avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 url: https://github.com/mintuhouse - - login: dblackrun - avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 - url: https://github.com/dblackrun - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - login: Rehket avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 url: https://github.com/Rehket @@ -254,12 +257,9 @@ sponsors: - login: TrevorBenson avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=afdd1766fdb79e04e59094cc6a54cd011ee7f686&v=4 url: https://github.com/TrevorBenson - - login: zsinx6 - avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 - url: https://github.com/zsinx6 - - login: kennywakeland - avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 - url: https://github.com/kennywakeland + - login: wdwinslow + avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 + url: https://github.com/wdwinslow - login: aacayaco avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 url: https://github.com/aacayaco @@ -269,6 +269,9 @@ sponsors: - login: jgreys avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 url: https://github.com/jgreys + - login: Ryandaydev + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 + url: https://github.com/Ryandaydev - login: jaredtrog avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 url: https://github.com/jaredtrog @@ -308,9 +311,6 @@ sponsors: - login: rlnchow avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 url: https://github.com/rlnchow - - login: dvlpjrs - avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 - url: https://github.com/dvlpjrs - login: engineerjoe440 avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 url: https://github.com/engineerjoe440 @@ -320,9 +320,9 @@ sponsors: - login: DevOpsKev avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4 url: https://github.com/DevOpsKev - - login: Zuzah - avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 - url: https://github.com/Zuzah + - login: petercool + avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 + url: https://github.com/petercool - login: JimFawkes avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 url: https://github.com/JimFawkes @@ -338,18 +338,24 @@ sponsors: - login: jangia avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 url: https://github.com/jangia + - login: jackleeio + avatarUrl: https://avatars.githubusercontent.com/u/20477587?u=c5184dab6d021733d10c8f975b20e391856303d6&v=4 + url: https://github.com/jackleeio - login: shuheng-liu avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 url: https://github.com/shuheng-liu - login: pers0n4 avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 url: https://github.com/pers0n4 + - login: curegit + avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 + url: https://github.com/curegit - login: fernandosmither - avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=f79753eb207d01cca5bbb91ac62db6123e7622d1&v=4 url: https://github.com/fernandosmither - - login: romabozhanovgithub - avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 - url: https://github.com/romabozhanovgithub + - login: PunRabbit + avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 + url: https://github.com/PunRabbit - login: PelicanQ avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 url: https://github.com/PelicanQ @@ -359,12 +365,6 @@ sponsors: - login: zk-Call avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4 url: https://github.com/zk-Call - - login: petercool - avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 - url: https://github.com/petercool - - login: curegit - avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 - url: https://github.com/curegit - login: kristiangronberg avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 url: https://github.com/kristiangronberg @@ -380,15 +380,18 @@ sponsors: - login: ArtyomVancyan avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan + - login: harol97 + avatarUrl: https://avatars.githubusercontent.com/u/49042862?u=2b18e115ab73f5f09a280be2850f93c58a12e3d2&v=4 + url: https://github.com/harol97 - login: hgalytoby avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 url: https://github.com/hgalytoby - login: conservative-dude avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 url: https://github.com/conservative-dude - - login: tochikuji - avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 - url: https://github.com/tochikuji + - login: Joaopcamposs + avatarUrl: https://avatars.githubusercontent.com/u/57376574?u=699d5ba5ee66af1d089df6b5e532b97169e73650&v=4 + url: https://github.com/Joaopcamposs - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke @@ -407,9 +410,6 @@ sponsors: - login: cbonoz avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4 url: https://github.com/cbonoz - - login: anthonycorletti - avatarUrl: https://avatars.githubusercontent.com/u/3477132?u=dfe51d2080fbd3fee81e05911cd8d50da9dcc709&v=4 - url: https://github.com/anthonycorletti - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -431,6 +431,9 @@ sponsors: - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 url: https://github.com/securancy + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji - login: KentShikama avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 url: https://github.com/KentShikama @@ -450,7 +453,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 url: https://github.com/msehnout - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=2ef1ede118a72c170805f50b9ad07341fd16a354&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -473,6 +476,9 @@ sponsors: - login: dzoladz avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 url: https://github.com/dzoladz + - login: Zuzah + avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 + url: https://github.com/Zuzah - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa @@ -503,24 +509,24 @@ sponsors: - - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline + - login: AliYmn + avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=0de5a262e8b4dc0a08d065f30f7a39941e246530&v=4 + url: https://github.com/AliYmn - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu - - login: Mehver - avatarUrl: https://avatars.githubusercontent.com/u/75297777?u=dcd857f4278df055d98cd3486c2ce8bad368eb50&v=4 - url: https://github.com/Mehver + - login: tran-hai-long + avatarUrl: https://avatars.githubusercontent.com/u/119793901?u=3b173a845dcf099b275bdc9713a69cbbc36040ce&v=4 + url: https://github.com/tran-hai-long - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - login: zee229 - avatarUrl: https://avatars.githubusercontent.com/u/48365508?u=eac8e8bb968ed3391439a98490d3e6e5f6f2826b&v=4 - url: https://github.com/zee229 - - login: Patechoc - avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 - url: https://github.com/Patechoc - login: ssbarnea avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c2efbf6fea2737e21dfc6b1113c4edc9644e9eaa&v=4 url: https://github.com/ssbarnea - login: yuawn avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 url: https://github.com/yuawn + - login: dongzhenye + avatarUrl: https://avatars.githubusercontent.com/u/5765843?u=fe420c9a4c41e5b060faaf44029f5485616b470d&v=4 + url: https://github.com/dongzhenye diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 01f97b2ce..02d1779e0 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo - answers: 1880 - prs: 570 + answers: 1885 + prs: 577 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 600 + count: 608 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -14,7 +14,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: jgould22 - count: 240 + count: 241 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: Mause @@ -23,7 +23,7 @@ experts: url: https://github.com/Mause - login: ycd count: 217 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: JarroVGIT count: 193 @@ -41,24 +41,24 @@ experts: count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 +- login: YuriiMotov + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv -- login: YuriiMotov - count: 75 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov -- login: ghandic - count: 71 - avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 - url: https://github.com/ghandic - login: ArcLightSlavik count: 71 avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik +- login: ghandic + count: 71 + avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 + url: https://github.com/ghandic - login: JavierSanchezCastro - count: 60 + count: 64 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: falkben @@ -66,7 +66,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben - login: n8sty - count: 54 + count: 56 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: acidjunk @@ -81,26 +81,26 @@ experts: count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen -- login: Dustyposa - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 - url: https://github.com/Dustyposa - login: insomnes count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 url: https://github.com/insomnes +- login: Dustyposa + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa - login: adriangb count: 45 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb -- login: odiseo0 - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 - url: https://github.com/odiseo0 - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 url: https://github.com/frankie567 +- login: odiseo0 + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 + url: https://github.com/odiseo0 - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 @@ -125,6 +125,10 @@ experts: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 url: https://github.com/prostomarkeloff +- login: hasansezertasan + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: dbanty count: 26 avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9bcce836bbce55835291c5b2ac93a4e311f4b3c3&v=4 @@ -141,18 +145,14 @@ experts: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 url: https://github.com/SirTelemak -- login: hasansezertasan +- login: nymous count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: nymous - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous - login: rafsaf count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 @@ -199,130 +199,106 @@ experts: url: https://github.com/dstlny last_month_experts: - login: YuriiMotov - count: 33 + count: 29 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: jgould22 - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 +- login: killjoy1221 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 +- login: Kludex + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex - login: JavierSanchezCastro count: 5 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: sehraramiz - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 - url: https://github.com/sehraramiz -- login: estebanx64 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: ryanisn - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 - url: https://github.com/ryanisn -- login: acidjunk +- login: hasansezertasan + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: PhysicallyActive count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: pprunty - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 - url: https://github.com/pprunty + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive - login: n8sty count: 2 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: angely-dev - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 - url: https://github.com/angely-dev -- login: mastizada - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 - url: https://github.com/mastizada -- login: Kludex - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: Jackiexiao - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 - url: https://github.com/Jackiexiao -- login: hasansezertasan +- login: pedroconceicao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: sm-Fifteen + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: PREPONDERANCE count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 - url: https://github.com/sm-Fifteen -- login: methane + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: aanchlia count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 - url: https://github.com/methane -- login: konstantinos1981 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: 0sahil count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 - url: https://github.com/konstantinos1981 -- login: fabianfalon + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: jgould22 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 - url: https://github.com/fabianfalon + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 three_months_experts: - login: YuriiMotov - count: 75 + count: 101 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: JavierSanchezCastro + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: Kludex - count: 31 + count: 17 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: jgould22 - count: 28 + count: 14 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: JavierSanchezCastro - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: n8sty - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -- login: estebanx64 - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 +- login: killjoy1221 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 - login: hasansezertasan - count: 5 + count: 8 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: acidjunk - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk +- login: PhysicallyActive + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: n8sty + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: sehraramiz count: 4 avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 url: https://github.com/sehraramiz -- login: GodMoonGoodman - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman -- login: flo-at +- login: acidjunk count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at -- login: PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: estebanx64 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: angely-dev + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: PREPONDERANCE count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 - url: https://github.com/angely-dev + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: chrisK824 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: ryanisn count: 3 avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 @@ -335,42 +311,50 @@ three_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 url: https://github.com/omarcruzpantoja -- login: ahmedabdou14 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 +- login: mskrip + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 + url: https://github.com/mskrip +- login: pedroconceicao + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: Jackiexiao + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: aanchlia + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: moreno-p + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 + url: https://github.com/moreno-p +- login: 0sahil + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: patrick91 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 + url: https://github.com/patrick91 - login: pprunty count: 2 avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 url: https://github.com/pprunty -- login: leonidktoto - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 - url: https://github.com/leonidktoto -- login: JonnyBootsNpants - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 - url: https://github.com/JonnyBootsNpants -- login: richin13 +- login: angely-dev count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev - login: mastizada count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 url: https://github.com/mastizada -- login: Jackiexiao - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 - url: https://github.com/Jackiexiao - login: sm-Fifteen count: 2 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen -- login: JoshYuJump - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump - login: methane count: 2 avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 @@ -387,10 +371,6 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 url: https://github.com/fabianfalon -- login: admo1 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 - login: VatsalJagani count: 2 avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 @@ -399,103 +379,71 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 url: https://github.com/khaledadrani -- login: chrisK824 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 - login: ThirVondukr count: 2 avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 url: https://github.com/ThirVondukr -- login: hussein-awala - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala -- login: falkben - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 - url: https://github.com/falkben -- login: mielvds - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 - url: https://github.com/mielvds -- login: pbasista - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 - url: https://github.com/pbasista -- login: DJoepie - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4 - url: https://github.com/DJoepie -- login: msehnout - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 - url: https://github.com/msehnout six_months_experts: -- login: Kludex - count: 101 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex - login: YuriiMotov - count: 75 + count: 104 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: jgould22 - count: 53 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 +- login: Kludex + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex - login: JavierSanchezCastro count: 40 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: jgould22 + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: hasansezertasan - count: 18 + count: 21 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: n8sty - count: 17 + count: 19 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty +- login: killjoy1221 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 +- login: aanchlia + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia - login: estebanx64 count: 7 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 +- login: PhysicallyActive + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 url: https://github.com/dolfinus -- login: aanchlia - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia - login: Ventura94 count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 url: https://github.com/Ventura94 -- login: acidjunk - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk - login: sehraramiz count: 5 avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 url: https://github.com/sehraramiz +- login: acidjunk + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: shashstormer count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 url: https://github.com/shashstormer -- login: yinziyan1206 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: nymous - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous -- login: JoshYuJump - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump - login: GodMoonGoodman count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 @@ -504,10 +452,14 @@ six_months_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at -- login: PhysicallyActive +- login: PREPONDERANCE count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: chrisK824 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: angely-dev count: 3 avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 @@ -520,14 +472,10 @@ six_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 url: https://github.com/ryanisn -- login: theobouwman - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 - url: https://github.com/theobouwman -- login: amacfie +- login: JoshYuJump count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump - login: pythonweb2 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 @@ -541,25 +489,61 @@ six_months_experts: avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 url: https://github.com/bogdan-coman-uv - login: ahmedabdou14 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 -- login: chrisK824 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: WilliamStam - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 - url: https://github.com/WilliamStam -- login: pprunty + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: mskrip count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 - url: https://github.com/pprunty + avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 + url: https://github.com/mskrip - login: leonidktoto count: 2 avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 url: https://github.com/leonidktoto +- login: pedroconceicao + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: hwong557 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/460259?u=7d2f1b33ea5bda4d8e177ab3cb924a673d53087e&v=4 + url: https://github.com/hwong557 +- login: Jackiexiao + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: admo1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +- login: binbjz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: nameer + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer +- login: moreno-p + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 + url: https://github.com/moreno-p +- login: 0sahil + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: nymous + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: patrick91 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 + url: https://github.com/patrick91 +- login: pprunty + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty - login: JonnyBootsNpants count: 2 avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 @@ -572,38 +556,14 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 url: https://github.com/mastizada -- login: MRigal - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2190327?u=557f399ee90319da7bc4a7d9274e110836b0bd60&v=4 - url: https://github.com/MRigal -- login: WSH032 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/126865849?v=4 - url: https://github.com/WSH032 -- login: Jackiexiao - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 - url: https://github.com/Jackiexiao -- login: osangu - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 - url: https://github.com/osangu - login: sm-Fifteen count: 2 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen -- login: goharShoukat - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/25367760?u=50ced9bb83eca72813fb907b7b201defde635d33&v=4 - url: https://github.com/goharShoukat -- login: elijahsgh - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3681218?u=d46e61b498776e3e21815a46f52ceee08c3f2184&v=4 - url: https://github.com/elijahsgh -- login: jw-00000 +- login: amacfie count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2936?u=93c349e055ad517dc1d83f30bdf6fa9211d7f6a9&v=4 - url: https://github.com/jw-00000 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie - login: garg10may count: 2 avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 @@ -620,41 +580,33 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 url: https://github.com/druidance -- login: fabianfalon - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 - url: https://github.com/fabianfalon -- login: admo1 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 one_year_experts: - login: Kludex - count: 208 + count: 207 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: jgould22 - count: 130 + count: 118 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: YuriiMotov - count: 75 + count: 104 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: JavierSanchezCastro - count: 60 + count: 59 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: n8sty - count: 38 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: hasansezertasan - count: 22 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: chrisK824 - count: 22 + count: 16 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 - login: ahmedabdou14 @@ -665,22 +617,26 @@ one_year_experts: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 url: https://github.com/arjwilliams -- login: nymous - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous -- login: abhint - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint -- login: iudeen +- login: killjoy1221 count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 - login: WilliamStam count: 10 avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 url: https://github.com/WilliamStam +- login: iudeen + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: nymous + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: aanchlia + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia - login: estebanx64 count: 7 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 @@ -689,14 +645,18 @@ one_year_experts: count: 7 avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 url: https://github.com/pythonweb2 -- login: yinziyan1206 +- login: romabozhanovgithub count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 + url: https://github.com/romabozhanovgithub +- login: PhysicallyActive count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: mikeedjones + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 + url: https://github.com/mikeedjones - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 @@ -705,14 +665,6 @@ one_year_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 url: https://github.com/ebottos94 -- login: aanchlia - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: romabozhanovgithub - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 - url: https://github.com/romabozhanovgithub - login: Ventura94 count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 @@ -721,22 +673,18 @@ one_year_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 url: https://github.com/White-Mask -- login: mikeedjones - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 - url: https://github.com/mikeedjones - login: sehraramiz count: 5 avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 url: https://github.com/sehraramiz +- login: acidjunk + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: JoshYuJump count: 5 avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 url: https://github.com/JoshYuJump -- login: nzig - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 - url: https://github.com/nzig - login: alex-pobeditel-2004 count: 5 avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 @@ -749,10 +697,10 @@ one_year_experts: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 url: https://github.com/wu-clan -- login: amacfie - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie +- login: abhint + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint - login: anthonycepeda count: 4 avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 @@ -765,6 +713,14 @@ one_year_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at +- login: yinziyan1206 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: amacfie + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie - login: commonism count: 4 avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4 @@ -773,18 +729,34 @@ one_year_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu -- login: djimontyp - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/53098395?u=583bade70950b277c322d35f1be2b75c7b0f189c&v=4 - url: https://github.com/djimontyp - login: sanzoghenzo count: 4 avatarUrl: https://avatars.githubusercontent.com/u/977953?v=4 url: https://github.com/sanzoghenzo -- login: PhysicallyActive +- login: lucasgadams count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/36425095?v=4 + url: https://github.com/lucasgadams +- login: NeilBotelho + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 + url: https://github.com/NeilBotelho +- login: hhartzer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/100533792?v=4 + url: https://github.com/hhartzer +- login: binbjz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: PREPONDERANCE + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: nameer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer - login: angely-dev count: 3 avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 @@ -797,10 +769,6 @@ one_year_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 url: https://github.com/ryanisn -- login: NeilBotelho - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 - url: https://github.com/NeilBotelho - login: theobouwman count: 3 avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 @@ -809,22 +777,6 @@ one_year_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 url: https://github.com/methane -- login: omarcruzpantoja - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: bogdan-coman-uv - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 - url: https://github.com/bogdan-coman-uv -- login: hhartzer - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/100533792?v=4 - url: https://github.com/hhartzer -- login: nameer - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 - url: https://github.com/nameer top_contributors: - login: nilslindemann count: 130 @@ -850,6 +802,10 @@ top_contributors: count: 22 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex +- login: hasansezertasan + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: dmontagu count: 17 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -870,25 +826,21 @@ top_contributors: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 url: https://github.com/AlertRED -- login: hasansezertasan - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: Smlep count: 11 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 url: https://github.com/Smlep +- login: alejsdev + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 + url: https://github.com/alejsdev - login: hard-coders count: 10 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders -- login: alejsdev - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 - url: https://github.com/alejsdev - login: KaniKim count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=db09b15514eaf86c30e56401aaeb1e6ec0e31b71&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=40f8f7f3f36d5f2365ba2ad0b40693e60958ce70&v=4 url: https://github.com/KaniKim - login: xzmeng count: 9 @@ -936,7 +888,7 @@ top_contributors: url: https://github.com/Attsun1031 - login: ComicShrimp count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp - login: rostik1410 count: 5 @@ -956,7 +908,7 @@ top_contributors: url: https://github.com/jfunez - login: ycd count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: komtaki count: 4 @@ -1012,7 +964,7 @@ top_contributors: url: https://github.com/pawamoy top_reviewers: - login: Kludex - count: 156 + count: 158 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan @@ -1020,7 +972,7 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 url: https://github.com/BilalAlpaslan - login: yezz123 - count: 84 + count: 85 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 - login: iudeen @@ -1035,6 +987,10 @@ top_reviewers: count: 50 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus +- login: hasansezertasan + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: waynerv count: 47 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 @@ -1045,19 +1001,15 @@ top_reviewers: url: https://github.com/Laineyzhang55 - login: ycd count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: cikay count: 41 avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4 url: https://github.com/cikay -- login: hasansezertasan - count: 41 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: alejsdev count: 38 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 url: https://github.com/alejsdev - login: JarroVGIT count: 34 @@ -1083,6 +1035,10 @@ top_reviewers: count: 27 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki +- login: YuriiMotov + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Ryandaydev count: 25 avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 @@ -1091,10 +1047,6 @@ top_reviewers: count: 24 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 url: https://github.com/LorhanSohaky -- login: YuriiMotov - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov - login: dmontagu count: 23 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -1119,6 +1071,10 @@ top_reviewers: count: 19 avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 url: https://github.com/0417taehyun +- login: JavierSanchezCastro + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: Smlep count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 @@ -1135,10 +1091,6 @@ top_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 url: https://github.com/peidrao -- login: JavierSanchezCastro - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: yanever count: 16 avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 @@ -1163,6 +1115,14 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 url: https://github.com/DevDae +- login: Aruelius + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 + url: https://github.com/Aruelius +- login: OzgunCaglarArslan + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan - login: pedabraham count: 15 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -1171,18 +1131,14 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 -- login: Aruelius - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 - url: https://github.com/Aruelius +- login: wdh99 + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk -- login: wdh99 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 - login: r0b2g1t count: 13 avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 @@ -1203,10 +1159,6 @@ top_reviewers: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv -- login: dpinezich - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 - url: https://github.com/dpinezich top_translations_reviewers: - login: s111d count: 146 @@ -1221,7 +1173,7 @@ top_translations_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi - login: hasansezertasan - count: 84 + count: 91 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: AlertRED @@ -1252,6 +1204,10 @@ top_translations_reviewers: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki +- login: alperiox + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 + url: https://github.com/alperiox - login: Winand count: 40 avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 @@ -1260,10 +1216,6 @@ top_translations_reviewers: count: 38 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv -- login: alperiox - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 - url: https://github.com/alperiox - login: lsglucas count: 36 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 @@ -1288,6 +1240,10 @@ top_translations_reviewers: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 url: https://github.com/romashevchenko +- login: wdh99 + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 - login: LorhanSohaky count: 30 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 @@ -1296,10 +1252,6 @@ top_translations_reviewers: count: 29 avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 url: https://github.com/cassiobotaro -- login: wdh99 - count: 29 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 - login: pedabraham count: 28 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -1312,6 +1264,10 @@ top_translations_reviewers: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 url: https://github.com/dedkot01 +- login: hsuanchi + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + url: https://github.com/hsuanchi - login: dpinezich count: 28 avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 @@ -1348,13 +1304,17 @@ top_translations_reviewers: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 url: https://github.com/AGolicyn +- login: OzgunCaglarArslan + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan - login: Attsun1031 count: 20 avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 url: https://github.com/Attsun1031 - login: ycd count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: delhi09 count: 20 @@ -1374,7 +1334,7 @@ top_translations_reviewers: url: https://github.com/sattosan - login: ComicShrimp count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp - login: junah201 count: 18 @@ -1388,19 +1348,11 @@ top_translations_reviewers: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 url: https://github.com/ivan-abc +- login: JavierSanchezCastro + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: bezaca count: 17 avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 url: https://github.com/bezaca -- login: lbmendes - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 - url: https://github.com/lbmendes -- login: rostik1410 - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 - url: https://github.com/rostik1410 -- login: spacesphere - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 - url: https://github.com/spacesphere From 54ab928acd1c2b929980b887edb11493cada8629 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 3 Jun 2024 01:11:29 +0000 Subject: [PATCH 504/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 92432458d..4a0168b51 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -42,6 +42,7 @@ hide: ### Internal +* 👥 Update FastAPI People. PR [#11669](https://github.com/tiangolo/fastapi/pull/11669) by [@tiangolo](https://github.com/tiangolo). * 🔧 Add sponsor Kong. PR [#11662](https://github.com/tiangolo/fastapi/pull/11662) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Smokeshow, fix sync download artifact and smokeshow configs. PR [#11563](https://github.com/tiangolo/fastapi/pull/11563) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Smokeshow download artifact GitHub Action. PR [#11562](https://github.com/tiangolo/fastapi/pull/11562) by [@tiangolo](https://github.com/tiangolo). From 3641c1ea5563aa91cd7e58f8fbf5b30c7c2f6f55 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 2 Jun 2024 20:35:46 -0500 Subject: [PATCH 505/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20`security/first?= =?UTF-8?q?-steps.md`=20(#11673)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/en/docs/tutorial/security/first-steps.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 7d86e453e..1ec31b408 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -45,18 +45,18 @@ Copy the example in a file `main.py`: ## Run it !!! info - First install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install fastapi` command. - E.g. `pip install python-multipart`. + However, if you use the `pip install fastapi-slim` command, the `python-multipart` package is not included by default. To install it manually, use the following command: - This is because **OAuth2** uses "form data" for sending the `username` and `password`. + `pip install python-multipart` Run the example with: <div class="termy"> ```console -$ uvicorn main:app --reload +$ fastapi dev main.py <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` From e3d9f8cfc7b956cf8383a02752e716a645ad949c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 3 Jun 2024 01:36:06 +0000 Subject: [PATCH 506/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4a0168b51..062c5b080 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev). * 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev). * 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo). * 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64). From 00ebe9c8412866cbfc544a0aaec6a44ee77c11ab Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 2 Jun 2024 20:48:20 -0500 Subject: [PATCH 507/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20`security/first?= =?UTF-8?q?-steps.md`=20(#11674)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/security/first-steps.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 1ec31b408..a769cc0e6 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -51,6 +51,8 @@ Copy the example in a file `main.py`: `pip install python-multipart` + This is because **OAuth2** uses "form data" for sending the `username` and `password`. + Run the example with: <div class="termy"> From aed266a7ef6059814018b85bab423fc890b2aa39 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 3 Jun 2024 01:48:39 +0000 Subject: [PATCH 508/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 062c5b080..ed74220f8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Update `security/first-steps.md`. PR [#11674](https://github.com/tiangolo/fastapi/pull/11674) by [@alejsdev](https://github.com/alejsdev). * 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev). * 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev). * 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo). From e1068116dfd14be141b1d338f6bcb6bcc73cb5ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Wed, 5 Jun 2024 03:05:51 +0300 Subject: [PATCH 509/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/advanced/index.md`=20(#11606)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/advanced/index.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 docs/tr/docs/advanced/index.md diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md new file mode 100644 index 000000000..c0a566d12 --- /dev/null +++ b/docs/tr/docs/advanced/index.md @@ -0,0 +1,33 @@ +# Gelişmiş Kullanıcı Rehberi + +## Ek Özellikler + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası **FastAPI**'ın tüm ana özelliklerini tanıtmaya yetecektir. + +İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz. + +!!! tip "İpucu" + Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + + Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +## Önce Öğreticiyi Okuyun + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfasındaki bilgilerle **FastAPI**'nın çoğu özelliğini kullanabilirsiniz. + +Sonraki bölümler bu sayfayı okuduğunuzu ve bu ana fikirleri bildiğinizi varsayarak hazırlanmıştır. + +## Diğer Kurslar + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası ve bu **Gelişmiş Kullanıcı Rehberi**, öğretici bir kılavuz (bir kitap gibi) şeklinde yazılmıştır ve **FastAPI'ı öğrenmek** için yeterli olsa da, ek kurslarla desteklemek isteyebilirsiniz. + +Belki de öğrenme tarzınıza daha iyi uyduğu için başka kursları tercih edebilirsiniz. + +Bazı kurs sağlayıcıları ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar. + +Ayrıca, size **iyi bir öğrenme deneyimi** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a ve ve **topluluğuna** (yani size) olan gerçek bağlılıklarını gösterir. + +Onların kurslarını denemek isteyebilirsiniz: + +* <a href="https://training.talkpython.fm/fastapi-courses" class="external-link" target="_blank">Talk Python Training</a> +* <a href="https://testdriven.io/courses/tdd-fastapi/" class="external-link" target="_blank">Test-Driven Development</a> From 72346962b035748aaf004b0c93a133195bed9cd5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 5 Jun 2024 00:06:12 +0000 Subject: [PATCH 510/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ed74220f8..98bc7f012 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/index.md`. PR [#11606](https://github.com/tiangolo/fastapi/pull/11606) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/deployment/cloud.md`. PR [#11610](https://github.com/tiangolo/fastapi/pull/11610) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/security/index.md`. PR [#11609](https://github.com/tiangolo/fastapi/pull/11609) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/testing-websockets.md`. PR [#11608](https://github.com/tiangolo/fastapi/pull/11608) by [@hasansezertasan](https://github.com/hasansezertasan). From c5bcb806bbb0a5696da9c3bdc8274df2d08a7681 Mon Sep 17 00:00:00 2001 From: Max Su <a0025071@gmail.com> Date: Wed, 5 Jun 2024 08:07:01 +0800 Subject: [PATCH 511/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/fastapi-people.md`?= =?UTF-8?q?=20(#11639)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/fastapi-people.md | 236 ++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 docs/zh-hant/docs/fastapi-people.md diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md new file mode 100644 index 000000000..0bc00f9c6 --- /dev/null +++ b/docs/zh-hant/docs/fastapi-people.md @@ -0,0 +1,236 @@ +--- +hide: + - navigation +--- + +# FastAPI 社群 + +FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 + +## 作者 + +嘿! 👋 + +關於我: + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.maintainers %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">解答問題: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> +{% endfor %} + +</div> +{% endif %} + +我是 **FastAPI** 的作者。你可以在[幫助 FastAPI - 獲得幫助 - 與作者聯繫](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 中閱讀更多相關資訊。 + +...但在這裡,我想向你介紹這個社群。 + +--- + +**FastAPI** 獲得了許多社群的大力支持。我想特別表揚他們的貢獻。 + +這些人包括: + +* [在 GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 +* [建立 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 +* 審查 Pull Requests,[尤其是翻譯方面的貢獻](contributing.md#translations){.internal-link target=_blank}。 + +讓我們為他們熱烈鼓掌。 👏 🙇 + +## FastAPI 專家 + +這些是在 [GitHub 中幫助其他人解決問題最多的用戶](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🙇 + +他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨ + +!!! 提示 + 你也可以成為官方的 FastAPI 專家! + + 只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 + +你可以查看這些期間的 **FastAPI 專家**: + +* [上個月](#fastapi-experts-last-month) 🤓 +* [過去 3 個月](#fastapi-experts-3-months) 😎 +* [過去 6 個月](#fastapi-experts-6-months) 🧐 +* [過去 1 年](#fastapi-experts-1-year) 🧑🔬 +* [**所有時間**](#fastapi-experts-all-time) 🧙 + +### FastAPI 專家 - 上個月 + +上個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🤓 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.last_month_experts[:10] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI 專家 - 過去 3 個月 + +過去三個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 😎 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.three_months_experts[:10] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI 專家 - 過去 6 個月 + +過去六個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧐 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.six_months_experts[:10] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI 專家 - 過去一年 + +過去一年在 [GitHub 中幫助他人解決最多問題的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧑🔬 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.one_year_experts[:20] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +### FastAPI 專家 - 全部時間 + +以下是全部時間的 **FastAPI 專家**。 🤓🤯 + +過去在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧙 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.experts[:50] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## 主要貢獻者 + +以下是**主要貢獻者**。 👷 + +這些用戶[建立了最多已被**合併**的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 + +他們貢獻了原始碼、文件和翻譯等。 📦 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_contributors[:50] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +還有許多其他的貢獻者(超過一百位),你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 貢獻者頁面</a>查看。 👷 + +## 主要翻譯審核者 + +以下是 **主要翻譯審核者**。 🕵️ + +我只會講幾種語言(而且不是很流利 😅),所以審核者[**擁有批准翻譯**](contributing.md#translations){.internal-link target=_blank}文件的權限。沒有他們,就不會有多語言版本的文件。 + +{% if people %} +<div class="user-list user-list-center"> +{% for user in people.top_translations_reviewers[:50] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> +{% endfor %} + +</div> +{% endif %} + +## 贊助者 + +以下是**贊助者**。 😎 + +他們主要透過 <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a> 支持我在 **FastAPI**(以及其他項目)上的工作。 + +{% if sponsors %} + +{% if sponsors.gold %} + +### 金牌贊助商 + +{% for sponsor in sponsors.gold -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% if sponsors.silver %} + +### 銀牌贊助商 + +{% for sponsor in sponsors.silver -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% if sponsors.bronze %} + +### 銅牌贊助商 + +{% for sponsor in sponsors.bronze -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +{% endif %} + +### 個人贊助商 + +{% if github_sponsors %} +{% for group in github_sponsors.sponsors %} + +<div class="user-list user-list-center"> + +{% for user in group %} +{% if user.login not in sponsors_badge.logins %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> + +{% endif %} +{% endfor %} + +</div> + +{% endfor %} +{% endif %} + +## 關於數據 - 技術細節 + +這個頁面的主要目的是突顯社群幫助他人所做的努力 + +特別是那些通常不太顯眼但往往更加艱辛的工作,例如幫助他人解答問題和審查包含翻譯的 Pull Requests。 + +這些數據每月計算一次,你可以在這查看<a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">原始碼</a>。 + +此外,我也特別表揚贊助者的貢獻。 + +我也保留更新演算法、章節、門檻值等的權利(以防萬一 🤷)。 From a9819dfd8da39a754837cc134df4aca6c0a9a3f6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 5 Jun 2024 00:08:22 +0000 Subject: [PATCH 512/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 98bc7f012..0540f654a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-people.md`. PR [#11639](https://github.com/tiangolo/fastapi/pull/11639) by [@hsuanchi](https://github.com/hsuanchi). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/index.md`. PR [#11606](https://github.com/tiangolo/fastapi/pull/11606) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/deployment/cloud.md`. PR [#11610](https://github.com/tiangolo/fastapi/pull/11610) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/security/index.md`. PR [#11609](https://github.com/tiangolo/fastapi/pull/11609) by [@hasansezertasan](https://github.com/hasansezertasan). From 6fa46e4256d14809c1d18239cf3e864c63e02610 Mon Sep 17 00:00:00 2001 From: Ishan Anand <anand.ishan@outlook.com> Date: Thu, 6 Jun 2024 03:07:59 +0530 Subject: [PATCH 513/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Deploy=20a=20Serverless=20FastAPI=20App=20with=20Neon=20Post?= =?UTF-8?q?gres=20and=20AWS=20App=20Runner=20at=20any=20scale=20(#11633)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 827581de5..33c43a682 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,8 @@ Articles: English: + - author: Stephen Siegert - Neon + link: https://neon.tech/blog/deploy-a-serverless-fastapi-app-with-neon-postgres-and-aws-app-runner-at-any-scale + title: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale - author: Kurtis Pykes - NVIDIA link: https://developer.nvidia.com/blog/building-a-machine-learning-microservice-with-fastapi/ title: Building a Machine Learning Microservice with FastAPI From ceaed0a447ed27a1e8049b7158d7d18249741090 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 5 Jun 2024 21:38:20 +0000 Subject: [PATCH 514/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0540f654a..c84af77e5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Add External Link: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale. PR [#11633](https://github.com/tiangolo/fastapi/pull/11633) by [@ananis25](https://github.com/ananis25). * 📝 Update `security/first-steps.md`. PR [#11674](https://github.com/tiangolo/fastapi/pull/11674) by [@alejsdev](https://github.com/alejsdev). * 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev). * 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev). From 99a491e95c75f75394267c819797f0870d3b40f5 Mon Sep 17 00:00:00 2001 From: Walid B <76976556+mwb-u@users.noreply.github.com> Date: Sun, 9 Jun 2024 02:01:51 +0000 Subject: [PATCH 515/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20typo=20in=20`docs/?= =?UTF-8?q?en/docs/tutorial/body-multiple-params.md`=20(#11698)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/body-multiple-params.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index ebef8eeaa..689db7ece 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -97,7 +97,7 @@ So, it will then use the parameter names as keys (field names) in the body, and Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`. -**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives it's specific content and the same for `user`. +**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`. It will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs. From 60d87c0ccbd2d3f28c3a42c4b11edbf1e12903e3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 9 Jun 2024 02:02:11 +0000 Subject: [PATCH 516/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c84af77e5..e71637d50 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Fix typo in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11698](https://github.com/tiangolo/fastapi/pull/11698) by [@mwb-u](https://github.com/mwb-u). * 📝 Add External Link: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale. PR [#11633](https://github.com/tiangolo/fastapi/pull/11633) by [@ananis25](https://github.com/ananis25). * 📝 Update `security/first-steps.md`. PR [#11674](https://github.com/tiangolo/fastapi/pull/11674) by [@alejsdev](https://github.com/alejsdev). * 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev). From 706d2499b5ca8f47866c33afc18832757d699523 Mon Sep 17 00:00:00 2001 From: Ayrton <ayrton@riseup.net> Date: Tue, 11 Jun 2024 20:49:51 -0300 Subject: [PATCH 517/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/fastapi-cli.md`=20(#11641?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/fastapi-cli.md | 84 +++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 docs/pt/docs/fastapi-cli.md diff --git a/docs/pt/docs/fastapi-cli.md b/docs/pt/docs/fastapi-cli.md new file mode 100644 index 000000000..a4dfda660 --- /dev/null +++ b/docs/pt/docs/fastapi-cli.md @@ -0,0 +1,84 @@ +# FastAPI CLI + +**FastAPI CLI** é uma interface por linha de comando do `fastapi` que você pode usar para rodar sua app FastAPI, gerenciar seu projeto FastAPI e mais. + +Quando você instala o FastAPI (ex.: com `pip install fastapi`), isso inclui um pacote chamado `fastapi-cli`. Esse pacote disponibiliza o comando `fastapi` no terminal. + +Para rodar seu app FastAPI em desenvolvimento, você pode usar o comando `fastapi dev`: + +<div class="termy"> + +```console +$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span> + +<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit) +<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font> +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +``` + +</div> + +Aquele commando por linha de programa chamado `fastapi` é o **FastAPI CLI**. + +O FastAPI CLI recebe o caminho do seu programa Python, detecta automaticamente a variável com o FastAPI (comumente nomeada `app`) e como importá-la, e então a serve. + +Para produção você usaria `fastapi run` no lugar. 🚀 + +Internamente, **FastAPI CLI** usa <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>, um servidor ASGI de alta performance e pronto para produção. 😎 + +## `fastapi dev` + +Quando você roda `fastapi dev`, isso vai executar em modo de desenvolvimento. + +Por padrão, teremos o **recarregamento automático** ativo, então o programa irá recarregar o servidor automaticamente toda vez que você fizer mudanças no seu código. Isso usa muitos recursos e pode ser menos estável. Você deve apenas usá-lo em modo de desenvolvimento. + +O servidor de desenvolvimento escutará no endereço de IP `127.0.0.1` por padrão, este é o IP que sua máquina usa para se comunicar com ela mesma (`localhost`). + +## `fastapi run` + +Quando você rodar `fastapi run`, isso executará em modo de produção por padrão. + +Este modo terá **recarregamento automático desativado** por padrão. + +Isso irá escutar no endereço de IP `0.0.0.0`, o que significa todos os endereços IP disponíveis, dessa forma o programa estará acessível publicamente para qualquer um que consiga se comunicar com a máquina. Isso é como você normalmente roda em produção em um contêiner, por exemplo. + +Em muitos casos você pode ter (e deveria ter) um "proxy de saída" tratando HTTPS no topo, isso dependerá de como você fará o deploy da sua aplicação, seu provedor pode fazer isso pra você ou talvez seja necessário fazer você mesmo. + +!!! tip + Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}. From 695601dff46066165d9e90ace7dbdee917875ce9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 11 Jun 2024 23:50:18 +0000 Subject: [PATCH 518/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e71637d50..4f1b897c9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/fastapi-cli.md`. PR [#11641](https://github.com/tiangolo/fastapi/pull/11641) by [@ayr-ton](https://github.com/ayr-ton). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-people.md`. PR [#11639](https://github.com/tiangolo/fastapi/pull/11639) by [@hsuanchi](https://github.com/hsuanchi). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/index.md`. PR [#11606](https://github.com/tiangolo/fastapi/pull/11606) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Turkish translation for `docs/tr/docs/deployment/cloud.md`. PR [#11610](https://github.com/tiangolo/fastapi/pull/11610) by [@hasansezertasan](https://github.com/hasansezertasan). From ad2a09f9f5af74bea210e996d3d6276f17a37573 Mon Sep 17 00:00:00 2001 From: Eduardo Zepeda <eduardomzepeda@outlook.com> Date: Tue, 11 Jun 2024 18:45:46 -0600 Subject: [PATCH 519/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Tutorial=20de=20FastAPI,=20=C2=BFel=20mejor=20framework=20de?= =?UTF-8?q?=20Python=3F=20(#11618)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 33c43a682..7f1a82ac8 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -350,6 +350,11 @@ Articles: author_link: http://editor.leonh.space/ link: https://editor.leonh.space/2022/tortoise/ title: 'Tortoise ORM / FastAPI 整合快速筆記' + Spanish: + - author: Eduardo Zepeda + author_link: https://coffeebytes.dev/en/authors/eduardo-zepeda/ + link: https://coffeebytes.dev/es/python-fastapi-el-mejor-framework-de-python/ + title: 'Tutorial de FastAPI, ¿el mejor framework de Python?' Podcasts: English: - author: Real Python From 6bc235b2bb649428d908189338841bd2a3573e0d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 12 Jun 2024 00:46:09 +0000 Subject: [PATCH 520/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4f1b897c9..cfffacaff 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda). * 📝 Fix typo in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11698](https://github.com/tiangolo/fastapi/pull/11698) by [@mwb-u](https://github.com/mwb-u). * 📝 Add External Link: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale. PR [#11633](https://github.com/tiangolo/fastapi/pull/11633) by [@ananis25](https://github.com/ananis25). * 📝 Update `security/first-steps.md`. PR [#11674](https://github.com/tiangolo/fastapi/pull/11674) by [@alejsdev](https://github.com/alejsdev). From 7030237306028fbd9919de6a6ba5f7d5227592ff Mon Sep 17 00:00:00 2001 From: Devon Ray <46196252+devon2018@users.noreply.github.com> Date: Wed, 12 Jun 2024 02:47:57 +0200 Subject: [PATCH 521/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20External=20Link?= =?UTF-8?q?s=20=20(#11500)?= 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 7f1a82ac8..e3d475d2f 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -260,6 +260,10 @@ Articles: author_link: https://medium.com/@krishnardt365 link: https://medium.com/@krishnardt365/fastapi-docker-and-postgres-91943e71be92 title: Fastapi, Docker(Docker compose) and Postgres + - author: Devon Ray + author_link: https://devonray.com + link: https://devonray.com/blog/deploying-a-fastapi-project-using-aws-lambda-aurora-cdk + title: Deployment using Docker, Lambda, Aurora, CDK & GH Actions German: - author: Marcel Sander (actidoo) author_link: https://www.actidoo.com From 57c8490b0a103cfa6f6afb078196bec8a0c140bf Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 12 Jun 2024 00:49:10 +0000 Subject: [PATCH 522/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cfffacaff..47198e4e3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018). * 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda). * 📝 Fix typo in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11698](https://github.com/tiangolo/fastapi/pull/11698) by [@mwb-u](https://github.com/mwb-u). * 📝 Add External Link: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale. PR [#11633](https://github.com/tiangolo/fastapi/pull/11633) by [@ananis25](https://github.com/ananis25). From 40bb8fac5bdad5dbf29636c51ac8671ef16673f1 Mon Sep 17 00:00:00 2001 From: Nayeon Kim <98254573+nayeonkinn@users.noreply.github.com> Date: Wed, 12 Jun 2024 21:49:35 +0900 Subject: [PATCH 523/846] =?UTF-8?q?=F0=9F=8C=90=20Fix=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/body-nested-models.md`=20(#11?= =?UTF-8?q?710)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/body-nested-models.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index edf1a5f77..10af0a062 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -48,7 +48,7 @@ my_list: List[str] ## 집합 타입 -그런데 생각해보니 태그는 반복되면 안 돼고, 고유한(Unique) 문자열이어야 할 것 같습니다. +그런데 생각해보니 태그는 반복되면 안 되고, 고유한(Unique) 문자열이어야 할 것 같습니다. 그리고 파이썬은 집합을 위한 특별한 데이터 타입 `set`이 있습니다. From a883442ee00211a0f94d0ab2347993f0ddae052f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 12 Jun 2024 12:49:59 +0000 Subject: [PATCH 524/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 47198e4e3..f47bda30b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#11710](https://github.com/tiangolo/fastapi/pull/11710) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/fastapi-cli.md`. PR [#11641](https://github.com/tiangolo/fastapi/pull/11641) by [@ayr-ton](https://github.com/ayr-ton). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-people.md`. PR [#11639](https://github.com/tiangolo/fastapi/pull/11639) by [@hsuanchi](https://github.com/hsuanchi). * 🌐 Add Turkish translation for `docs/tr/docs/advanced/index.md`. PR [#11606](https://github.com/tiangolo/fastapi/pull/11606) by [@hasansezertasan](https://github.com/hasansezertasan). From 5422612008bf174ee9f897f0852ec797f0a4190f Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Wed, 12 Jun 2024 18:39:50 -0500 Subject: [PATCH 525/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Update=20`docs/en/?= =?UTF-8?q?docs/fastapi-cli.md`=20(#11715)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/fastapi-cli.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md index deff6f875..f5b0a6448 100644 --- a/docs/en/docs/fastapi-cli.md +++ b/docs/en/docs/fastapi-cli.md @@ -1,6 +1,6 @@ # FastAPI CLI -**FastAPI CLI** is a command line program `fastapi` that you can use to serve your FastAPI app, manage your FastAPI project, and more. +**FastAPI CLI** is a command line program that you can use to serve your FastAPI app, manage your FastAPI project, and more. When you install FastAPI (e.g. with `pip install fastapi`), it includes a package called `fastapi-cli`, this package provides the `fastapi` command in the terminal. From 6257afe304853e6cb16c933a9413194b9e189033 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 12 Jun 2024 23:40:10 +0000 Subject: [PATCH 526/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f47bda30b..7c78bff9a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev). * 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018). * 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda). * 📝 Fix typo in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11698](https://github.com/tiangolo/fastapi/pull/11698) by [@mwb-u](https://github.com/mwb-u). From e4d08e9e1ff7e3cbe93c3d8bd3234060d808f99b Mon Sep 17 00:00:00 2001 From: Nayeon Kim <98254573+nayeonkinn@users.noreply.github.com> Date: Fri, 14 Jun 2024 11:45:10 +0900 Subject: [PATCH 527/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/extra-data-types.md`=20(#1171?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/extra-data-types.md | 130 ++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 docs/ko/docs/tutorial/extra-data-types.md diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..673cf5b73 --- /dev/null +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -0,0 +1,130 @@ +# 추가 데이터 자료형 + +지금까지 일반적인 데이터 자료형을 사용했습니다. 예를 들면 다음과 같습니다: + +* `int` +* `float` +* `str` +* `bool` + +하지만 더 복잡한 데이터 자료형 또한 사용할 수 있습니다. + +그리고 지금까지와 같은 기능들을 여전히 사용할 수 있습니다. + +* 훌륭한 편집기 지원. +* 들어오는 요청의 데이터 변환. +* 응답 데이터의 데이터 변환. +* 데이터 검증. +* 자동 어노테이션과 문서화. + +## 다른 데이터 자료형 + +아래의 추가적인 데이터 자료형을 사용할 수 있습니다: + +* `UUID`: + * 표준 "범용 고유 식별자"로, 많은 데이터베이스와 시스템에서 ID로 사용됩니다. + * 요청과 응답에서 `str`로 표현됩니다. +* `datetime.datetime`: + * 파이썬의 `datetime.datetime`. + * 요청과 응답에서 `2008-09-15T15:53:00+05:00`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.date`: + * 파이썬의 `datetime.date`. + * 요청과 응답에서 `2008-09-15`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.time`: + * 파이썬의 `datetime.time`. + * 요청과 응답에서 `14:23:55.003`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.timedelta`: + * 파이썬의 `datetime.timedelta`. + * 요청과 응답에서 전체 초(seconds)의 `float`로 표현됩니다. + * Pydantic은 "ISO 8601 시차 인코딩"으로 표현하는 것 또한 허용합니다. <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">더 많은 정보는 이 문서에서 확인하십시오.</a>. +* `frozenset`: + * 요청과 응답에서 `set`와 동일하게 취급됩니다: + * 요청 시, 리스트를 읽어 중복을 제거하고 `set`로 변환합니다. + * 응답 시, `set`는 `list`로 변환됩니다. + * 생성된 스키마는 (JSON 스키마의 `uniqueItems`를 이용해) `set`의 값이 고유함을 명시합니다. +* `bytes`: + * 표준 파이썬의 `bytes`. + * 요청과 응답에서 `str`로 취급됩니다. + * 생성된 스키마는 이것이 `binary` "형식"의 `str`임을 명시합니다. +* `Decimal`: + * 표준 파이썬의 `Decimal`. + * 요청과 응답에서 `float`와 동일하게 다뤄집니다. +* 여기에서 모든 유효한 pydantic 데이터 자료형을 확인할 수 있습니다: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic 데이터 자료형</a>. + +## 예시 + +위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. + +=== "Python 3.10+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="1 3 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 3 13-17" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="1 2 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` + +함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: + +=== "Python 3.10+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-20" + {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` From 343f5539bd9280ebccc05619a744c96a85af21ab Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 14 Jun 2024 02:45:32 +0000 Subject: [PATCH 528/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7c78bff9a..c6ee5168a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-data-types.md`. PR [#11711](https://github.com/tiangolo/fastapi/pull/11711) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#11710](https://github.com/tiangolo/fastapi/pull/11710) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/fastapi-cli.md`. PR [#11641](https://github.com/tiangolo/fastapi/pull/11641) by [@ayr-ton](https://github.com/ayr-ton). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-people.md`. PR [#11639](https://github.com/tiangolo/fastapi/pull/11639) by [@hsuanchi](https://github.com/hsuanchi). From 9d1f0e3512711ccaec66bbf746d0939ff4842ed9 Mon Sep 17 00:00:00 2001 From: Nayeon Kim <98254573+nayeonkinn@users.noreply.github.com> Date: Sat, 15 Jun 2024 00:06:53 +0900 Subject: [PATCH 529/846] =?UTF-8?q?=F0=9F=8C=90=20Fix=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/response-status-code.md`=20(#?= =?UTF-8?q?11718)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/response-status-code.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index f92c057be..e6eed5120 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -43,16 +43,16 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 요약하자면: -* `**1xx**` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. -* `**2xx**` 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. +* `1xx` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. +* **`2xx`** 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. * `200` 은 디폴트 상태 코드로, 모든 것이 "성공적임"을 의미합니다. * 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새로운 레코드를 생성한 후 사용합니다. * 단, `204` "내용 없음"은 특별한 경우입니다. 이것은 클라이언트에게 반환할 내용이 없는 경우 사용합니다. 따라서 응답은 본문을 가질 수 없습니다. -* `**3xx**` 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. -* `**4xx**` 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. +* **`3xx`** 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. +* **`4xx`** 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. * 일례로 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다. * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. -* `**5xx**` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. +* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. !!! tip "팁" 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP 상태 코드에 관한 문서</a> 를 확인하십시오. @@ -82,7 +82,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 !!! note "기술적 세부사항" `from starlette import status` 역시 사용할 수 있습니다. - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. + **FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. ## 기본값 변경 From a0761e2b161ba6363c581a98cbc47abc7cd4dff3 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Fri, 14 Jun 2024 12:07:11 -0300 Subject: [PATCH 530/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/benchmarks.md`=20(#11713)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/benchmarks.md | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/pt/docs/advanced/benchmarks.md diff --git a/docs/pt/docs/advanced/benchmarks.md b/docs/pt/docs/advanced/benchmarks.md new file mode 100644 index 000000000..72ef1e444 --- /dev/null +++ b/docs/pt/docs/advanced/benchmarks.md @@ -0,0 +1,34 @@ +# Benchmarks + +Benchmarks independentes da TechEmpower mostram que aplicações **FastAPI** rodando com o Uvicorn como <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">um dos frameworks Python mais rápidos disponíveis</a>, ficando atrás apenas do Starlette e Uvicorn (utilizado internamente pelo FastAPI). + +Porém, ao verificar benchmarks e comparações você deve prestar atenção ao seguinte: + +## Benchmarks e velocidade + +Quando você verifica os benchmarks, é comum ver diversas ferramentas de diferentes tipos comparados como se fossem equivalentes. + +Especificamente, para ver o Uvicorn, Starlette e FastAPI comparados entre si (entre diversas outras ferramentas). + +Quanto mais simples o problema resolvido pela ferramenta, melhor será a performance. E a maioria das análises não testa funcionalidades adicionais que são oferecidas pela ferramenta. + +A hierarquia é: + +* **Uvicorn**: um servidor ASGI + * **Starlette**: (utiliza Uvicorn) um microframework web + * **FastAPI**: (utiliza Starlette) um microframework para APIs com diversas funcionalidades adicionais para a construção de APIs, com validação de dados, etc. + +* **Uvicorn**: + * Terá a melhor performance, pois não possui muito código além do próprio servidor. + * Você não escreveria uma aplicação utilizando o Uvicorn diretamente. Isso significaria que o seu código teria que incluir pelo menos todo o código fornecido pelo Starlette (ou o **FastAPI**). E caso você fizesse isso, a sua aplicação final teria a mesma sobrecarga que teria se utilizasse um framework, minimizando o código e os bugs. + * Se você está comparando o Uvicorn, compare com os servidores de aplicação Daphne, Hypercorn, uWSGI, etc. +* **Starlette**: + * Terá o melhor desempenho, depois do Uvicorn. Na verdade, o Starlette utiliza o Uvicorn para rodar. Portanto, ele pode ficar mais "devagar" que o Uvicorn apenas por ter que executar mais código. + * Mas ele fornece as ferramentas para construir aplicações web simples, com roteamento baseado em caminhos, etc. + * Se você está comparando o Starlette, compare-o com o Sanic, Flask, Django, etc. Frameworks web (ou microframeworks). +* **FastAPI**: + * Da mesma forma que o Starlette utiliza o Uvicorn e não consegue ser mais rápido que ele, o **FastAPI** utiliza o Starlette, portanto, ele não consegue ser mais rápido que ele. + * O FastAPI provê mais funcionalidades em cima do Starlette. Funcionalidades que você quase sempre precisará quando estiver construindo APIs, como validação de dados e serialização. E ao utilizá-lo, você obtém documentação automática sem custo nenhum (a documentação automática sequer adiciona sobrecarga nas aplicações rodando, pois ela é gerada na inicialização). + * Caso você não utilize o FastAPI e faz uso do Starlette diretamente (ou outra ferramenta, como o Sanic, Flask, Responder, etc) você mesmo teria que implementar toda a validação de dados e serialização. Então, a sua aplicação final ainda teria a mesma sobrecarga caso estivesse usando o FastAPI. E em muitos casos, validação de dados e serialização é a maior parte do código escrito em aplicações. + * Então, ao utilizar o FastAPI, você está economizando tempo de programação, evitando bugs, linhas de código, e provavelmente terá a mesma performance (ou até melhor) do que teria caso você não o utilizasse (já que você teria que implementar tudo no seu código). + * Se você está comparando o FastAPI, compare-o com frameworks de aplicações web (ou conjunto de ferramentas) que oferecem validação de dados, serialização e documentação, como por exemplo o Flask-apispec, NestJS, Molten, etc. Frameworks que possuem validação integrada de dados, serialização e documentação. From df4291699f0fc73cd1a1052286f8fcb96d2b43df Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 14 Jun 2024 15:07:16 +0000 Subject: [PATCH 531/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c6ee5168a..be7c36d87 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/response-status-code.md`. PR [#11718](https://github.com/tiangolo/fastapi/pull/11718) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-data-types.md`. PR [#11711](https://github.com/tiangolo/fastapi/pull/11711) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#11710](https://github.com/tiangolo/fastapi/pull/11710) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/fastapi-cli.md`. PR [#11641](https://github.com/tiangolo/fastapi/pull/11641) by [@ayr-ton](https://github.com/ayr-ton). From d92a76f3152185ba19d3ee89f8c11be13b3205ce Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 14 Jun 2024 15:07:37 +0000 Subject: [PATCH 532/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index be7c36d87..375e179ec 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/benchmarks.md`. PR [#11713](https://github.com/tiangolo/fastapi/pull/11713) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/response-status-code.md`. PR [#11718](https://github.com/tiangolo/fastapi/pull/11718) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-data-types.md`. PR [#11711](https://github.com/tiangolo/fastapi/pull/11711) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#11710](https://github.com/tiangolo/fastapi/pull/11710) by [@nayeonkinn](https://github.com/nayeonkinn). From 696dedf8e6bee983f15dbca16ca0f3d462d6517e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 17 Jun 2024 09:20:40 -0500 Subject: [PATCH 533/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20Sponsor=20link:?= =?UTF-8?q?=20Coherence=20(#11730)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/data/sponsors.yml | 2 +- docs/en/overrides/main.html | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 55f3e300f..5370ea092 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ The key features are: <a href="https://reflex.dev" target="_blank" title="Reflex"><img src="https://fastapi.tiangolo.com/img/sponsors/reflex.png"></a> <a href="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge" target="_blank" title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files"><img src="https://fastapi.tiangolo.com/img/sponsors/scalar.svg"></a> <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> -<a href="https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> +<a href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> <a href="https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> <a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 6285e8fd4..272944fb0 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -20,7 +20,7 @@ gold: - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png - - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024 + - url: https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example title: Coherence img: https://fastapi.tiangolo.com/img/sponsors/coherence.png - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 983197ff0..83fe27068 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -65,7 +65,7 @@ </a> </div> <div class="item"> - <a title="Coherence" style="display: block; position: relative;" href="https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024" target="_blank"> + <a title="Coherence" style="display: block; position: relative;" href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank"> <span class="sponsor-badge">sponsor</span> <img class="sponsor-image" src="/img/sponsors/coherence-banner.png" /> </a> From d3388bb4ae6ce75f7c85a1fcb070d8c9659c764b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 17 Jun 2024 14:21:03 +0000 Subject: [PATCH 534/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 375e179ec..bac06832d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -56,6 +56,7 @@ hide: ### Internal +* 🔧 Update Sponsor link: Coherence. PR [#11730](https://github.com/tiangolo/fastapi/pull/11730) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11669](https://github.com/tiangolo/fastapi/pull/11669) by [@tiangolo](https://github.com/tiangolo). * 🔧 Add sponsor Kong. PR [#11662](https://github.com/tiangolo/fastapi/pull/11662) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Smokeshow, fix sync download artifact and smokeshow configs. PR [#11563](https://github.com/tiangolo/fastapi/pull/11563) by [@tiangolo](https://github.com/tiangolo). From 32259588e8e2e77f746ddbe5bf75dc2183995224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 17 Jun 2024 21:25:11 -0500 Subject: [PATCH 535/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20add?= =?UTF-8?q?=20Zuplo=20(#11729)?= 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 | 2 ++ docs/en/docs/img/sponsors/zuplo-banner.png | Bin 0 -> 1760 bytes docs/en/docs/img/sponsors/zuplo.png | Bin 0 -> 18891 bytes docs/en/overrides/main.html | 6 ++++++ 6 files changed, 12 insertions(+) create mode 100644 docs/en/docs/img/sponsors/zuplo-banner.png create mode 100644 docs/en/docs/img/sponsors/zuplo.png diff --git a/README.md b/README.md index 5370ea092..1fb4893e6 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ The key features are: <a href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> <a href="https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> +<a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a> <a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 272944fb0..244d98a9a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -29,6 +29,9 @@ gold: - url: https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api title: Kong Konnect - API management platform img: https://fastapi.tiangolo.com/img/sponsors/kong.png + - url: https://zuplo.link/fastapi-gh + title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' + img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png silver: - url: https://training.talkpython.fm/fastapi-courses title: FastAPI video courses on demand from people you trust diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index 00cbec7d2..d8a41fbcb 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -28,3 +28,5 @@ logins: - bump-sh - andrew-propelauth - svix + - zuplo-oss + - Kong diff --git a/docs/en/docs/img/sponsors/zuplo-banner.png b/docs/en/docs/img/sponsors/zuplo-banner.png new file mode 100644 index 0000000000000000000000000000000000000000..a730f2cf2d339d34ac80dee90944b6e9b9740522 GIT binary patch literal 1760 zcmV<61|Ru}P)<h;3K|Lk000e1NJLTq00CYA001Zi0{{R3L<x^U0000mP)t-s>NC9R zGPwW$|Li`%?MuY{>G<$z&h?+*@_5ty+w=5{+5YtW?pVnAzv}m}<@(L<DIu8u000JS zNkl<ZSi|j@drVVT7{I^gHl=AQX#>H<ME@XxmNMZQ7$8A<4Pe2+mM}_SJPHVigKgba z!3Z<8BC?470V2CYq!ckuFeYS_VJ&n4L<Efk>x&=+-P1>mh=z5>eYa34K5#S3W)n`D z=ALuEbI$Mn`kix63gTB3cuUJ7?;`Ia?;`JOcmpG6$|@(}-Kv}^kJmZ}?}X=UIpiF? zw4K*~t#kSHY;ZE(ADx1CPm!&}dwNdJG>DvG|8;v{_v@Z(epL@{WF-0eak&L-5I2I2 zfBs(N0{sZwRH=D&fIxP}K=L_WkyyOOp1-24#!l)LBg&P^!_-2k>)A)$)V3MFW70^F ztL8l(w}p7J!1D@lQysQf@<<S<D9BMNYse;z1F!qt(a|fb+=e_oeQf)~GXG;k!><@I zs&hx>!v%0T+6L4zz0ttN`kEo%XCB@=GPmsu@VfZlyQi~PEEKHv)PS~TN2Qw9Iq=4z z*hHJ&L|c8iw^*JE>nZ?(%1EvmVu|iE<k@UnkM|D12NDpLQ$XZxfLOd87FHIJX9jK= zMRZ4R;L=-=w~jBx*xpt(&^{zLuNz{+%18*R0EHx?hdVgf!(Ib+he4c&<YEBX6J!P# z8T%XHz`}B~a4MU#cjO{RI}QU?j=b)y*i2ThSEj9Dg&)Q3=GC_8cvj;j`6Tf)G+lWv zr7OecHvxpn0b7k9LtI;z`6tRXA?KR$UP=-)84vQ(YfXyQF7#J?@&FslOmdlIa+A?S zHT`D1DYP0l7yCYZ8s3)DF0`^4)2tJw^J<Nk1O{l%u6v-K;cYUS$R=a^hn}b4_NS?U zyixObS-l4x^ol*=(+VNx(RqVBsZX-HieN&0e{H_A`@pPUqB?qIu2nP9(mXt3Uh-X5 z(x#PXO+3>XCfciFsFW_jsJ&kJaGc)929I_ou)2aC*B|`+v^?p8Od;v14=ZcNkuOLw zU{WBBN$T?xNI{<+{|EZ@8NCsiTtJtq2B*$gOSvk6479gm>5C4$FX$DE`=)$1>yJct zW~qr|HeNrl^eCjWehKUORB`^DG~hSdc*j?GyD{O0NPU?EvzN_ZzOo}4Cy2V-?wZPk z$UvT;Z&>P`wIx=?m%7!HZX>#^E$eV0x*C=wXm!NYdX`uD1Lm(6Q{P<>NFPzQ43ZW~ zAQP%cZCi?0rUUN_dd2Rm!oKyUlNpm<17aJm)UA@KKK0CRe-%VMk^o0!<5jyDi24tG zn3SU^qe07p9@;x~5%YI)x__7n_6C=C^%{Y<Hks)NkrDM|xCHdc4CW1AGB8eO0DX?- zRk7<$77zgYrsH*A8NWeZx&Np!Q(IHi!kOb0O|W`JctlIK>+K&FEtSznb1U%K%Vv0q zsodOBo8OOszj8J5UhV|mt~uT{Nx6B^GR_Qd))y|gup#Px^X*;O8C*}>cnfoL`7-oN z-vss=S5|%TPIPh`dFkvlmKT3RURQx$7x_u0#zN(*o>q=)$3-HT<Mn7|^@?$$j<D~= za#=u}G)v9<df*|yQ=ZD}z$uG0E`KT-aZgQ+-7UpsK{r;LdnYF{`V+F$t_Fe$mcq$1 zcHV(ueya}C^M0>S1QTSUawb{c-eKWmKKc#miXaE@8t11w$oxw@Rj7;@n&HLuhAB(8 z)PPoPG1D5dHv!ihIQU)akhfy{daIAW8QwK=$fd)Q>f&>a<?T0F$Fr)?nOBOhT39>Q zMeVIi*{MylvVOe@CeS)&3SsjhKb?edf6Mgu0Po*l;zuwfU8h8g0x6D`=+SnoKE`YM zaB!C;5$7L};1aVW2~)=6OHH%9ytc9UM-QGTGbU=PDR7msybgYsV>*=EO2sqazOkz$ zapDR^?7LznPFy|CD*@q`*U32K4J|5a0Z@z{0p8u8A!M|Cvm%4Pg*Z+sMjM5NoW6{Z zUr4~dvG`gD*6~X4P6!5WG~?y|8)jmE<8d5fJ3BJYzuExUngO3(-_yMf>pXUI*>`2* zCB<k7D1OH#k8ORJS)7e#JMW5TXEVP!!^FH-mi;Syd|uOB5xv-CixSNb7d`)GBl3r5 zyOT46EHv6I@3NQizWi0&NBzsktvI9RAD_?MD__F<ADt&d3*X>8ne%u3z9r{hkCFe) z@0*?1g?VM=?5Dzc|KAZg8SkRsMZb%F7yUY!-@gDp-Ju=j&!%4h0000<MNUMnLSTZ3 CC~l<y literal 0 HcmV?d00001 diff --git a/docs/en/docs/img/sponsors/zuplo.png b/docs/en/docs/img/sponsors/zuplo.png new file mode 100644 index 0000000000000000000000000000000000000000..7a7c16862983be77faf22ac937c1917fad0b812b GIT binary patch literal 18891 zcmeIZRa9J2v@KXja3@G`2$JCL65QS0HMqM=a0`~;5<+kY?iNBIIKkcB-FkE1eeZUE z^vC_^j~?SPimKwAUHhC`d&!)0Z6cKvBvFwFkRT8Us<f1t3V1yMzh($<;JGostslHZ zdaG%<su+8aIXXL7SlgPDxq3O8lbL&3TR<S5bNX?Ms6EUGq01ThZ%?*+VpPSeKcn*c zJ7v<!big-??gU<qu<USPx}V_^BRa0`mK<Yc;r*ij!|F5DHzhA)Jv*4Zi}jo2;5wgA z$SOPzlO!k{^{Ynnk%c9W3vYwPj4#!3?x}3mHc<fl4)S9?1D^d4&S3}y3C<eal$N|4 zuc?C_qp_KTi8-UEog=tg2!vnA)6v-Uqq!@YiMge<y#U2=O9us+wV42gCWkz;yrZbO zm9><&v$?9bf|{xKM^hd%3L!xxeotO7ft|UlF`1{Gt-TAcrvSx&%*zYjzZ_<wAp4IY zt{(*`wB(h@L>-*X$=Dg$8JQWxJ+0kYDFl(o_?^uxcvZwC{&NcOmjH#8tE(d~6O)IB z2criYql2?06AKRy4-+#h6DunN7{TD;W$$Y2$zbpD_GOCyHHVnFi>b4<qpP)pJ=x2g z#wHGKt^yPk;5^xXPX4k0|7Ui4m;W>ZFbC7i873A+W~Tr9a93-K|Ciw}XZ~yW%ZGWD ztUb+bwZyFL%<WykEeKGsvNQk3WdC(m`~P;9h53J-eVK_@+RoV0T+`aj)#|@K_FpHY z%&jf0z&H7Sd_>XN+8o&6<=cWY6ihFcWcp82f|X(VKTGpspa1WF{^uh9EgS!jx&Fso z|1Asrw+8=@cm0pK{#zFKZw>w*@B06jxsd(~+?m@0MCSpZn;wkmHGqAvE+W!u2;j#T z!R!+RLI#l*6ISz_JJk2^RTH1~-?EpUbwzkzn3N!bsxDqgH~ty}Lm3vw@bVQhr<ib5 zun7~X`0l3*f)5|Ou?wYANTi^kL$PG`Qn&9-J&unS7hf~qARVo83Dvl44`=atWb>F0 zXJSGSxS9s!J*cFQ7#)+pE<oJD(*|4>c%tSCT>RfpO;88aU>vH^%V2v*%m03IhMAGK zcTOhkw0EB9NSnMKA7nq5?}BM}Q%XEqq{d1^opxk?ro7rDjmVa`{@!G|Ahyy+o3&bb zro4ft8h?t1oBzq%gJy9MV!!t_ILKI0-LnlE8VhzjdU&<;U^d<DRx{nmIX)YSIz?%< zC}H^1WH{~Fx!kMtq*@el39i6nFU&6<D>;bN_(o!(k_hdwUf8PZ;U8$cnk7ewZ~YnD z$rlN?7I+<BC1O&$B6wn$nl1++(RxHQ4xp~I#LAKJzTywfPMK@u>j7VCxjgfxu8JlP zhrq+~KL#YO@lzxm;2a(ya6OLfWY>tuVkoJPW}0ytq}cOgijWPk5!|0EE;&C&W{-WZ zlzrGgrl%|$UW}6s{|E`xF_==C=QEg9K(K9bg1qUQW!(QX9-dp`fV6Yc9)O$K9pv2l zwP7O?*Z*>Cyb{XBvyVdR5FHVEI)=+B{{*FeX(586iO*>u;l3dT1}bQ7$;or3l7--I z@`Jjaxu=ZI>n|7Fy1tk#=W#}V>$14hbG9yq?IF+T*5XH;X1Ipm6PjIVnOcdj*nQQP zigGhgn&m&b(mliB<DC96B>6y)CsF$L(Hzo%Y!!T6dKEM<>|BaV+v;fZnzf=4&QU<0 zg1Q$iI2-O2Li?X=b=p7yD)d&hA~pj=FKG42Am&c5Sbp)eKwvsDrWy<vrpm5#7q*Rh z4SvTUYC$(<_O(~+lT?EmwmvdvQ4)mDzwn8c;K7})t=FnnUH<at3VcTV$@R>AwMAN) z(EL**wwP8RxKKsRj2yOtz+pk-ks3oH{fRY@D&o>Am|01?GVt9c53F$@rbJ6KtXK(_ z)KAXW6YJr5sUDfFLmFS&I#tK>9ULWJR+uT9B-V}#O>L(^Q@A_f)ApE9;n$)7`J#3v zsL5$66XQ!omZvoeUtf156py^*I9+%~s8&<cCGi?fxsuHbYSAXKA)na%x;(Aa3mhBI z{-q>QWMQ>`uto|G?|z<?8s`0&*!ljvHkClqFkBb*;W@$nhIP+P%7dH;L=M!FQ+3EF z&v&nk1t-fTV>8^WXOB1Xp-9PV;bdyqY7{hT$T*WC>TA4B5rtjx)ghR9<tpTM-rt=0 zS}`8d2M5Ho=4|DmyEl8!)QTiea%kgQ#CM)?Zhy3%nosV3x<X(`t7qR@Kq>2JpNDEC zh>7;Yi-+f=OS8J)ZF+-LeXg<NX-vJPZ=lOqu~~U0JRf*Z-*Xxu+eX(Q>URuVe2t62 zt(_hgiI=t(-)hP{`U$pD>Y{uB3jOAv)85F3I;L>(i=OCWiRYp#*ix7i<6dOOE?pzq z?vXSNQ}rYF4g3lUE#gm-FeII9DWqY=g>E8u^Q(%cUPqjn@7s6aPL@%ZcAa`gCmZaW zP>6d*<hp<D`($?V30~>*YoMLTB%Itf<($kLj;?d+&4-{)UwziDNYy0z_6yYs(Ew^i z?o>RJZus^qTr?7lNJ|TZscK`7x;6EQ3Q11f`6(}$oxZ&Wu`=SS7he6I_AUj&d&4E% zY6+`=o89DhM7V$kMQca{F`P8)Q>6)CF%tfg=>fYt<7>)fVW<<!GbJQZMXlr%pYsRa zFPP70a<;@C^X`~JDCH=%lkZ@NGNz+S$vC$<`1;g2`1+Y~sK;`a?f3?(cOr$fZ?Dh+ z^AK~ZhWKmcvFKpWb05!RQAbgwsw?8Bsc^o{Vw~)r{awTNogbNmeLeiqQuP<tT;<=E zj4|d87=BS|hUN5tu1utEO*t)xZoP7?B15e#4%k%5Ji<6x(ch$?TYOx3#6V9WY{h2j zqVj}aJ?*qGueb-+dJOZzcd|GmepMMUx_16u^VII*>!_4X+VR=t?d*=zT1bbT9S(%x ze$o*-I<T`av*<S$PO4`PVs9fda#oC3sMqYa`+KFs2<{Pt;)jA)yIL-GmL=ErP1We| zXNugLl2)Z;;{{QKodGo44CtSSR`fSum#SHgS57-4{va+j;d@1N>8caPP(|kCfzV3x z*3Yhn_>D`L0OK*Q9qV6xx{h(&qY0jIJ9o^ue#!_y(u|qTIxFB8c@i;H4=+A({Ii_m z(I~g?$$~oLbzX&y_YaBVhfT;L?@1QiaZIDJ=V*gMQ`db6@`*p*IW;eQO8mLMhd-kr zFW+Wda6^-!fZQi9^c40dg^@%u$3`+@aP1Y>v8HF~j(e$L1qO*P3A%B0jxaI5*>K4^ zjceQKAgO7sREh{t#W$#FgRAdE(qTBbD-w~(SE#%ip&mw{j^l4uyG`&`{E!u4>)zF( zA!4-)2;q?~3!lhfcyj!NUqU{HNlDPFH(uJT^W-~kQ4ya?f-k*&Lsg2mS!d6eriwW5 zK3GEf?nkM>WEg$>q5mKkPWP0?>W4Z*o+U9dsl)9HdFkfK%|%EB*~!yuE+To~k7>v< zq}jKaLd}rlYZiyRk4;^C@T56e-u<0~xo2GsEDrgiogs`=P;X=LGda+bT~r3ub7V!a z<P~r=Hv_NL8x2x5(&)%QE=}7VP1?W-A*<_1w(|M56P(1<Y!%@Z?3B$vjAJN59-WK% z$9O?14W$G{k+oc@Ah9BR!eeS8(4{Z!h(K<EgSRST)Wo?C{SW$5SyJb{J5Lwg$zNhP z2h>WfGKD*|L;XNaNMmkCa9sZqEth9`$efdC1fm#n2OQPXd7vUOjZq01dE2`dy?m<< z+W4;8*VU@Qopj{-!gzy<9gF-%Tw@Tfm{-I3HGi<tZzi4pbeJ^8sfJnVUwxGA2rsI? zhsv4zURrweIY1*Pqzvh-*u%w$j{sv1_3z_e8g{GDN`JI$=7&?cO-amrMA`__iq0)U zpHsK113tK=2wzoZHh<VwO7vn&1O(gWCwK!vfvwc?A$Vkk<_&%Z-~GH22Ys6UN7#{f zt|-2vC9T;K2Y>kVDl9dwW4hCnD_8%<IAlVPAR@F9jpOJC>ol&oOOy>Q+9z`wb%V4r zc@gL4{VR0lnwi7$O-&S2_Xn6Q1A}Ojz3PiSi`MPSvb8LAk+8~qL&<n-(iJV^@LKkj zH?hYiOU}299eR(46=#v|#?Uw0%2ahi^;4Oja-DZLMQi;##qd@hi^pWi^-r972N`KT z@vB0m8qDfd1QlXowetwUzrjsYfC~D{K}|N+M;#-giU|(l5mp`tB~r7GQ>`DKSn6Hv z*Av2zZr-#+wUU}HOK#^{P(_VPA}N@5hxN^TbvW%kixJ6LL9^PN?%cfAa&jZg=DSR! zsEjpyJ0y>fS`h7lmm2Wuo5&>ZC^7&Qz_i_0Uy@hWO{TT7t1(nvQjIU`h<}f5Q)poa z)<0dZ-_mBS9Ey;37!OI7zI{%)AO9Of_etkwN-}q@K~D7VXc;N<E+fQ2yD+(RwA6Xt zIb{lg!@vEf4vDKpf23DB2H)=i(?6<bo%gGL%!PX{HC?~7f}c;yz29PrC269x$9u_c zA&Vg3Te;o}R1lsq9}I~VKgdsCuU&tQ7*$F;IC}$YoL~MI??RJ#?||JGm!or6-<4Le zm0%9WA@njdGL#ZFhTaQ)W_q^vnD%6egV)hd-=ri}1<Gi+$nY5PL<5$gwT9$l<)Q1W zB{c>dfpP8_m8W{biTai8!7!h*?g(c$Y=QYl6KSl_Y`E4;LAZ>*VWY90!0CyOZd6l) zrW_s)OCAe7o!#+qg~9tT^oLHb44{m<QZDfWoW}I8%a4)JhzhTmlJ5mKz6NWG`s6l3 z2M5R|BzU_G>YEQa!tO>F3w4#<BsMM=yEipFWGsqpuTQwJ9i_Ls_c_8a<vhJ6tVlb6 z_s?fWUW`NkrFhzdnO~yzjkp^YduiYS4J=fvR?&I+ECYhvAL+g-Hf;T<LwkrOWRZC* zO`E#A04ZF<uib=K{JYanvh_IV86tXvAAzWk6=C1^fAPBtJdqfn`(ZtbHg{=m>aPvI z=TMVk`tvKo(!cj?p}c{bHyM<NZpBU2e9LqsEF|riFip;vItYSZ#iGsUJig#|RrAFD zhHZyr5-!MwG~McmVW3Z^DM-RMfdlGe#bNL052oA-k5(!@XxYgk^o^X(@3pGc!^WCl z2s?4);LjCxZpz*zpR1w3vn`&+BI#Bf_swT4KW!FEVNmVa^-ZpyA7rF^Iw8)zVi!j4 zxRW}G3GSHd??$a$S9*H?kaSPTskf~9?SeuEBV(S}2L>@)+3Ii_fuq$Fv+yb;uoKl( zPyyG%crf-+E2{-&wxMx%t!9+~&OEN~H=C-GVcI7tJA|J}aBu{&3*6PKcO)-~VsAfb z^xv~T`-!wjBQ<_@5?t8ix}Fo-)dGLi)U^8w06`v)h=d+tIJ_!^!5|Vp6rbJsSa9Tt zG^~eYT_Hcu52WDCNnsz|pYxdE>N|QQ%zxVa0#d}vwruI5;h?;IGa(cTB**+Y)X$4% z!Eoq54)`vnM=V+QoZSBvS~UC%4$VVQ((w*ka`0o&M;-#{qlc-EMuoVVcI|Up?D>rI zO7O86>3>Z|4=T^|k(_2Ho~V1NzuTcCcWh;z5a1<}`kcP)o_%ZRkL_{1Tu!QpfH!{( z8w$}gOZ$j1gICaV83%<<(Zwd?#3U>?pdJ1({LE9KDFUpCJ?*+`Go;E9Rqa0I@(j}0 z8zj0P3jNs+x51~e3F^TCTSvSpV^?38@~@RgXRR}|Bl@6oiO&(^&30s8g%Rx$<_Ycc z*n>z^&YFR*DHnYEw6gA+(xw1^sD2yaAeCK9L>Xb{GloJh-!IEv!*_eR<jFXYDP5-b z2P6!y<(<&A0mO$|zzKl2>LZ@a^x`uzZz^?X|D0k=SpfV+nuUesyFnYT6a@nVYO!KY zdokbG{5+uu!p7z%k4I&r=n4*}67RoCm6FxfJQUV6!vw>w4-DIz&Q1=g`#(AtQH^3H zV9GV3gM*>d<!~C1qi|A8Oii1Nd*FD-=juMb!NKW^^8F`7MMX_LZpNBOsat0wP7WJ} z0c-TMeAe<)t;OB$YIh<+SXj6yErn7%X`_&pCgt|oezAqmFNBcG-tl;;jp%&V5(NRJ zuux^$J4xoo&aa&cv7hoFSxp41Aq8@;cGs{sRf?zEVE-sYNEZT+PA&bfT(_ZnuZ)@Q zr%X}z5B1W~d~syC96{p6W;anVVYU4t?@#+h0%SZ!H67ApOyaAi?d;^`{V+TOB|W;z zmAPtDNx83_sLIO938G}kwO$%CH2YNP0ip^@_;%$1_KVG^Ieu3>g3oKn4`+i+C+Fw= zEyt}P1(I=O)YNyl3o>Dc8SdqQmkkN@0~KZZ?3TuwYGW2OiQVe74XG;B^6AV_4(+#F z0@f%GgCz!S-joAHvT3wu>a;iwcJmTRa&mI6%_Gy(X#}y~dcDIiP!JGq1`n}CMwgcj z6N@KycUD)OeB6+P>m+&(4s1yTyg&1K9GL+V&gxBy6FjtgStyifj%2j_puD@iS1un* z=dq2HmQRt9Pto~%B;cJu8G%ZwkRtPzMv=)Oj+ifw@^+Aku0-Wyigb~=krJ~ytzF6c z?<&kwHt2&6E{jQ~Nt298No@DG@Z3(Dfq|VWJhdGiLQ^(%$*!g&k#4-i;Ozugi~l39 zW|@|<;4rl`3KCMjMkzyGW_&!lI<0!-w19v>$;9pvK70i;q``ji3uO~n0hy%2#;cPa z^z#T(e<K;0sLboNXr{A`fn@d!Id*&$y;e__$A^cF{k*(9y`NT?E-o(8Nz)bj>(|Qx zOfdH2h0=1eva0;W?uT<jfBu+&Wkn1u)vVmg<Z-$AMd-lH#g*oBeMAKjyqYn6I3E$R zW+$*_&1iI5mk5uDNc)IY6^tiRC7Z@bIY2HNesVc&NF&{THTN+Js^Q}_Bcskwsl@3P z4+jf#bKot_3)Q9(4{@3mdaJ;j-brJr+i<|QU6V|Vk6W>3c%E;`SLk+RbA0@lU#K!* zR7Vw?X$v7ShAIA)+1l!to{}P-6!R(Oo6LGwLe-B<HcLh(!*;o(q2b}J##8K_ZBnU} zUm>)0@O}@_+{WGU`~j=b(lxocf#+L)Ej>Lc)oB@)y(}?mYlfKx1%=^$MnvF&_b2lX z9R-vnw|#hqXD6#Y2g@BoY;0`ONtVNztF?Z2j-$EPo<|EjNoMx;jPPi_s&LhmB{xSc z$E<JPhEQtj=?z&=e9Pz$#yA)&fUm8oxmj=-aawNoV<(8Er>Eao>x<q!J|1DzZ)T>W zi<T%z1P^U(?Sq->f<XtOH*W?eC)IHA@RBKGCEjw`%~6&HDhfTagL!6(6-i0B9Y6U0 zd$>K{-QTC1p7?34dbHH`wXd%aEbPPM^)ipg(Lw-Ypr4<g*XAFbq>T#w7H-Ft5C19+ zmpA3Ch!5_s4%e%Udm7CKu#z@X8FUc>Nk~Y*V!xIC_U)VV?*wvIJW?TlekjM&wLWmO zYLoN1!Z1l2e8;V#5Pshq=1Tn*YV^<5ru{WwdBHWoN7sKRzP+7L6dJQ)KbxsGy*N9g zU40Bi(YenEn5{7fV`5@s&84IeF1-b=kC!VU`x$JOjpl>6d;%ILo0<mH()G5pNv6MI zR)_WZq?4j?8P+}}zI|V!_7eWmNyQ3TYu}X%xLvm72x29c8l6H|s;kj*>ztJ9BnC+Y zvMHs}NCks!VpDBmBPir=Rwd8Rb?fpP;+f(}g@ltH-2M{8J?xl1wNET$U+!}$m7f;s ztaquGY9vzz%(rK~mGJNFlTA&cY_PkJrA>hsy0dyM&HBD1e5gb~z>RX?jnJc*bkXX@ zfT~myTu4wdwfq*Iq3=L<w@8wivNC3WEa6DJ5J}&{g5DQ7>R-LRDhQD|zGsn}+VkAD zGt9vFsgzAdUC<&3SBLYO|1PI14M*}sBb@jDl~WERzLh*{zdu^<jl_QOnV}&$g-q_m z>qU>8L5DWKdv`D+qgGWQNV;1!=7Um6s>KRakf&{-=fs>ki@yYDZ&*V+9<K<cop(m_ zU^{u;_Np2i)5F5TGMSB`h3*g7yv}a>p=XeC59b@`VrVog4K_!Fo`*o;z=pK7wx)mm zIw%@}_P%%exZ^pSau#IqrsQ97#B_$&=jZEv(Rg0F<5WoGe^8B*GFi=|=)dJ~I|Xl# z<X9>xCHOAC_(PKK)vTrLX5&?7nNA%oSlt(A-7eQ_N}`-?bTWNY#u|9oyQXR2)d!uM z`dJNYIpEnZ$*j%$@?D7<2-z3=jb!rl<jSO&G4h@K<&sVkQpl7_kr1tuFopW=cV-k% z<MRcI-vpLJ2mMDK$>dDY>RX8f%KHnyxJUR_nWRj?M;e=-29s88JG+O2v4mWSl=F4_ zzrUf^F^8D;NO*hRDwVUO%{P7Il4fP)O(pfSg>rP3|Di^L1bM!gko%#g^QIF9u2n*s zHF_2-EVVRSf8D2lqTy&%()D)t?|Qnswbj&m<-c+&7pV;T2?RX(f)$~rp&5i2)Z1n} z{Pp$q)lyRG1iqA_8;XX2VC3Y)vOSbhfKh~ujNAkk@KqolgAQfd>GicGIHjtpiWpdH zIYKRcbug>Sh>eBS4MIqrJCM$mZ#7%M=cE$`os5wYjX}3w4BXCWyPwa+-W0Nav#T(0 z7iB#?lz@N$A|Zbw(tw9*Uk59zcaU6gZ3JYt94R691FhS;%l&CgY-||mBt4Qqb*$Y> z@7Bkw`O*E$?|MzFYwPPy2Qw@vB>Y;8*cccPh}B{<hs993u_aONf$gdl&F*{y)1(c@ zaE?$ssCp1cg&vEfu5aEl@=TqNCQqs<F$xFny@HGk(oY=*YQ^l}kJA-B&BDeHH>dcQ zr~Ot7-!Wlfw?=Z{%O&WReQwXpTSqH%&Wv%_@vPX0Zg0ORnl!rZvg*`ZK|yZrz8(*S zzk^5=U@rR!;r{)~C0g(+)^R=j_GVNXo2JK%9SVaiNTZx2Tw_0If4XwkZrhdFzA2Z- zW&4jg$j%T5r~LxuwBuF`k7APAcf$@ra7$8aAOodz#DJ<8ieWYNBc;`s%W_z6kTtmz zTp%$y8OG3X**QK1M5<MtPH1T8%4t8TWGn&4=nr)|Pft(oH%68t*$mHqhjScyP0r%} z8jp9EPT+eCedSVQbXo0wHIywt2m^=mT?s}b3<~70)K8I-T?<VviK(gKKYy~zePKtW zO+hmBJ$<$0xsHm0&kU)x_zMl0EZ4;w82Gbu&*iWbN-516IFhYSqL-4BWB5&dCJ{6! zXkZ3;r70;XS2oiO-M!tVhw-}mT(Sd}h`Q?~<4ITp%O}qVvOVw18&dYWp&1z_MNY|F z6pCboEdur13#+OKP$WP#$0R2w55)McTO7BRRk^kGN5klMfc6K<SrWC<)Z5&um>4<O zR~b2OPrmiO|0)7Q4{Tiu2NM!7Zf?@!(K)se(=#$ZC@Zr>MMbSx!QqKOTv48F=v4L8 z4u0a)G&ar*pAWjHxzY0j7quGA4H`T(DWcP4T+XKXvgq*!R14sF@X|>MDJfwElJT_t z;bDx1?Rq8xU0q#`zPB|KI>${eH~|$dVGM8Gc1EF8zsU(te3QqyeQ^N)dj?3Z_vIe9 z+um!)O3QJ3NM&VZW_Ne@Xr3s%@8jh(tK<6G+H1GA(_e(?JTBC&ZEgC{oD>w@CHm79 zvuHkoes}CrCQlEyQI_zpUV+?-hEzfSC%p_niSW(Av;yr~3#)$%nP0dZ!a+{!8W}-f zZ1HHAqCymJbLI;x5DoV_v9$cE_^M2!{ENwM-^eoh>gww6p`lR9z`_jzDLEMl6K7OP z>gmo$boQWxG#C0Q8R!JqP_wNyx4lUb5SWfv2ik>}W)%0WZ@x!LOJgK#+$UpULm(L$ z+T0$)<JpZi38Ap$Y8WCbkrn#PesgA&R8)V6zp0d%F%n_EG44;H+SXT(I;P1imV+wP z{xx`i8~_m#3gGGM?aepsk4qQyYaX}kwRbzz*iDoq>5^q?3q>X5B;)5N8XFt4ny)XX z5Bi+O%F2p?iwl>fQ2bj_M&@oC+H=0%&O-TMzY_D!n_WtK=uS|v9oKph&CJYJ03H{; z+^b(FUiLW_u$}vf2m&N+{|=zVJdING<BHXuhyvrD@ZTdN{V8;sxl=ZYNlDO<le4pK zLWfpm8^ZImvntbmG}ohrHz4V1{B!_|>3KFl14TYs<YIZTKaCC+o^ijr;u-*8T-^q{ zK0q0&-S#<c0k&WN72A-4X;IDlo(1vA-ycJSjGZ3E@9sib<}2>m$*2gzO1#ih=TxcY zX*V)cuEt*-43Q7zDytKU5~2lTMvKjt^=_JjUw&Xfi$GKQJRs5ezhbvR<^AapUlffe znnW3MXNH0TC%|bt0}H|DF~Rrs^&_K1R2LCt-f8nNX3eNFUbi^7@uQJiyPSsW6zU|! z2#l{}3P&f60=0VOVD`Mxd&)P;q(B0dJT#C}+VeWA;k8Jt5(=MkH$eq!&m7+4{WBi$ z5a*|KmK+oCWxngT)DP;)j@SIuv5Q>q`NOPHrWJIa8d(lv7XcYLx!>5!>hBkh(Op-3 z7L(A-=_+H<zQU(?U3j=o;F<%teIRMObOpcS_kZA)W)%>~0-O=H6QE+{%4vX6zv{KP zm+M)KWD8uJoaD+Bt$|{#ki_qGMw!NB$jDT8u`?C|ndzxfa|UP+Ah;I<3K!Bf@To4~ z*<YNH)b~VqYjd;u`}a?ToVF`ZkM{tkd){4GYy8m5z!0$?0f_PVC)%6WuX_Q>%;s?k zr>&c_UeqX8W&_ZaIyth=W@-Zf9^oW@5NCjbbkS*6j9RfLQR+5W%L9&t_k2zveFhM1 z=Iyzh4gXKy+mtjw1~PJTMmRoBpZy*ypd47IQK(W$p`G;h8tWO1&R$x&xVZY3ra)6% z>@6Ul)C#!GNETne%k1pX$Vgh6kwolMsGz^_#lPDL+3gYaQhzFGP#xm{{YXqp{uTQi zWY7%p_P#$a&hh7DV#yL3!RaVVO7oS7B@rzzCRN?zsHZP^?bH{Q@^F5Fxp(Oujk$06 zgJTJR7y{|>kq$sF6afYx5?ruVDpfD7=&LF+UTz;rrkrm${vfS#+VOZlVa9q2Sg&5& zo#waVV%@UNkMBb%39A8evebPaXk=kQ4X7k_z<n}};yA#(fFal}wKh%M*iC*<T-XLh zeG@o7;4a^%_q72)&@}W@=QIJ9lyN$~J>P!e@6bk@e^NF%N%%bzK!LOL_isO_)=ZS3 z#|d1;;lQRhXvLR|BNG1b0Rs3wCMjurW+stb2J0)Pwu>a&Ol|<ffrCS`6e4D3wDdas zi9w<1en|{pxg3HiErv4@+YHbFSP&BvGXm7j6J*iEFJEY<K@|)+IdO!Ahc^Z30iWBE z?BVgT+W*m;h|e7b5fM>JR<>tvsy=-juo10h*Y~cx#QFL8M(hODfGvP}PRgj)2!SGF zVZj7({|jB{fh@XK<A;6=rwE8Iw?AqJv$eW!pcT`(O1Bq>Lb{ATczeTrQ}~KhrxSbf zWA)_ftUC&aj(IOx8NB_)L>JIiB+J9?zsAi@fNH-W`@j+ifsl;6>;-6yi{|0E0nq(m zu>l?2YFKd^&5yoc6f`vOF57?m&L8hG+=P(RYQ3#zTZ<??eY^^Q`%5V*_BXj~zvN@v zdpkb=CoeQXB2MUN++v+xd6(N;WZc!gDLqdgpSQHMSbzrg;~DzLGIcyC{IgE0)QXJ8 zb6F{vAm^keur5|upBQQHyf&qQK%AW!jh~-F5YW*@#mr#Qi0`nEQAwaf4C0qPj=D($ z4#ZPdj9%m5m_7xI=MKOkkTH{C=#;}D<I;b&BMJ%%I=Q^;`;$`Y^z`6$u+&D_alG(~ zl$7|TIDzXid!4;TA>zgW><#1xupgo`iApvhIr(isd}AZ`3)BPk1qMRI>xw`S3)j@t z1lSckNcEYnlh`y0WbEv(6B84E|Nh+xYGt+Wtuv@BtKcoS=Ly-v!$TEVv@jAP;5|JN z=%yf5y(ILZ47R)}8%!c16rd}C`e?e)=tLIz3K@5yM(e4;-l9==k;43~+DLXft2t74 zPfz04ulp+9*i@EUlRB%7#loxG?_LM=3{NXHl`JYNs{Lc2Z$NCh3k`|y*jP~L7l?7i z{1R7jjf|lt@t5o%E-z2qw`ftZ|Los+RN1x8ratd-r4>Tng7j|{F7^lAdg338qZ}}u z{v|tg(*~l?PmlV+nxEq=XijJ;<PhLj{_s}$nbEEu$TEbMiH`4mr9ViEBofh4;+Dg` znzoJ2U)&Iv{i|d$M>P{x6+ATO@H1$t<^m4-_0N_R&I$(yM+#waPhwuJ?}sLS?-k0N zHw37}kD42T4z@b0P-%Va%T}P{Aa27-!M&%7c^jFWZ<8GfY`bj|YSzDVCLp)mQCc3^ zYf229665uTvT+|~d^69QPVC`v;c&_3Q8pIH51Z$GLQSVfnMRVJ-M8T3cH(KO8c!Do z+cl<m%JgK>@?W1I;ho^3?GK0`D)mQ&_30eYbIMk+=&r(=&6MAClk7mF4db}mPU*x^ zp}5cWn!a+~K^pz%oBWZC4{H2PRYjKp>nH2}Q+=ozZ5&6J6(7B8hPP**-)V2VL02l( z80M{X{>gQ#w{yRmzx;ex8GMga)R64Bc7&$)#UgQDxZSZDjXcu}U*C~=&Q+OEp=6Y& z9HIvKe6>*f8e@Kcl2KUhez)fp_b$CwBhN`29cLPAq3k>F=oK6pv}2^!D-E-+p7cbn zmeTEp2%5%3b{baq+qB{~mKYOG@3>8Z(R|~F!{7T<$bQLe{7%m}p(cotHV{eNR22=! z7ddu)gz-F0SpB)Rm<TFe){*}mYO6>d-n?$yVXp}k6<)m|Ne!FU`&hkha+Gqv?DIE@ zp~%toZG!ZKv+oEq5M;}cM;WP8Uhyl0Q>Vzs<5=V(2}dsut@RvX%*!AI|Evp*l5($L zw&vJGtWAvBT$Q|L%u#v%8Z^i{ro-xaSl+)0S7`=Qj@7sYg$A!b-Ht*w>trj5_VI5r z5sLcNN<(0B_p4eJf|j99Ho~*l?t0@Yy)_=$-B&br6jcXmsL2f6#C8&n+Yq<<XblXy z>H(~{#P|1uOZ$V;&pMC^^SF1fYS$`V48+^d2`U1W91W!0S8%%r=I9ShrnsF=jI|Z= z1=1R(Gl-km?EYE$C}(PnCUL5b)woiY=`b<yHi+}r?{tbt)mYJomWW}@XTN>DpsA$A zU9-<*vEKb`AV1oMre}b5V8WGHkfhf<bAVz%egO4xv%7nkeAz#%fpQe7Wt+B%B@0a! z2PtvZpb$4sG7E#O+-(e6q4f91iI6Z`-~0@hKOZ=Qs9XA#YZgALl)dE(nwi>_OBLZ{ z^eqj1#ETjQ`To0Z10#U^X4m49NC2vMkOJ;LzFA+|@fC;(p<wrvF~A)ju!GQ4pT>r_ z_OLoXzA84uP76bAjq9v?L{*Zi=P;3-jrhVTZuB8H#Qbk23LK2aWAiU*QfjJgzX7#& zQsWT}2D?J%_fr21<;CvZ%k##ps{DI!^;-P@wkj}W1Z5?uAXl>}yW`q)o3XAP%({Tw zg@J^G^Z^=_M9-U5jo*KUx{vuhX0vxOsODN-$^`)aXSSPTAI#p>O>U6M2mA@(!p2s2 z0DsDK8_*bZemXXdQGr4Mk4~c2s8w%00SD4BmEdv1vVRXK52HZ6R++D}on?KEi<^4m zu3!xyl(QNjf;Nrx=eOHAgXUORSWj2XS(WW~w1CdPl{5xPoI|qg=Ct1#{+kPN`&1?+ zPe#a~G;Jhpomh&FIC#`ah}UVz$AU-17XozDx@-b(PwU;)qN3sk_%>IPi>uSZ;pu2z zA&0x0-JSho(Paqf-K)ECrr&8#DG&HcvpG;*P$*?szjJAY%U-KQrijqhI%_f0MQ9p3 zdLo3BhS$hUIck&;3@3d0ff5<BawPO*Wc?Z^t@k8-uZ$qM^JGUXT#|;Bo;T81`RaX! zu`&lffwe3-=D?O3M}~TLGS6AT2#@8G30wpfD>r*$iYS(Li41f|aA~dfVE@K8s{ixb zJNRFtOw3=}p%O1H<5xD`v&q^n1D$TRW~$)g1jT6a^DoK)9+xfEf-&Xt({DP5R1UsM zB|lNn&{E#&CYb&GQl}SM>W1R3`NU$5+O-h{lq_M$LaUccq`Cc4>i`ge#48-Gj~0vk zbMOp2g9u{7&6TC`>C+Gv8ypN<?~ht!{*`O2XIN(6<~YyaA9s){3f@uzTKFmn=of$k z@zy&m`@{FytoHh?in!KqH*+>f?YHaYX<^qpYfEp{C&>$?idziSx0=m{8jWcBT>9ho zdAI4`Q+hS^weBu{yHApdryt*1vf6Cyu4hFi54=Bi2&I-MSgqp{Oduu*V~+mUmc!|g z%!VJkv)BUvOEI06uoWTMmd4X`#fV728wC~<A0v=apLcD5MA7Ka2BK7j@`!bbtnp|K zdzErQ_;<AutY7gtfnx<i0M(??>d6TPJn?&99qfKKR8q>lSp;mB$0|gpTp|PxmD%^k z(HH1^H$WH%>H&3{9nfN8Bnnis`s0XIA0EeLnVM`>y}j=acRPWe=ed<($?SPzBo0I3 zccB~_9-d!Sg^`_|t#A$GAJq5n-~S#Q>;a-s5I~8yI%;aK`T6-B&o-ndf2bn^)F}e+ zs{6sr>P1p@b@hu{5+m^zD6YYSX-t4HfkCopVL)0W)@yWxnw_1!0eb#syiTo!{2-hQ z)#mp0dZGR{H5FAJ;3PochvT%HGkbc+=u5h`_CvV%ylbpL(uf(~EV4-^1>;3l*%^DA zdWGBz5YC+29)-{`_0{om{GcY|;F^P(8706ajvK#?+3=~Lm=u|M)uSaPEU3?r&oGH` zP|2l#5B(8am$)YHTqgZEU0w^*sG_&rWQh)P6me>jZF99wxp2?jB?bXOa6W|q8qou` z<*)@Eb+)(LJ{fHd?b#Vp)pKXgZ@~aef>?s7b(7Wob(mO*5CV=Qpk`C){b_<#>FiOB zwpVoR&J&fa24g*&r?IUT8U@{t9(st}7wq%r16D9V(*s7wbz{<;4uh050`5|E$mcil zB{qDii>oWj56yUZqa}4*eEfHkO-iLx-_=X0lajCi5DR*|zow&Td;wv<VhI}^SD|(4 zZ6ovZDPG7yFG~mL39tsW+s$)|cYbo)|3}WsiUs7P4+RpjuOUk{=ExV`ZG+xr6fJHK zi*dsBVwiITNVR_VS5f-_Ouk5qc#L}AG4f!bp*Q&HfVPK5%&Ug$26ng(0%mlUX6Uc{ zdA`Oxny7EQrzZr!Lsu+Cod$b(At50eOjDpZUYwqiOFsdU4@)LF;998P;*Kd&rBWp0 zJSj|<B@~cd_i?%=a@c*XwoX9N)u)?U(C2#-yW4wtYHaLeY<w)-?#am_g<~O;4ad7z zH{(pBX(fZHKpRSjN_l*vMHMJaE^IqCN5pO4E7|i#uMP>FlxJw!<8Y%HbzdqefJAVp zYDY>VHqvBj=AA}ttg%>~)>E|ylXQ)DtWHdnVpXA-gr=g2>!lfZvDla7J3VN!75^$n zjV*-F8Kr#crd@38awK$8yw==hv~m*PZWMA)>a^GKhHaar(8f*!v9d4izC$+Y!EpxP z-7CM63TcxcP9w_ngAxZwY|eXX=LT!3<$TK9gbG;>_-%e7J4MJ_HJe)>0xt>qe}DGA zo)xnyXW}3r{lUTegTsP_m%}Y%!ZU%AV}DXQ5e8pp7cgAg>544=El}dN|9<TUYpt8j zQY?mfcd<KB6g8`XIma^04e>w!%SAZ=Iy>*gcE(L|bj5dooz;DnT0knz2gGm(h^+p% zn|P29MKUR)pc7iA*MtQYR_XIIXm*U%ebjt806GYW!NI{Np#5aD@jDUFvSd?}SFo_T z7Jt9&EVc0g3UD$&lamX)XlJqn8<)u-2K4PnfneDK?uNy<8@9KvZ*`EVL(Im877H8u zW!@K_fi7@?(d@P#4mu4*Qb;SamN_YwT;#BVj~A+Hl?KE>#tDI(9yToJ0~HOQ%>o6N zK_^rqmcV!@okgq8hU15NbeMsI(o8tDe0He+<6YjgYFia>kx&ST>anZD`k5Lx<nf6K z7Oyok*S!mTjf#g?h5`2+wCX=X$4CQ$(Ie1$N-id}YRsyg^=I}*jS*YkO4CNqFyuM) zNHAx}rFS?AayraHr<mcisVk(OSo#QstmT`Ce`qnM)1bJXb3-9y#a9oe1LUmZmjj=B zp3Rh_@9D18g-->S#js8wO^cgE)*J`3%RlI$8!y2h;SsA7@j{&|9)^9vVS{7Gn+>OX z0XdQ?CPYv7dq!p!S#?^WLB&1-Pz7V3!lDC&6^5zIEDb-T4IiF%B`CW~$eaHrE2V1k zs{Lj)(fsPdTR<U;H#R-}-RFaPDBp`ytB2cd<JRk?7JMOpXk11;Siq=IF+4VUB3 z3n!aOFAPZ6=>SbZwd1M?B{ek#-9Abv#>)Z%gmVIv7t_8d9ICk6z(B~wG3Y*9GUGFw z|9Sli4;29+;o9u}_BKyE8rSo*56@}+7pm<-qq0)~;7D2ARR)#)KqY(kjE0Wx;a#CV z_ii9Tj~d>7q4A~3@FF>Mc7B-kG|MsviHOE!B{!Fh00l0a+erj-Opu2s!@DiJ#p5`Y zhgllHBMHWdLTPNCFX5EZtzPHU*9Wtv$cIQ(0R2%8cr5#+L2k}RwlWq8q}tiv{!1Vi zeZA0RGxfvy!O*9mU)P~SJn7(H`B&NXsin4nD$rL=38qtC&)YhG92$F@?X$`wA*RmJ zpDySh^AyxRdFwsauh{<!o&6h#;)=zV9m9e6lEI;%9+*<t8WkxFx(IcPQc0a8N+E(r zOi>C^uZwgZ=>FVmcoquIB+RLN{5N=izu#y{^l6%^U2;p%^q$B2`N*>SUL0PtnkMf# zI_)_>aeEP%CadCqRf~_TJGPuFaa|f3G_^Gm1t-FJu1;fk<bIrE6s!@}T)V*B96rmN zIcHhKe6s80_{hb^#FS$^c8O1r(LMU9x%Id!4m2<II*bWJdTgqlrBI)iwOrC?rs4fN zJO7-bl)dgRnXu4qG(npfS72i}WM?w0mzK<lyG_bA5SA<P=okvBBk`AEv}LgnSZbn^ zJ_G2ch|+qdc3ai?yS|U;zd$IMAxu$;SPBRak_?b=?B_q>5EJWv!<4O@uC<%5-()pe zZ1qy@3X;tS-S3CGsu~cXqM#poGO4O)42b(nHUYUN6o*b@Wi^6SW9JQMKn$ib)QY`f zp8(xO$D0#lO3<&$456&IU!+Z|mUuU6Q}<n?oB$|0FAbrcQSzpkw6wIc^Ccv=!#SL{ z5;2`XbKI=TuCvK7l?PXqJ4M+)`;f(3S8X*$QB(^TD4k5b`uyZTpS?4OqgpI48h<3< z_;}|=uU&%=l*|Z9X{~A#9u&9`+uyw27YG0b2K9!Dg&o<%8B*n5)K=lw(l^g6+@6~W z%+@O$cxqsd=6%$BjkkMP{|3p-un{6n#k})~KK4W0#h3ern6kIOK*E^<8u}qICkLGz zHnp%qV!EF%*WsAvR4smZ#$$!K{&*&K)+KGt!XPOBZ}*zMNcw20r6mHnQjrXm?{h4V zn4??_4~fpPWwYro#q-x_ti=;-e|ZbcdG_?&IsG5q1aO(8)ww;EWIjlLG*jJgs2T4L zLp}w;3F<O|^HNs`yzHdU;VzK2tR}w2s<xY|4U7oh4`HQD@Y|DmZD3B8YN9i>-{eyu zp%}$&m@wnN_KH)cLnr3lV6{&@FG*|I`TZiz=ry|{0+qW9DB;Q-{(dj$4=DjUA^zvj z_Rj^z9}33abqA*YtT0FAPfboPfZ#z6=IW3Eg`vNOSCE$Oih0A901yUEwx<ZLDL?<u zGs)@(Se;#v?HS?64|r->EQTyS_eu<;^y^W|b?Un>-b^Sb<e;Y%CiOA!bx677yv7qQ zof1)zc6TSxl_HA$B}%RX^Wo~&7GF-HXmie{FzK_#&cy}FYg`;YPZua!>DUsXIML*L z!nXo%v0I*J;_dj{*CL0BF$q*&i6l8*+(`dCoJ1y`7l`?W&M8s=_r9@GS)ldiVPfZQ zBbwX!qL4z30XA2~dbHr)l$k*OQ(V*sSGCYAE2|G7cW%lB5?G*TPqB>-ct<qmpc!U? zJaYy@@s2-ZH?<O{&HGC2{$vh=x+yF>V%;s4_cC=Gyh$MC0i-!d&*gn#6^8k7rpoxG zW7O=r3k{kckR{OGkYP8OUC-kmX)}l5;o+J7E7SHoteZXoRc=6UHZhJ=2n}NOuPlS2 z189ZcwQH$CHs2iod?ZDqm>mkVN(qT@9+g6358wUrhAPn9bZ*lFdlpg|^^uZ1A5QxZ zQ;7l#B>(0vHn|l4b!8elt-8C~jc)U~ZqgHM1`;+1n+VX0TA6~X6akHjUopFZ5LVW| zEU91kN5!0e7&$sJWBs66x!6_3rGdkyln$0CV7ZP+P<s1bd-cZn(Bs}4BK<Eutml0| z5+#{*+|wA=kN*C=fydZt>p=(4-KmD5TESN&){9tq<Xhe?9*3V~goW{ioZu{mbReMc zaKT;l3^H9wM7WnbU1)ttc58Gig~ueoikWpuUHR)F@jKN#$@5ld#AM^dWAuL49{-`M z|6NA4j;UNr_czl6QeL~^Dg`~r$%kb4DvQ55JRM%=xR5{qBR>x?(*pb*RR#9;ytJc1 z?<2}``8}<NmiEVo#d^E>way@znHG;q*)dbF1I%i?5D^5<D+dRM(6BJ$t)UE{Y)0X? zo6F;$Z;wcpYLqiujgq~HumJuV`d#9{p%PH~)N9d%fF2@W-^%65Nhb(EOdOmr5PIuC zh5z*FQ^G_fHq8lOg$0T^f`FcJfqpL_>C9Kpzf4ARg`>2Fkw)mqnXS(#rIJFg;XD3A z@C0ZL0?W$AR&Bm-!GB|<>U;8}<mu%@PEU`59gq&o#Kbg|%|{s6d3!#qRHEj2S7Hev zPf#glT=HILpn(i_P#I$v93~gU*HUU%NY^;^5s2z0!Ga67wzi(0Mf)i?D9Bs=B=|l> zFj<xu+5q1kEI8sCp;I0{U>3YYA+FcvjVdAqyc(>{MxiH=sMktpNZ}zvx{V9gNxDBb z@bF_LE_R;q0aqjDs|xiT9qx~ea)$L(kk=0fJ?hrSf4VyhO>AnkI7cm&EMP<1$8<UB zhl>ftfKozpz~~_J<j@*FfPkZ-qLP`^CYjdI&@jjf$l#erE5qAVjuD$+Qf|lGOiPDe z=uTk9bFfM0Y{34X(iZ?ji;9bjZF^ZW%xU@tf+=si;7NZM_iE=@miKs5$4*(93sj5| zHDAz#VU_{_QbYg;1bS7Ky+08O+Ob5Gw^N#i190@Ur!p$u243Hr9G(Shh3!W9E-uFZ zkZ8WY-2ZKCeYhMj8)c3XiD0ZGMW*}Hei(F@W_N^>cHe9<7Z&u#ScvJt#*+yBD(H`6 z<z)#Ulb*u=`nrE+W3No(ZIBa3GQJ^Q#%Z06b7fJy4VTSOX!Coy@4E4bZhLHb3NX}@ zcE9IhNjAW)H)kpBg0bI#W0BlV*izn`E(_Q1o=`FwHrXH|>J5S8F7FmD=s9i26UU}V zS7s0=HlL*R>%##6+I?e*PqLVhmk7#zVt2w1H*Km`&JfX$PK(~>t0s?6YzeBxUq_H^ z&K))H;KU}Tg@OhB)fon*^Df5K^NKyp|CKs$nhj^P1nP`H_(W6x(v`Yw)4Z0TmmUYn z!@lNp;EovVh=B**O(+cZaRJVt$*5S?Q4_-s{QtaWE`l_55PKg808D8#sRC$+s*y)@ zpsy<iVyGHy7}6f@IBvgJYN?-XG!>{Q1XWi`LE%@KcCDEr4u~yR&_)OSXJLPTLHFaO zSWu{cyMf&|uK~kPogI_o%|a9Kx#|UNvnq!iZQsj_3o!s2lmN*GP6YOu!GJEF8hxP9 z-A=)Gl_DgN3B!OawgysVA4sGLU_%4guGErQ4eGcroQjbV*<6D|{1=Xo6ih<sVBcu3 z!@R$XnsMHY0A-+;%XWcZ%hjh+160uW((2V=n?5-`?JKY&75}SKmynYa-*$gxbe_s! z;XpS~c2BLQ_@Ov1UbuK-btNxkrqzv&x9&Lf5&n98=d{3Tx?Ug@L#u8}bCY~o<8;<J zN~HFiJSG-al(?*_aH*g*X`~9m&HZhjX^SK#2}#t!0rHJqKgq^6POfA_zvG@OwTfn0 zP-Q&&oWMAea^fm8evA}fN}S=eo$%6M=!8&-a*1dQbTYC|bWN8^ATprSOpI5%Obe#V zNzC@o(n?HADST*a=5SnD!9;+X{H{z4%+%Kx&6CPX-Bfnz;J~DKv9t6_GM>2KVLkx9 zteI6l6;+yAOhO`8{;P&otws6JA%ud06&k(4I;6K3*381f7+?mZ`vI2`fryI>*D}M7 zb~UuQT1&-*UcK7~YD@2pL`jS{ZzA8YS#a;x0Sy84^BIOSc|w4&lLxr}*(q~{73czU zJFUS2qN!?g;^{;5#8+?qd6RNihTR3{Y|3f565~^ReE(D1eYJ0&Ge6*RHDkY#j7o28 zYDwmMjXv^QB7CSR+twMB5@96`F)3F}IzZ9aC`f~yv9n>8{QPtG*HuMQ4IkBEuboc) z8{W_{@>gZTZ0{V9e>Q3cZw+)EIgF<c{ZrdVqa^%fd~26K1}!n~ASsH=U|u$lULKgz zK+}z6c5g*`MQ$mJKm+X|78ih5B@5eX{@&zSSWH4(B#F}Zsn0U%WB2>X*jkU=s`&5Z z5zRI8*axp|;Qt&3U;W6ZY?1uk1zo0lZgiSbUpEM?7hy$AJ@+PgqudY8*w{LH+;}Mj zIqa)x$^63~BTUzRF*lgTwUP}o4?d5lIKWj+{vBw)lpxiGQkAjeKr3UKg86?shXsz@ zzb0yyC&_GE{K6d5@hR_fM=VCQO<Cu|{wPa)dtGluc=h$rSo7ceP*fuR^0GkzD)}(? zIv(*EjA!?}llnJtx}okwJ&a;jK9AFa*(vfr!$NlG=uK*Fxk6{L=tKWFGiI0x?v8}r z&`U#$sB{Uk7EzYam(8LWc|{}=mG=xM(ZS5<kl-fH;;QuDeGO&hr?;aa`<-8-URM8U zj2eqw`$BV+;+6o%$M3J(o6Tja$kF;|1`76}uG0ky*H=t$7tdGPaJGE;)*6*0KK;Dr zO>(nW*6}INXL>!4ot0A<^NL}EGn#dN$CXm9<d}-=33YiMbtPb_|3TN%4Bm*BkBA4h z)oF<C^hRF!kJ##7lt6<scZ2k2(f38`Ij&xb4IHbdakPE*XueF=4Q3^zDMiZ<T#B6L zRqo2TU(FEH{+u3}4fy5pw+z{v1g@W=DO^{>t}M3~_OQ0B8Bp&U-Ywn8s^B;{<yQan z<!!-;a{kxf!8$MlFYjTGg_HZ!eEdkTukc-e<hLHm+)QS#`790Z;t6nrZx?ytSIYnG zIC=-RR@k6x@m80d87qH|9Z8xr+(sO#zuGq=qsYQ9we569xV3?)9e~qFwa_vdV0Pnn zzqsls)`fqXR@MGNuAd3n^3+KG$k?qCLAv|9ZU^OJe1^@MhI4{(sI&+v88J{Aiq(gs zXSlo@T8lU98JYIndYXB2)j}yVMeLsKGtmf?`=fIdVxb7N4QSfwkT>hCnQOy{d`3P* zTYH<uQ={)`4v&V=r<|z<8QkFZ`OLgV+*GojXPVHKUnZIVy8{P1ISW43_viNkoaWbS vwd;J`3hXkN3%6`z!bFvyBCiedp5g74bdM<SE7-uly+fqM6~rn;jDr6!SJI8Z literal 0 HcmV?d00001 diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 83fe27068..2a51240b2 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -82,6 +82,12 @@ <img class="sponsor-image" src="/img/sponsors/kong-banner.png" /> </a> </div> + <div class="item"> + <a title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI" style="display: block; position: relative;" href="https://zuplo.link/fastapi-web" target="_blank"> + <span class="sponsor-badge">sponsor</span> + <img class="sponsor-image" src="/img/sponsors/zuplo-banner.png" /> + </a> + </div> </div> </div> {% endblock %} From 653315c496304be928b46c34d35097d0ce847646 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 18 Jun 2024 02:25:32 +0000 Subject: [PATCH 536/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bac06832d..f3c84d529 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -56,6 +56,7 @@ hide: ### Internal +* 🔧 Update sponsors, add Zuplo. PR [#11729](https://github.com/tiangolo/fastapi/pull/11729) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Sponsor link: Coherence. PR [#11730](https://github.com/tiangolo/fastapi/pull/11730) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11669](https://github.com/tiangolo/fastapi/pull/11669) by [@tiangolo](https://github.com/tiangolo). * 🔧 Add sponsor Kong. PR [#11662](https://github.com/tiangolo/fastapi/pull/11662) by [@tiangolo](https://github.com/tiangolo). From 1b9c402643beaf22c6b1cb73159c9edae27d8086 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Thu, 20 Jun 2024 16:06:58 -0300 Subject: [PATCH 537/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/additional-responses.md`?= =?UTF-8?q?=20(#11736)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/additional-responses.md | 240 ++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 docs/pt/docs/advanced/additional-responses.md diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md new file mode 100644 index 000000000..7c7d22611 --- /dev/null +++ b/docs/pt/docs/advanced/additional-responses.md @@ -0,0 +1,240 @@ +# Retornos Adicionais no OpenAPI + +!!! warning "Aviso" + Este é um tema bem avançado. + + Se você está começando com o **FastAPI**, provavelmente você não precisa disso. + +Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc. + +Essas respostas adicionais serão incluídas no esquema do OpenAPI, e também aparecerão na documentação da API. + +Porém para as respostas adicionais, você deve garantir que está retornando um `Response` como por exemplo o `JSONResponse` diretamente, junto com o código de status e o conteúdo. + +## Retorno Adicional com `model` + +Você pode fornecer o parâmetro `responses` aos seus *decoradores de caminho*. + +Este parâmetro recebe um `dict`, as chaves são os códigos de status para cada retorno, como por exemplo `200`, e os valores são um outro `dict` com a informação de cada um deles. + +Cada um desses `dict` de retorno pode ter uma chave `model`, contendo um modelo do Pydantic, assim como o `response_model`. + +O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no local correto do OpenAPI. + +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!} +``` + +!!! note "Nota" + Lembre-se que você deve retornar o `JSONResponse` diretamente. + +!!! info "Informação" + A chave `model` não é parte do OpenAPI. + + O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto. + + O local correto é: + + * Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém: + * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo:: + * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto. + * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc. + +O retorno gerado no OpenAI para esta *operação de caminho* será: + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Os esquemas são referenciados em outro local dentro do esquema OpenAPI: + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Media types adicionais para o retorno principal + +Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes media types para o mesmo retorno principal. + +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!} +``` + +!!! note "Nota" + Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. + +!!! info "Informação" + A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). + + Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado. + +## Combinando informações + +Você também pode combinar informações de diferentes lugares, incluindo os parâmetros `response_model`, `status_code`, e `responses`. + +Você pode declarar um `response_model`, utilizando o código de status padrão `200` (ou um customizado caso você precise), e depois adicionar informações adicionais para esse mesmo retorno em `responses`, diretamente no esquema OpenAPI. + +O **FastAPI** manterá as informações adicionais do `responses`, e combinará com o esquema JSON do seu modelo. + +Por exemplo, você pode declarar um retorno com o código de status `404` que utiliza um modelo do Pydantic que possui um `description` customizado. + +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!} +``` + +Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API: + +<img src="/img/tutorial/additional-responses/image01.png"> + +## Combinar retornos predefinidos e personalizados + +Você pode querer possuir alguns retornos predefinidos que são aplicados para diversas *operações de caminho*, porém você deseja combinar com retornos personalizados que são necessários para cada *operação de caminho*. + +Para estes casos, você pode utilizar a técnica do Python de "desempacotamento" de um `dict` utilizando `**dict_to_unpack`: + +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Aqui, o `new_dict` terá todos os pares de chave-valor do `old_dict` mais o novo par de chave-valor: + +```Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos nas suas *operações de caminho* e combiná-las com personalizações adicionais. + +Por exemplo: + +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` + +## Mais informações sobre retornos OpenAPI + +Para verificar exatamente o que você pode incluir nos retornos, você pode conferir estas seções na especificação do OpenAPI: + +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject" class="external-link" target="_blank">Objeto de Retorno OpenAPI</a>, inclui o `Response Object`. +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject" class="external-link" target="_blank">Objeto de Retorno OpenAPI</a>, você pode incluir qualquer coisa dele diretamente em cada retorno dentro do seu parâmetro `responses`. Incluindo `description`, `headers`, `content` (dentro dele que você declara diferentes media types e esquemas JSON), e `links`. From 33e2fbe20f8aa8b82cad405679bf71704c7d280f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 20 Jun 2024 19:07:28 +0000 Subject: [PATCH 538/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f3c84d529..aa7a749fe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-responses.md`. PR [#11736](https://github.com/tiangolo/fastapi/pull/11736) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/benchmarks.md`. PR [#11713](https://github.com/tiangolo/fastapi/pull/11713) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/response-status-code.md`. PR [#11718](https://github.com/tiangolo/fastapi/pull/11718) by [@nayeonkinn](https://github.com/nayeonkinn). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-data-types.md`. PR [#11711](https://github.com/tiangolo/fastapi/pull/11711) by [@nayeonkinn](https://github.com/nayeonkinn). From e62e5e88120167e2dbc1cb0ca6c60ef8e8cb2516 Mon Sep 17 00:00:00 2001 From: Victor Senna <34524951+vhsenna@users.noreply.github.com> Date: Thu, 20 Jun 2024 16:07:51 -0300 Subject: [PATCH 539/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/index.md`=20(#11731)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/index.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 docs/pt/docs/how-to/index.md diff --git a/docs/pt/docs/how-to/index.md b/docs/pt/docs/how-to/index.md new file mode 100644 index 000000000..664e89144 --- /dev/null +++ b/docs/pt/docs/how-to/index.md @@ -0,0 +1,11 @@ +# Como Fazer - Exemplos Práticos + +Aqui você encontrará diferentes exemplos práticos ou tutoriais de "como fazer" para vários tópicos. + +A maioria dessas ideias será mais ou menos **independente**, e na maioria dos casos você só precisará estudá-las se elas se aplicarem diretamente ao **seu projeto**. + +Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo. + +!!! tip + + Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso. From b7a0fc7e12b850bf937f705a473f6c70d9b26137 Mon Sep 17 00:00:00 2001 From: Benjamin Vandamme <6206@holbertonstudents.com> Date: Thu, 20 Jun 2024 21:09:17 +0200 Subject: [PATCH 540/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20French=20translati?= =?UTF-8?q?on=20for=20`docs/fr/docs/learn/index.md`=20(#11712)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/fr/docs/learn/index.md diff --git a/docs/fr/docs/learn/index.md b/docs/fr/docs/learn/index.md new file mode 100644 index 000000000..46fc095dc --- /dev/null +++ b/docs/fr/docs/learn/index.md @@ -0,0 +1,5 @@ +# Apprendre + +Voici les sections introductives et les tutoriels pour apprendre **FastAPI**. + +Vous pouvez considérer ceci comme un **manuel**, un **cours**, la **méthode officielle** et recommandée pour appréhender FastAPI. 😎 From 26431224d1818523ecbd59a1a04ed3973457d2cb Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 20 Jun 2024 19:09:46 +0000 Subject: [PATCH 541/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index aa7a749fe..058f199dc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/index.md`. PR [#11731](https://github.com/tiangolo/fastapi/pull/11731) by [@vhsenna](https://github.com/vhsenna). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-responses.md`. PR [#11736](https://github.com/tiangolo/fastapi/pull/11736) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/benchmarks.md`. PR [#11713](https://github.com/tiangolo/fastapi/pull/11713) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/response-status-code.md`. PR [#11718](https://github.com/tiangolo/fastapi/pull/11718) by [@nayeonkinn](https://github.com/nayeonkinn). From 85bad3303f8534f3323bddcdc5acf169a558bfeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph.dev@gmail.com> Date: Thu, 20 Jun 2024 16:10:31 -0300 Subject: [PATCH 542/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/settings.md`=20(#11739)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/settings.md | 485 ++++++++++++++++++++++++++++++ 1 file changed, 485 insertions(+) create mode 100644 docs/pt/docs/advanced/settings.md diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md new file mode 100644 index 000000000..f6962831f --- /dev/null +++ b/docs/pt/docs/advanced/settings.md @@ -0,0 +1,485 @@ +# Configurações e Variáveis de Ambiente + +Em muitos casos a sua aplicação pode precisar de configurações externas, como chaves secretas, credenciais de banco de dados, credenciais para serviços de email, etc. + +A maioria dessas configurações é variável (podem mudar), como URLs de bancos de dados. E muitas delas podem conter dados sensíveis, como tokens secretos. + +Por isso é comum prover essas configurações como variáveis de ambiente que são utilizidas pela aplicação. + +## Variáveis de Ambiente + +!!! dica + Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. + +Uma <a href="https://pt.wikipedia.org/wiki/Variável_de_ambiente" class="external-link" target="_blank">variável de ambiente</a> (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas). + +Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python: + +=== "Linux, macOS, Windows Bash" + + <div class="termy"> + + ```console + // Você pode criar uma env var MY_NAME usando + $ export MY_NAME="Wade Wilson" + + // E utilizá-la em outros programas, como + $ echo "Hello $MY_NAME" + + Hello Wade Wilson + ``` + + </div> + +=== "Windows PowerShell" + + <div class="termy"> + + ```console + // Criando env var MY_NAME + $ $Env:MY_NAME = "Wade Wilson" + + // Usando em outros programas, como + $ echo "Hello $Env:MY_NAME" + + Hello Wade Wilson + ``` + + </div> + +### Lendo variáveis de ambiente com Python + +Você também pode criar variáveis de ambiente fora do Python, no terminal (ou com qualquer outro método), e realizar a leitura delas no Python. + +Por exemplo, você pode definir um arquivo `main.py` com o seguinte código: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +!!! dica + O segundo parâmetro em <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> é o valor padrão para o retorno. + + Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado. + +E depois você pode executar esse arquivo: + +<div class="termy"> + +```console +// Aqui ainda não definimos a env var +$ python main.py + +// Por isso obtemos o valor padrão + +Hello World from Python + +// Mas se definirmos uma variável de ambiente primeiro +$ export MY_NAME="Wade Wilson" + +// E executarmos o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +</div> + +Como variáveis de ambiente podem ser definidas fora do código da aplicação, mas acessadas pela aplicação, e não precisam ser armazenadas (versionadas com `git`) junto dos outros arquivos, é comum utilizá-las para guardar configurações. + +Você também pode criar uma variável de ambiente específica para uma invocação de um programa, que é acessível somente para esse programa, e somente enquanto ele estiver executando. + +Para fazer isso, crie a variável imediatamente antes de iniciar o programa, na mesma linha: + +<div class="termy"> + +```console +// Criando uma env var MY_NAME na mesma linha da execução do programa +$ MY_NAME="Wade Wilson" python main.py + +// Agora a aplicação consegue ler a variável de ambiente + +Hello Wade Wilson from Python + +// E a variável deixa de existir após isso +$ python main.py + +Hello World from Python +``` + +</div> + +!!! dica + Você pode ler mais sobre isso em: <a href="https://12factor.net/pt_br/config" class="external-link" target="_blank">The Twelve-Factor App: Configurações</a>. + +### Tipagem e Validação + +Essas variáveis de ambiente suportam apenas strings, por serem externas ao Python e por que precisam ser compatíveis com outros programas e o resto do sistema (e até mesmo com outros sistemas operacionais, como Linux, Windows e macOS). + +Isso significa que qualquer valor obtido de uma variável de ambiente em Python terá o tipo `str`, e qualquer conversão para um tipo diferente ou validação deve ser realizada no código. + +## Pydantic `Settings` + +Por sorte, o Pydantic possui uma funcionalidade para lidar com essas configurações vindas de variáveis de ambiente utilizando <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>. + +### Instalando `pydantic-settings` + +Primeiro, instale o pacote `pydantic-settings`: + +<div class="termy"> + +```console +$ pip install pydantic-settings +---> 100% +``` + +</div> + +Ele também está incluído no fastapi quando você instala com a opção `all`: + +<div class="termy"> + +```console +$ pip install "fastapi[all]" +---> 100% +``` + +</div> + +!!! info + Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade. + +### Criando o objeto `Settings` + +Importe a classe `BaseSettings` do Pydantic e crie uma nova subclasse, de forma parecida com um modelo do Pydantic. + +Os atributos da classe são declarados com anotações de tipo, e possíveis valores padrão, da mesma maneira que os modelos do Pydantic. + +Você pode utilizar todas as ferramentas e funcionalidades de validação que são utilizadas nos modelos do Pydantic, como tipos de dados diferentes e validações adicionei com `Field()`. + +=== "Pydantic v2" + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001.py!} + ``` + +=== "Pydantic v1" + + !!! Info + Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001_pv1.py!} + ``` + +!!! dica + Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. + +Portanto, quando você cria uma instância da classe `Settings` (nesse caso, o objeto `settings`), o Pydantic lê as variáveis de ambiente sem diferenciar maiúsculas e minúsculas, por isso, uma variável maiúscula `APP_NAME` será usada para o atributo `app_name`. + +Depois ele irá converter e validar os dados. Assim, quando você utilizar aquele objeto `settings`, os dados terão o tipo que você declarou (e.g. `items_per_user` será do tipo `int`). + +### Usando o objeto `settings` + +Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: + +```Python hl_lines="18-20" +{!../../../docs_src/settings/tutorial001.py!} +``` + +### Executando o servidor + +No próximo passo, você pode inicializar o servidor passando as configurações em forma de variáveis de ambiente, por exemplo, você poderia definir `ADMIN_EMAIL` e `APP_NAME` da seguinte forma: + +<div class="termy"> + +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +!!! dica + Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. + +Assim, o atributo `admin_email` seria definido como `"deadpool@example.com"`. + +`app_name` seria `"ChimichangApp"`. + +E `items_per_user` manteria o valor padrão de `50`. + +## Configurações em um módulo separado + +Você também pode incluir essas configurações em um arquivo de um módulo separado como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +Por exemplo, você pode adicionar um arquivo `config.py` com: + +```Python +{!../../../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!} +``` + +!!! dica + Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +## Configurações em uma dependência + +Em certas ocasiões, pode ser útil fornecer essas configurações a partir de uma dependência, em vez de definir um objeto global `settings` que é utilizado em toda a aplicação. + +Isso é especialmente útil durante os testes, já que é bastante simples sobrescrever uma dependência com suas configurações personalizadas. + +### O arquivo de configuração + +Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: + +```Python hl_lines="10" +{!../../../docs_src/settings/app02/config.py!} +``` + +Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. + +### O arquivo principal da aplicação + +Agora criamos a dependência que retorna um novo objeto `config.Settings()`. + +=== "Python 3.9+" + + ```Python hl_lines="6 12-13" + {!> ../../../docs_src/settings/app02_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="6 12-13" + {!> ../../../docs_src/settings/app02_an/main.py!} + ``` + +=== "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!} + ``` + +!!! dica + Vamos discutir sobre `@lru_cache` logo mais. + + Por enquanto, você pode considerar `get_settings()` como uma função normal. + +E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. + +=== "Python 3.9+" + + ```Python hl_lines="17 19-21" + {!> ../../../docs_src/settings/app02_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17 19-21" + {!> ../../../docs_src/settings/app02_an/main.py!} + ``` + +=== "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!} + ``` + +### 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!} +``` + +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. + +Após isso, podemos testar se o valor está sendo utilizado. + +## Lendo um arquivo `.env` + +Se você tiver muitas configurações que variem bastante, talvez em ambientes distintos, pode ser útil colocá-las em um arquivo e depois lê-las como se fossem variáveis de ambiente. + +Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv". + +!!! dica + Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. + + Mas um arquivo dotenv não precisa ter esse nome exato. + +Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>. + +!!! dica + Para que isso funcione você precisa executar `pip install python-dotenv`. + +### O arquivo `.env` + +Você pode definir um arquivo `.env` com o seguinte conteúdo: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Obtendo configurações do `.env` + +E então adicionar o seguinte código em `config.py`: + +=== "Pydantic v2" + + ```Python hl_lines="9" + {!> ../../../docs_src/settings/app03_an/config.py!} + ``` + + !!! dica + O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. + +=== "Pydantic v1" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/settings/app03_an/config_pv1.py!} + ``` + + !!! dica + A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. + +!!! info + Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`. + +Aqui definimos a configuração `env_file` dentro da classe `Settings` do Pydantic, e definimos o valor como o nome do arquivo dotenv que queremos utilizar. + +### Declarando `Settings` apenas uma vez com `lru_cache` + +Ler o conteúdo de um arquivo em disco normalmente é uma operação custosa (lenta), então você provavelmente quer fazer isso apenas um vez e reutilizar o mesmo objeto settings depois, em vez de ler os valores a cada requisição. + +Mas cada vez que fazemos: + +```Python +Settings() +``` + +um novo objeto `Settings` é instanciado, e durante a instanciação, o arquivo `.env` é lido novamente. + +Se a função da dependência fosse apenas: + +```Python +def get_settings(): + return Settings() +``` + +Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo `.env` a cada requisição. ⚠️ + +Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ + +=== "Python 3.9+" + + ```Python hl_lines="1 11" + {!> ../../../docs_src/settings/app03_an_py39/main.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1 11" + {!> ../../../docs_src/settings/app03_an/main.py!} + ``` + +=== "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!} + ``` + +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. + +#### Detalhes Técnicos de `lru_cache` + +`@lru_cache` modifica a função decorada para retornar o mesmo valor que foi retornado na primeira vez, em vez de calculá-lo novamente, executando o código da função toda vez. + +Assim, a função abaixo do decorador é executada uma única vez para cada combinação dos argumentos passados. E os valores retornados para cada combinação de argumentos são sempre reutilizados para cada nova chamada da função com a mesma combinação de argumentos. + +Por exemplo, se você definir uma função: + +```Python +@lru_cache +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +Seu programa poderia executar dessa forma: + +```mermaid +sequenceDiagram + +participant code as Código +participant function as say_hi() +participant execute as Executar Função + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: retornar resultado armazenado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: retornar resultado armazenado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: retornar resultado armazenado + end +``` + +No caso da nossa dependência `get_settings()`, a função não recebe nenhum argumento, então ela sempre retorna o mesmo valor. + +Dessa forma, ela se comporta praticamente como uma variável global, mas ao ser utilizada como uma função de uma dependência, pode facilmente ser sobrescrita durante os testes. + +`@lru_cache` é definido no módulo `functools` que faz parte da biblioteca padrão do Python, você pode ler mais sobre esse decorador no link <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache" class="external-link" target="_blank">Python Docs sobre `@lru_cache`</a>. + +## Recapitulando + +Você pode usar o módulo Pydantic Settings para gerenciar as configurações de sua aplicação, utilizando todo o poder dos modelos Pydantic. + +- Utilizar dependências simplifica os testes. +- Você pode utilizar arquivos .env junto das configurações do Pydantic. +- Utilizar o decorador `@lru_cache` evita que o arquivo .env seja lido de novo e de novo para cada requisição, enquanto permite que você sobrescreva durante os testes. From 06839414faa57d03315d585bd80747e4c800203c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 20 Jun 2024 19:10:49 +0000 Subject: [PATCH 543/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 058f199dc..8779938f0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add French translation for `docs/fr/docs/learn/index.md`. PR [#11712](https://github.com/tiangolo/fastapi/pull/11712) by [@benjaminvandammeholberton](https://github.com/benjaminvandammeholberton). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/index.md`. PR [#11731](https://github.com/tiangolo/fastapi/pull/11731) by [@vhsenna](https://github.com/vhsenna). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-responses.md`. PR [#11736](https://github.com/tiangolo/fastapi/pull/11736) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/benchmarks.md`. PR [#11713](https://github.com/tiangolo/fastapi/pull/11713) by [@ceb10n](https://github.com/ceb10n). From c26931ae1714ded8aae3fff5526183b5c0977d39 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 20 Jun 2024 19:12:54 +0000 Subject: [PATCH 544/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8779938f0..76ddef59a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#11739](https://github.com/tiangolo/fastapi/pull/11739) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add French translation for `docs/fr/docs/learn/index.md`. PR [#11712](https://github.com/tiangolo/fastapi/pull/11712) by [@benjaminvandammeholberton](https://github.com/benjaminvandammeholberton). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/index.md`. PR [#11731](https://github.com/tiangolo/fastapi/pull/11731) by [@vhsenna](https://github.com/vhsenna). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-responses.md`. PR [#11736](https://github.com/tiangolo/fastapi/pull/11736) by [@ceb10n](https://github.com/ceb10n). From 913659c80d25e9f4aa4404584f8a81a4fc24b481 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 25 Jun 2024 20:33:01 -0500 Subject: [PATCH 545/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20add?= =?UTF-8?q?=20Stainless=20(#11763)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/docs/advanced/generate-clients.md | 2 +- docs/en/docs/img/sponsors/stainless.png | Bin 0 -> 29572 bytes 4 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 docs/en/docs/img/sponsors/stainless.png diff --git a/README.md b/README.md index 1fb4893e6..35d0fad1f 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ The key features are: <a href="https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship" target="_blank" title="SDKs for your API | Speakeasy"><img src="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a> <a href="https://www.svix.com/" target="_blank" title="Svix - Webhooks as a service"><img src="https://fastapi.tiangolo.com/img/sponsors/svix.svg"></a> <a href="https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers" target="_blank" title="Take code reviews from hours to minutes"><img src="https://fastapi.tiangolo.com/img/sponsors/codacy.png"></a> +<a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" target="_blank" title="Stainless | Generate best-in-class SDKs"><img src="https://fastapi.tiangolo.com/img/sponsors/stainless.png"></a> <!-- /sponsors --> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 244d98a9a..39c51b82b 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -51,6 +51,9 @@ silver: - url: https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers title: Take code reviews from hours to minutes img: https://fastapi.tiangolo.com/img/sponsors/codacy.png + - url: https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral + title: Stainless | Generate best-in-class SDKs + img: https://fastapi.tiangolo.com/img/sponsors/stainless.png bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index fd9a73618..09d00913f 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -20,7 +20,7 @@ Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-autho And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 -For example, you might want to try <a href="https://speakeasyapi.dev/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a>. +For example, you might want to try <a href="https://speakeasyapi.dev/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> and <a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" class="external-link" target="_blank">Stainless</a>. There are also several other companies offering similar services that you can search and find online. 🤓 diff --git a/docs/en/docs/img/sponsors/stainless.png b/docs/en/docs/img/sponsors/stainless.png new file mode 100644 index 0000000000000000000000000000000000000000..0f99c1d32c6448dd020f4252a96529420841cbcf GIT binary patch literal 29572 zcmeFYRa9L;v@M7QC%C)2OK<`NcS3LoF5%!3AOwftuEE`%oFKs+f`kNj3+@mcy14JY zce_9O<9_r<k8v3zz+vxG*|ln|Ip>;HCtO`s4g-}06$S<dLqYzHCir;*{#hWyf$y(6 zS>nKtaBnSLH%-%zR8B6AR<;mJDmO1DODaoGTPqkC&v~PmC5#>}<lvR`eA<)ko~XAn zbx9b)zRsB}iXBKz(mVeD#<_R+u|3WR$WffucFT@&vIzUxhIu|s^-ZZL+Rlw6?&1tm z99-p#NZ5qNU{eHyVq|Ey99dc8y9$4|n)RVS&OKGC-6r!x+Ch7OvJ*O#3yi_Qpd#9W zhtgG17B+XZ=P<Q!G_&OJw08ne3j-r6;pt>*ZfEI6WoBt@>mWvR+}c4yWoscuqr<Pl zrQ#%QX=5wz?PB@XTUE>4+s<6bf<{6dRn$`$3}A2RW=iF04{>l6_7tP}k8y>;@6Uhc zq@ntcTioo#XmnN7siYlUEUEZ7_&B)OWjt*?cxc2?sYG2Ytb{e+$o}UL;FTDSjhma3 zFem57j~_Wc@^U!3SaWg<2?=p>@o@6+u!B3;UA-LKOg-5hTxp+&_+MkZv2-<ev2}8@ zb#$P59@Es!(cMjqh6Y@x`p?0i7vTSl?%?{LK>*?4e7?fT&B4X_f4|+$*6RP|_U9}A zb^G(1h1G36Eg`yZZ0#)_T)`uV(eUtb{l{Scbye^Gc9om!e_eeZNm#+&)Y?+V*22x^ zzuxv=7vwE%t!=<e{vU5qbFsAqF?gOWxI)AE97)dq3?*0@&i}JC&++;H{_B7KlmAwX z|0i7k6R!VO1pZq$|4(-PPq_YD5%_Q2{6E?C|F3YN{+GD3bO4I(Bam)}@a9)Q_QAVK zDQF=hBQLC}t-`=i!6>|u)bgCqY_m>F-ui}kFY37PDa|yL=R!bN-BuIN)(loAwyTth zrC&NsmOh^`Q=Tty;2*Qug)R+B3Q;8;sz8L<YuMc|z5rP4-8Mn=o`bfPe-BMLpO5=Q z7*?9wn}7TW75mh2$G)#Ou7A}s({}OraJL}{wKrfc`lhYe=Nz?Cz*NtMR%26j>WwD@ zwLizd=Z&E8RkR}yr4|qK8-`!ExfV2z+L*0pyH~KY*CSXS=k3bzWPsY=wa0Sy4V*@w z1)r*trL1h-wQqYllWmN8s$n50mI+3X&vc<&w;v0}XtJb^toZ~|by|KXa`hd99)fEF z;mJ222ArJ~O|d?V_`G2y?~C6MWYN}uIDFM)L6@F!?qOmxtcNCPYv8RJu#F6Fxm0h+ zItN#DzRO@mr7gm1CwWDU3^(I`s>G7Kt}}9u5;WnQWyrBTt6FKcP#;89OD=*8w@?q} zMlOObEk4JE&Tii~EXuq9J!N;s8({G;dX+dd3&P-mC#Szph3uqsQ+UGW<a(ku<K8gG zwhV*TMeYO{sIOv*$`|a$K5<tp(_#TrwA2%<g9t<#Y<d|BWT+HrHi1dFG-vL&G|3SB zgp-)8v?XgK6*Xx`N{x8io7nk_Y+&t}<tZr0U|sGjRZNsY(A5{yFjC2ieCKn~9<JVF z5O5361WBw_S@X3nU0kIRccYPd$Uy(6lQv1LUgyf>ewB}qfyos6Ip5U{hNf)N3c;9l zFi*jkW20A}XI#HcwjZ~~*og>;$MoE`*O;BBfe1U3jh`D1d}ABI^ieYS3;Tv!l_!E$ z$)I{;-C@(EnJMDL?Ub>auP7-ZxrlxIvYRWaKrn)Kzyqw1S=h#`Gnru+<@I&HZl7+j zBI`n34^?oMZI%6qwxUqXMhiza!%t+SKZ;*WcV=VuTO^4(Emy@nD_OKzv^{m3(z!52 z85ZilP5LOuZ0JJqW#XZHqd)7}X7~wXkdU^`76ej|#(t0AG#hdt2MR`fn+~81HZ8>@ z6MVfNT(_}wtx@v0T3BSaX(s<8$2b0|H`abZP<)0PGm=yhzAv&?pMzzd`(;exT4<+C zEN|iN@2wt`)29o9rVl<`sI=yMH*ZmcChDso0{dPRi(XiW`gTnSWCY`E8Kd6SspqcF zWF<eeun?`TBHs~(#B6jrBx$EWlQezc2`I9hi9(wY8cNp(oyn@Db$@JoD^_%3MoHR` z%W*Fsv~au(+d^pVZTrS95+&thKCHCmB2<L`GDZY_22G@xGq<Ooc=DTRz^^h9D7-{| zV|POjM(^hls|KII6SyYoMWkzG=khWwMe$pv2+{EoOV<>83gSgxiZ>joN?v8UeFT(3 z@R-;7`sH3fZ*t+@56v_e?&(WN#GLogZabg+bi!H`X$Z6@ZAXeEJ>EXcm577Id{oHz zi`f0U=Tq&GSDPU5##$0;AQkGU1C}gx<=oYSV9d9oI>c20GyD=wW)6X-8!q&^{jK{< zOTFyvn}B1%m#+-7sqdZfWVqNC2^#cl(OyNwYTFhyqV{lQjNZ1#R&~}_YO&zUQs=N% zk9j~K{H8=7ih`(|Ag*w=6jl5jqk?EkJ#$EsaU)ynf}ym*iT^%RM$SPYN(NB#0ga!n z0|sA~(9wQk-gBYa5A=h$krF11{B?q>-aqsDl~tt4oGBqDwxR3EA-)3<Agv%eqTE(c zav~?RUhfREMQ{?hm}@i<#rZm@cI#+6;1hH)z$e(uf<<xqiFj{tifo|n`0hUI6S5=f zQKcv=MKIE<JbQ5-l%BXdl69-5ey*3J4VcntB)$VNv36^kT8g$swn(0$O%1x3o;cOp zRy@SBhMRKplcrb%G;M=T30$bjn!aP4i}$*=RYn6vZwK~xus>jhvNSfLOrbu~Xe+V~ zc$i$ISnACO+9KwKFN%)yD#`c79Im<-;Y~&{#hBz)?<4x=HlBT6an53js->QV9&Y>C z<3r0J9CidgWUNJoGtujVn%a1>#>0gi7tWqXi=?|HSUFs>1Mf{)+K)G`Jvnp(WMpKT z$d0s9&>4xM6vrbjyO!d#yNiYnB1Uxd8^SA8qf5<BX@gL`n7+Pz8geSF9{O6Svftt? zv=S~i#)l@?^H0Su>OI*2$~{$#+2TG#V1$Vt8BWPS-}Xqz6z_~+%^zxc-fe2pZ1{47 zA$5d$yI_OQR=N_kwYjKSt(z0kG}kP7)bgQIhlR2l0rs&xNs2DW&KWY`0ol}bCi|3a zJt=}uOAyHa#gr&C?{HS%E{$_i1)sIjzR+e4LSV`b#|R<J-sa}%Po??W-_sp^=Gs23 zZyN#;L8VRO%nUjGeX|gj7JP(r+*{U7VK^g0)~AKU7;aAoVBB@|LDchvsz8^xoWX@t z6eiqrqV_~2I(z7SxBYMGUnK<4`TLhtYuLM=O<6r9QW3;Q1{3Ct%_2J`yby>_ChlmE zd(4Y>N67Ggl|bDDGKy%s@&c)x$X{vKAsE-j!mDxRg@8JjN5aNw%2v7x3QoR)4MWYW zD`HP$kV12fH0$f25pyR)VhD2$O>{LPq#U3(x1LcP7`7NfR&wzj6Mbo!k~mE=mL~Z! z1$EsBzk&+A={su?WTZc*n+qX$z3H!(Ycts@@(o!5Q}@~H@(6zfFEk1aWy+P95jU~{ zOrPHA*Df%Z@;|6kNA&LHmYAeMkxptRQ<X|pL+MYHdHhp;p}87VVui2#Dn4ylJT;A% zw>?#B{<MlOrRpL^R~@Oq7%1c^Nrq&=$jQ$0l0&vIpe;Kr+gwDD9=Ck~aD&t4UvVnY zZ)}NZp{7^}{`a+2A~Eokp%ORkm>-MY`I46tEpum#tl!L~V7!gVXVSL1QrDkLscIa8 z&F9L`sAXS(+Kak7?1U}t3c@hARPQ%a_{%pe*o<5*c4E>s;#UwEU~oyMk;84xE88<9 z20YBgR5eC)%d=J`b0`v?rmQz-lxnh8ecSe$pM;v5QH#orpF<YLEO_3aK?V%N%tZj) zqe~Z!LjC#Luuv$4-I%cdPDh8MNc^t&^|$GG<X#63ZITjKH#ZMAq>FTO23yALK<OeV zJ9%Xg8Rw>TQ8o;5-G8=Y^Tm4Bb<%#zoHD^|RnEE5_>{gi5Ai{XA)_aYzdI~j=jg_0 zn0F8tjN$O7b-|ZUDAz*B7?p3FdR)bXDS|OB><54D{5drf$arxURwd1fVG=`{>by74 zbK*)wW!8_sMiu5|h7a#?BFdRD((fFVXqwH!{dQUS+I*EuH%^f?U8?ZyE*0|X^#&94 z08X&tn|572B+_m<O|lY5gry#rZ;i?4u1%T}*7-M7=q5_l`=OFV19g_$(#m>can0mc zZkfRdVkTk;dGsvZ@`SC7?8&Em81W9-&H}FD)v6mP5K^lFyl9RTSdI-|L6dpmN@AUt z{!+#-*139je8;XdDHiD*#H6ux{h1>-U$Kq=aRjw*jT!k21H(?uHN)*M;V*$ZU>8YR zU_bYl6@nzm@=N-Fw0hqx^_64{<*Ht=B(e#D!56)!`6Oy5zn{`Wr0M%D$hTf7uM5~0 zTp&n@U(g2HigZxn;s3!}td1c*DMC<LsnNTET3e{IC#}US*U&8zWnCZUX^}21FbhF| z852(&^~~PB6aT<E2T5rS-f!_8lk>nHs1tYFiHi!tO{O4@oqRv+pLXi+w%KS)+(XCW z6$NX-#_<_b%-NJbr)3uFT2ZYhEZ+e=nhHNW#1KAM8*48F2qcyf0wx6E7+g7SDP%1L ztXH%u7J@rS;;2Y(wy@Z6NF`^>8>Pt5eK0Dz{q1hNE%0QjH>_Oss4%0#R%cCa7hQ4R zDO9-;g*fBcDe;yjrzhl`J3qRNCykFy5}YdHZu~WuVyk81=<G~a?mrhzvD#pgebco# zwmHWlfE^g&tl@HQ-N+2DWe6w5VCAMeWjqWhTak7A5=QQ?i%=v}StDJ#%g`Br4~*V) zisuUg${^czIf9lo3Y%gcfmLWsH_<Y~QpX$gW|iMemUZgcq)WU(CfSJV=2l0+MKE%m z9(tC+4MSG-oj*{o3nH37(n<ysr%%d~4ebHFQ#t~Ji(G)E!4?1~apLUr8sjxg9AvHe zjO4BHFci`|-9IOSD2Ch(Lxs2wsa7-bK``BHh}&YEagT>JxJ^3a2lF{vYj|6RXXZ+E zr3-1Y^&ek*Tj1jXx5$1n%8VUm;Z>?`*uWk<uR)Y|YY%-pBk7Bpi=rN@Ih>GeKjagq zK#eU%OiXAd0vpYJn5gSwy0EUARint|w#E>KMhiDSoL@<V&tqA4WlE^3#k7_Ex)|XV z!Hl~pM+owOfDBS7v`j0)nb)LJOBg>iFO^3=5rv{L#1JEZ+{cS-Am&gI%6yh5Xx7=z zrKQhJf)d1qE_LL{qFsuOGqX|Ol{_DV@w1mGMY|IfOLC3SQ*Orj^NO4)aXb?gFL=JR zbK|8+mpQ$4gPx~lC6?I<!xI#8R8%@%=Yg?pUy3!q-s4U_6U>*g<&}N<d6uS;rU=2g zwybkOKta$MGAQsGf46FKmyeadi9o3z-Y{&k-EuUxjP#IS!$MU{7+G#mGrcmZR`}~` zL>wcX>l=L*3jA@5mxyV2<6p2v+he8_eTHFly*h&_Vg~Dewhg+T8Dd6JHl4s3mh!c+ z5s*fBU26%X(oZ35Vz}Z%3)nHjUPVa-H~*x}7X-?{Rm}A&Ng%0`YjXaNCEJED+mJ@U zd$~;iFYiim5(O=7ixGUsv^e5x&0uNUyT9GFQ_6As)DHcFqh!Jgbler$9F<$Oh}#A2 z$l#@+*1K>GE1q;ij#Sl>fcTB<^J$s9JY&<MIp|@L=wBB>uiE$BTzqu|O=JmY3`^_* zLf+yxBOQ58gKfreQ-<tp;xkJ$X~@Hl3imYjsd6dG3<REA#$Afk8gzoZ9CXw7t9f0Q z&SJQg=I5i9u3@nSTvDDorJuTF&wrG<2}hf+BX}Y-_l;~Ow_;4#DZJOHgIfsyBVqUg z2Yv`Eq8mJ4f-KgY`CD0@JtXl&TL=T4Z7qpTQ;(wg3~C@u9*fCpCnwb?*O8WR-zF*c z4|K_9p^fJA(^Fa&Z7Q_5MQcy0>eL}CbzN8o11&8Cf;@Dp(K3eBw70JZeA<jB1&ES= zpW)C;55<`UQz`BLke|lJwIuw?50MI`am&QXu|C0wN(}fE$lEy^+KN?SD9U~0=Gn+a zKEtaKkaOPUrLGU_<79}0T)N*Pj}XLVqW-cYVbn@5n@>SreKy9ao2r@!H#T`AO^UAz z^#D!-??&kTEs0fs6Isv4Z&g&tfm~ckf4HRZ3p$In^!q>6>iCcoVGFXpopmJ_f4^w3 znlMP%%sL;FHEOZueY)zD$eWICX4lOSI+1X$XKTGRwurkxjT~tZAdxqXA;sMA?v_XN zfeZDrD+sA*VPnG@!Bz1eEeo@9gx+=Xqo%M``Z@h_y1%wXoq9DTgCAR=f^rfgCoMu{ zaEl~f8xIFo6it2rn{4+X@t8Hl)0jyNW*#jl?hR$N^{oklQl}iORt9N4Itdf5M+&JV z#X7vKB=!_B@!Jr|uu9e}RoX`S6wCyy{5`2(*niQ+vto~&=1r_N3|5;ZCt)Php@Apl z?!AT_CCUFZDG1nc_}^-V;lnY)zn*)k9jk{^XBL5T4U5Xh^yj?N!c>=MwV7_UStZU^ zM3Fg>T-KQ*_4jM;qPF3OR9R+Igdy!jy<F<b@TNd(W?Z?matoWWjg59J6KZ4XaXB+r zw;RKi#di9x_u4di#Qh@iI76cN0|QTD<I+)KWMh~<ljL2yU9#g@u+9`3_C0?hrKswi z$ue~NAg{2o!r^LG#@9IgJ0T+;Vmdrz$`|?QD_n^~R7~CY)QPf<dw1gPNeIlreY0PO zbYj+#t%ge|5d!M07P|eo+|<Q=R@90#Q|zavr{O37CM#3ySo#wTu*7r^j^A|FYS;wV zwPf!%#cX@o@WlC0EDJy8aKU`UAHS?sLNJXRvhZ1neMg}$<av^N@pTeODgQx@=fGkG z_80uFpyes2X?p?--LIV%80dijRZf5<Nhq#U8_v9W_m@`<i-QtfQR?O!(2?KBK@%Pj zEor*;n4P(LcF3urmBqM|SB7`qen7Wr>9{XU0Rkdi4w4-_+o&u)7E7m&tZss0kveoD z#j4$M6`3uq)8D_}ZaxO;hJ}#5o!5!jyHsD9lxoHm?H=Y-+F3njT`Iq!?4P<FF!9iH znJ+^XrQFPyF)9q*XnMIb@>5ZzDHc_UtZq!7%5Q;S^}}?6jRaGrAQWDoQh+Rf{zYa) zXT(o9OXZ)MIlW?ZtzjI7I9|9YoDY0$4Dg2G5BTNha9Sxz%sh1T*s)JZee8PUC7)yu zlUh-+NsneuCVa;*d$0tt?a52g(3d9syTeL01z-NN>B;S!PV!3$Q&9;l#fK!d63lBV z8}7`yX&`42D}1W9{`dM#Tb*W|89U;1F+0W;Tcp$LBen&9>XWT78kc56yuYuasNT3B zwuCXmFykXOu~Lh8PfWrsL~qP0d7Z2@>1I~#6aS&q9<jEF>V*3D_p&g2QAOPUiCt$C z&{cq7=i!;6wGlQEw<fJbn^MaD-H{}{^1LpINqP?<TuRsq#f<Jm+}qphwVqs(76wY^ zPzZGfiRH^q9U_g1T<qQ9mo&|FgL3i+c#P&_(*kkC!zS6=TlZx5xCEFBLlAr3jkT(< ze5PsV&5Ys%sR^^KjI1-I`H8D;e=JmCl(>EwjbQCkxO8O$4Ls(NlN5AmedgR~eLJTt z%Mx5gCC|kJBBsWlbNv`|F^5Rv5hqQK3`6Ii|4QhhaFI%EvsSHVp5}%!kjSM#!xr-n zYLcObXr0(*=;N0s6c=|yOky1x8)N>CJ;r&ueYX>N(vztBlROG639DIAnihv&1sK;X z7{1mcrIcYZGe?nKABKm8>_`SmuvhH6XS7>n(gx9^m=g|LNy=+8s?uhR7XP;O$47^G zjlz=`7-nrUhpvWZFE5GwuRwd=Iji$k2u_@kq)ym6GChjc%;@O%0|*BiIuV31Nd`-n zR|ob}B4Lax{J(*{nnmi}!p;r&G<BOq>Ui=$zh|jvcgihxzaYtxZFxJ`+p`m(m=UeU z79YWnRSD>P;eW5C6<nBEY2-s2*9BKv?uIAxIv0hXr3zRm7CgIdUt@YEQ`TJY<l)?Z z(wNrYXUXigAoGoit+^354@X7YW!;PDk;U75udHjp(e{@LSx_~MgzzO{`1D6!xA(pq zlwJ?-sz{gra}}N&q!8pJfJ&?0`PwdcL4YbNV$HGEh#*c!Qp#c?kc(u>u~)!JLl>qv zugCe6oo5bH${eE+)40re+?j46(<$_)B)r6`wO1$HcM-lRj7}2y)S&?GL*#igy$s|! zH@{VD!m#$6X}85mrih418B@IZl&m2u6U@I#<b<pdkAe~Th5|^j{=u+bG1K!2C@GDk zyXW%1<Bzm?Bv20NP59e$a(QB7{pN2deX}f#8rFwZAzwMOQx=(U?%$a^xf7Ic`c8=9 zI$Qg6@6oQld-EcI(!XltRy03`De4}k^2PhUn}=6SC+{@Nw8qBEnmYN-=Q7PuI+2Eq zUyoC|&|YNt<6zMI2>&bn`<-P=O}x^U9%7>r!VYAI#iu~i|80_H^>#jstwX^(reRrU zgg|P;f->P3#e2PbZUU(?M5F3NqK-$0i^0yM*!{IPqwa<WCUb@<NeaMl+`kQI*5%xy z&g1*#)o!Bf;gD^eu}#nbVL%({ecDoG-!PGNj1sgY>eQA%3{l3ibj~QDKg4M*F{CqO z3BloxD}LMBPHZs3qaJwsvz1}wn9a!_4KYD~%^uokgLGQDOZ^euVUR%&Z+o@?lW*Pw zvWm_n;u2e{uPcgq4>PDk);D;LO8!OPbU`M&w=&)y_is?{UvBGYmHbdek>jW?i$=X= z6BD@l*G5=kNHH5WN(Be+nd)p`Ofn!)G)}G-VR32Kor!X0sgBHIW?`&85KB*{Fz*gv z!&<$;9>lOf<lMy%+lcQmG3VBT-W|27nT@-TFli1-3HZ}l2wRW}r_!#}T8)0il(?@g zEiKh3kd69fsWtG_@Jpw@(K525GDm?ZM!{M|MaA8nf8ICD?yT2ScaEOQ)k9#MA;HK8 zH6xd9^sBvaj`r93l$=B%L;<;>hxH9*w{G*d0@DTf^A(Ln8-o}A_`@4F_Ej)cHnel5 zdm=ZJeB>4ZKXTpj^aN2=l+yMUX{w=o{uaTP2=PBTzSiWyl=<tT_n-t#+DJn=_&j=F z;LY;A%nx{N5SpK))~OuM_};@E@*6fzevQpOk4LeJvd!=5v872D&L~Bec7zpWjYh$& zI99^*WHnRB^(Cb^`n1x+?IjXA(M0>_PvQCUVL_3S!_4%$WGFZ})3;wJeLbHZu2R|b z>a9jeUe_v?MMOkY8?_qyoc2kFqL=B^P}F^x!(@#VtQV22R!E==hoq^}c}_F2AXC_= ztRoonDRD;-a_arC9;XnkZ4l0!x?HT@NstO+;gM+anY@iMj^Cg`WmH9_;pedE3B_R5 zsqQU<+W!8#9?4l8YjT*FM?ye~!_(;{&!=D(dZ;McS@^@(q}K)#sU2VrM-i_sEcnhw zxOcy@)ViKn>s42r0!#kpI}HEme80d^$*4j-1FDpe+4)Y7`oiu6Wuvct`Plr_<w-WZ z2_)RdKh9O#yf24GMk*>QUO{GS9aqF>+!q>cX{A|*4*v4W^YyL949=LYOifK~^hak1 z*y}I-tvg)!?zqzakf<i^bvDFE>A4z^;n<!|NtY*7r&Y+WR9{gx-i+AG#rKDap{c?w zS+zv+J5||e*jrmx==zNDC;Q#WBEeNoznc-))~v`z03xUz3Yy<u$c=o8EJv01aEd#r z2SLc>GKG8j>1HeSy~muTV2)q}`+!+ZMelKdbwM=d9Z^}H@9IJdhD5~4e3O{cLJIi; zcaQvlbEi3?-vr%U{F-dyM;LEyERqi$`z<C|HrsgNGy~2bK74R$)ji3d#zSk-L`S$I zr6ZuywJZ%eYigu(7_L`VAyuqBv>Ddy3M-zd(5Zn4v|0=$Yz)LANlrlR7v|^n9bTa8 z;MfI`<~JJAV2V~`iF{mk>cMFBIMjUlw|%nKbG7twCH1}U4OqK%f{`qJX7|-jSZzzv zR}Pt~C9t^+N$FH@f46<!q-)^G2*DR5^pVP%4l4v`O6vtOh2fM~l#<+B6IIgo@|qH{ zD1~U0!bh(nX@^kYlJ9e&8Vy8iy=hWB((ylGTZkw~>!K${D(!*Y=ZAd_iExr7WYD&F zA0k<5)<aM^`ls6iBZHzTn<aOHsj0q%cPl*(v)((*n|*}lQYxjfmK<BAPa2lRnsvcl z*~&~*$zs;zTe?1*d_5KUOq~r)xS{%Eju5dVj2@3@(QTZZm*tPye3{6Kn)cg<adErZ zTIxzY9*v=*B=zt=1_=lB4%lI(d-|>l3JO<8OLrH$Z#6XHJ!c!NMq2=?%vI3THGev4 zE&)l?_UY<qre+1y6!I_{>zalQNyq463@s`{fVhT<)vYf}GEdv1;tNTbzv7Z+>8zwi zHJLf1Rz?H-StNBlA$%iokFWb-`rvlbP>9aHr6CYgN6;b%QK?fK{iZujNm0aaKc<~z zcas)^8oG07zx`0hPG%@B?kZjf=Mhc>zYr5}qeb0|WE4N|ftT?{Jh~~JkJO{~Jgs=y zB0a%=Sjkk9gq%jnt||-RB+~{q$<TK$j9%KnbK>h)l15DVdTe{V?7y>h=89$c`84Zn z3D(Ff3K3F)3XIOcO&v;PRI+pUT|8P4D=zGLVv<kx>EFT4$ot2$X#+>@^2dXQ@nW?c z-zE2%A>;j)rLF{mpw`S$D{MKMNfTRP)B@!=Ne85#s%9axsd>ikTgf`v?$dhL5yoxa z#NVQspyUe?Y+97cS9#Fd{4mI{Jt{e+#Z#xCs%_8M$1p1M#OTM6)lm;Kd;`@y42pY- zTUAl<Mg}TRjC-mu_$v28nz;#E9J_Z^I0;FJgd==}tHOZ@N_y!KM0a|RTo_fvgXpkQ zsyQNA4I2{|+8kShZ{NOkN;jDUpMp_?IDSM&7MsUg^#b{}y~BDu+fBF)ETtC9RExV^ zx~e4)vDZLkL<G#%pw*fC{xtjhc0=Z=){n;kBPT!N$g21|3x4l-ysVl0YCV=Y_ruHe z_D(RypwZ@Z);!k8xeveNev4BrQ!wCT3@DR{TuDnyOLyW095m~$7yU`9B?>xHuBE%< z4UJV0>6N+z^$?u<HE|+@u9J)}v}!ysUSxF@WE6UKS)-P3jafQs@m}cFa#0~kcgGF= z%;#DQk824qi)chA(@5XD4p8G3TvnsYU3?vtsYCR_bhYVaKHGqYlVVsra`t+&lfD19 zsC>+!mg)_hoi}IJCn=(zQ8h%G<PL0P^WoA$z6P1Nd1Vh=Mp?ZX@IXb$LFX!L*QU8q z;yWZ4bTa9Sz^Ct{zl_-9|L_NpWodoA%Xqe!D3!VPJ)h&UVfXBc-_rxApcbb!DZyVt zu75=@|GZ^X%jUzl3S?0FNh<LLld}K&>h{NuJEQZzqv4wIXL(6`3*V2GINN$ZW(zu- z{X3Y$K~?6<XM9s?;#&N$;2vhYc62T&tARix7cf=D&YWyZbeoH@#gB*mGB7G4rkE)v zkn43U?$l19JO+xxW=M8<eu883+q%NC32U(bhtI0TdQJ8V1rB%oZ@v8McycN3FT?z% zcr>rAMG-L&J%!I2v2<z75F_zjW|HhpS~+0J&Jz85UDK(_d$DVycHedFyb4r<v43|U z-}<3x?th;JxKA^((abt!ysIgcbewOreR_N#7x92h<OXaAs(j@;{oGMsU$2rOFfqBI z2Ka8R_VY?jSy@?m`TRFK9f6Dx&&$7~8EV<0UNc4?L11$~-~E$S*2EIAyqo@2Ah#7i zE`A3o(;D(bBy^dxOw9twVmDLWm$5yTCE|1KRP-l_`K`LZLffZTnBPpg0&y8tu~H%P zjk{Ai?^Tv`O*}xzGlkvvzVh379Lxp?mRpXbY-fKu@`r`L{dX9Nzl9`DY^^~w`e1f+ zWYmhSe04C_VDR1Hb=FMH`=`s{nmWs?{gva3-)b}ZHSaqfgD}N)0fW|=4**pF#uRW` z?F4Knl&nZi)pcj7@~WeQD4qlN(;IFDc|f8$evdZ*NTHCqZr7u!ikV~`W3Mrx?cBzf z><R@)xmCJ-Oej;Cr8ggb=|mE+mseJbdK~E5+uLhsXn@VN<K?z5=){wtgu-NlP<jR_ z{<_uw+YEexrd_4~&Eru2W{yJ48=YLZQ6Z5*Io`Pk0|uYe(v!<klH<i0hBYLKzXuCr zEzUb4e=z=!5VOg^cIv9Ue2qWhxX^YcQv?CKzLv4^a+SgNPz(~5A|MK`4i{39g-G~p zU~)e1Oyp^?ywld7ZgSq3t}>|6|F#F95FY8}kG=AW$=!<>auJKT#562_er-cTwj6Vy z2&qZ5--KHaIEz{gVv$^cMK#?4t0C%p?`bxY4GQ3AI`5WdGkE)KCk{f_llWbS<BuD} z4Hu4ssR|vnbe<w}u>C21YXiz?O;W{HrH|70dTl$$FXolR^=eR-ushtg6{x!2C5lf6 zb%38^C?y^N`YNu*j-+z>0SJATXvW)Dfr%p_LVKYKR`LNaDEd<D%hdH!F3(0dpKiwe ztQP6VpEU*rpUnhV%jW|XdNte`&Dwy(w}8UYBUGGk|9p3UbDjedP2{L)W2WPgU&}cf z5^YIh4CZt-NE>@!F|PWRZ?`zZfdnM_uoAXGQV)#3ie^Z52BQFO{-@lKG##ALl7y4= ziN)MZE4aDWGY&PzZKC5D;-7CPEtM+D%ab(w`uZjh)OBr_THI}IZ9z`?tkjJD(SG-? z>U~H1k01AWUnp80Z}<17DhA}Ke&H}+ixp`BhE-Hl^gMaB>>1?#>4>Fxfe|^M>9&v4 zw+;vw$BqY&nQEg*LQd5QaB2n<K8*@lHj3zUxT1!xQtuJ6*mO$Raoq>zwp9s-0=vcy zyQmU;Y>KrEfC|MfWp!gPp7y)L5~>5@-J3nd@5Cz13vNC!B>a23B{{0P4fp9HACGEH zd#0<6>{Qv_^ShC4U(URz1n}1ZE88%4kn?y^0t(g~wg8)aGw!OS&2Pc}`@`LM`)NPv z_Z8o}@UOTD-Tr^#e!XB~QdTPUGeM0=`6VQYXKZ3If+#*jm-J>0VQJYp^Ch`(rCtLf zw)fq?Lr{rrZo88hqyldH(^a5!Ax=CI1Z7$k+Eo#eksl9cov%;U)Fd9XnB7O%zh{Ca zdlMf+CNx>BLb|9@=AMLQI;oFI%ww_lr_8P5S*%H8ifQTVv+UONB7sN_4-d=NhLStA zDM(}~7S;Ycd8@5$Ro}z)EMww-;LwoqSjYnr3=*x~_IL3MG=dYw<F>11y#}jq_6r0T zgTY_3Cs7+IQs7T`x6g$}QrLUq$3>2R0B9(Xi{;R(-vkm-^z2FWUP8C6w3FU^=l%h9 ztH*sw;(iSiV7^kYHMy{xx+19N2(Q7lo-aV3k6kT)s*#B#K=1-_z5}?!D8A5O4G#Id zvY)4mtVbi{Ad~RD|Bah7o$||K9xR7>teEyygJRiI>qkxlXjG0702{HZMPAEcyzT*h zetu6ZI(RrV>pY}1hU8|IV`8k2;a&7!i|Is+p$|hxL2kmIyIv5I3AtE+a9<AsSS+uo z*dEX6@V?vw2z#zxR8+K`>8d&qL;l@<;oqEf4gid!7*H8I`H`iYfg?7{KbkY+doaSP z!%`kjdN4Wl8^d0jfPnK_{UqWx>s{>%0^;E1rsjvlVKc^mnKd1cBuD3=qz)#;$MJF$ z#Ns}l`BU`Bfz9WC6-S!ZBUrP&_sSC1aaf4i44?<qtw({hqR#8Rk(}+<AR2Ea==EU3 zX$M@;@5G<r?I;8wv+$Ur>K(qHX{+!;LDY?#oT!%@%=#jpbLMa!KculmkT2wkZRD%i zr+*-?u4j&xS|zR)T>&HU&tEBah+Hl)W_!Xx-9aX$8hhJz2cvY-Bx&NvDHdraGN|mW z)O0`__nXooRzT~T_eagun!+!i{F0+I`nco{^sVf$p!=TIR|re8_h}y?XWNA)j{d*n z6$t?3-e15%etx{!4no8TTrJ;kDMiRjj$9&w+LvgSK^Q8?dH=wPpxCi0GP7bE-CG#s z;q@m+S;JLFlfF6vl?0m9xV_&SE*6(;29g2Ot~S=QEe7l1FwF=GH(KrG-1=)8UF zda?5h(Cqs9dhnp^QZpR7grbrXC^~zsU*RUo0Ic>ZYQV&=c77EARi<ZT#GXnSAOWqP zW`}aiNiOy;x=j`;_(+3Qex|I+NzGLXL6epC&y*xj>Rn4?>E_k+%4XP2jzSUx&1(10 zAWq@68Gn1Z-{9H{JtTbZqtUMea+A-(O$lB=wGq4SM&@<~JZAglUxU$%S8`vNL(L8S z9xf+ieNVcOKtqXSFabTJS4ufi>$n+pyuH{Bs*j|+&ffp#xbisqY9;CFDeL1hcLI7{ zevrB%2Br9Yf)a-$FYLdCVwH^c+r5gjhNtTRiNQBA?_PX8XDU!<E`mY{CR<7)aF^Nn zni*~tapt)#*oF`%TOLZntXNoBfChMz>bl+=4)BExBpsNldZ~QLZvgz3z|jEka&^2y ziO>~}%LwW{TeT#E&z7bkAkf8g85I{_Wib`J@BTdJ3BiKe4=6L<&$kx~jvZ}4i@aL# zIR~ntNPx1rTa%*9;k*X&y0WTj)T&_=D1^nPI?WH8gYnh-^C{6`foL1UPfZCaAHjnF z@!aLdI7}JlJU7nvbg}Ss%ijF9_-X<Ad)KYQ_u)Ewcvz9=7mgB~i!RekHlr3Tnhab9 zWf**d1-N19>ix$9YYD&(ge(89I-ZuCGc$93D^d!%1lQzv{Y{72a8|2th7bkQ)6;j{ zPSrHQ12M6X>*7pjTFN^n2%nmH?pjRR=V3V0_V91vW)4s-tQvy5C)W@AfzSv6g~1mZ zML(+Yf1zbXzOWbhfIir*DD_d+;kMA3VP^zT7cwsp1s{P(*!zz!kg<Rf%Urj|jyr(& z;=W%$cW}BfK*+9tvG#?MLfogxv?ny-!tkSS9-iCgP3>!aFu{@>U+?7~UOithQyrof zx`D27Xg!3EaCZ1iSL!8%%aCZB&HSCJYl6WjoNKVIF>H3Z+?xWa)A8@C-7if`w;s5H zLS21*@4xBRXX?5`af=TM5-bM3uQ4la-b?0@6~^l71JRHW_mY*wePN@{&LD;UGu?(& z72liGUx{eWv8**e5{?ZUtT2K*lC*W(u5SRo{Bpzi6P28`U(?}xIRDK63eju#xoNch zT^jMHRD;&{A9%XL?NCp6b%5+&Y7AN(z)2K9MqefT+W&CyTI!Ez>%->u`o4&pVQO1| z66bF>&rdc(RPF5Pn}}VeEotEL_~l26-N@JffN87ch(7>a6ZE~m2EhUp3KTI2*`E@% z93%?Q+`_`%bJ53LV21<V|H^GH3(~ZEf27!`xIFv@2i+60AiiJOkp21J90>n2%hJll zR4Q%G0>yUteMS7kAEsb4msu^i5B@<G>FQ(JbZ5s!qJ^|Ji?!r;1Lc$e<e&CfYlaIc z(0Q=_?SB}Qww9KqW!G<fy@oXej}S+-l<v>G_SwRWiWF6Yj6pdZhb>eu?@^hY9g9o& z<I&HL)y8e}jqA6P048p3qlkHBV=3D9GT!aLzz|S`nrdiZYx@0$HytEz0rSL>X$G7M zEGMiAB7RyIVzL>@Qj7q4x<Hf9FeD!#NOX=ZL=B~81tBKLx{_&%CFl#)4)3YL$<W1c zk%KI}u}DAz`D<^gVwVIc6mL*G0RQZ2+MvMc12X&J?rH^iRN#8oaGwZZ%0~MI=ri0M zue?vukl#_Qb;M1SQ25@NgNR8XYBP~57z4EK^L>EUKLfW<^yXQ3f{DB>QB^7Vjq*?u z+$>)wEi@m8y9oI3J7n$*Xr1Q<0MvYPM(ZNwpsONTPIyh@AizLr$Pg8^lM>iLXFsJ0 zdL_qAe}G%nMHO+d)S6lYgstUp67!Q>n#;gHa{NP9$N&YPMt}@WZ=QRYk4KBY)g;=0 z(gAoc@^JB6#C>n`PJA#NIUtbBiG2oo*m~S<P<(I=0eR+qb@UmeJKz_}oMa5!u!2sU zE*mr|bKyzZ`9IEU;+3;JW>lu7=L{$wskG+P!TOr{$HLT$)Ei6ucGGOSwf+LP8?h48 z;0w$J;Lo!^Gh0VHRkiR90GUxM`0lXME|#nabP2N96i_q^Ae(?*_MNvaaUNAS2^klc zG);~u)8v=5TLPU8P+ZnO)3_U~$AMP=;$@x6`Ci;%vFYhy<w=Eadzv3@&TR1Rya!Xl z2Uv%^)?<~GmG@7L=q^wDk3$oJ?_6+@5jbYG;eWd|zP%cpZNjA>$sz}5vY;A%k58v> zGs^nXzkit8JN&-<c$l^_sm5H?{`7bUFvb@!hCd+^CWQ}hSO8OaZQ2KU85kQsj)@%0 zGX*tcNRERYYOvVX`H>t6WYoLeCdHLd79|Z0o~UjrLU2$Sf?pvRC56vITatk_oeIZ| zlGTS0&5YgyG=%T7%<+5l637^};7M0T#Cr?{Y67GU&<uz3P*!H<IUs33&DwqVP<svf zxl8~h^`HrR7IOJJ1C)M0EqK7f`rI9U2VhLB9Ky{{J!9$0W5+sKqG=$#$FwR|`@Dk= zsCFBmps)mw``#ZQ;FPfcv@jv9elEqt$;bg|W0`97?<ep0eIdV&mKHjNsID(IaUcrY z3zE143?(8r)BV>7H=MFkG}@{RFe!+!B^<tIeotl9)y08wktyuOs#(IelZBBSEu{_- zE}&+1f0wMdjIaYw_V8-OPc4Pn;~7{~(s{N(vrNuoG1zf?K>l&j`S9C}wzjs*YVxoC z=%32M9}uMvShtFlCo7}F1Pi@pV|L}WDylh?zDBw&_>|Z$0Qwu1csz|g2eI!A04*Y! z4ag;+c{*ntCJTo^EXgZ8L8>d3u^T|Ow6p+MmJ}BwVw-|S57tEI-Mho(wof3{oXJ+a z_p3lgg5qVrv`-g}mnI8c>kY>xWYbkQF!%)62E<I_{3oyGRgj@jrk8@kP@zI%b<;X( zxDQyMsO7e5g?RnfAC5PN5_5oxd{dMQ>Y04(U}8Ve_}Rq<ZWBl9vpI|If+`hS;`>5y zV$Kj+y-#0GBpWi_*5aWyS021EU{THl+MW-+fxm!U^1G~fKXl9bb!aYZ=z<TuCm{hx z$Q+@K3(OB3@&~T5ah+M;a55{vHY%l9FgO{|qySe~=HI1JATRVkx(@ZF8oHd)Guo-; z8$eFi`y_7WKm)gNe?Fc{tBb~~VK3LhUfWuV1<o7)3>M)sPd{e7zI0hkOfpHr&{r&* zp9i!sb2R_00?;eSz!&|CKfKPhSlmHLW;yp016Y8AeZe>bdI6B}1o-%C#;-sL`aawO zMPE@}Ee_=S5itH0aqEJW$^~iva-nxgcbfjP=u4sAlT+ZYby#ZQcUVjl`~w=_CYk9= zKOC5@2O*cuLDzAyfmeo3T`xcz4_Sa#rGKZ9FPRWpQxnb#-IPgi$s+Wwv@3JrMK4g7 zDd(^yWnzn<MZv_NhpC0vJrs7?lyA%TRyRcm|MIpR`Mt{l7K90k`T*-mBeR>oOn7nh zy9BfI7))&}lmGnK?@5H<5NNN*yN;(%{ZYg_<G{<*#2)@5iB+gshQ`s93nC2^cj~k^ zAm(Sh+0OcSG6xY50dtL&cqGb1F2hw~DbsRZQ@4mHF{RHaj3XaOfJ%<0_C~2Nb2;b{ zT)WA|Qas%5*8o}%m#0lud>HV%mjgi(8?PuUV`gPde6{4h^zU$C+okzg4`Is#PlkX^ zccRMR)r>nPxiIJ)hk>b>bt}s?4GWK0d-NF;6=0AhP*gn2aS_Iu@$X*YmPShVyc$t( z)!zr|f2d^!q$mLU{vj%7yrA}jyT^|!pBa~`@~WmnS_;%z*{#3Hr%OPbL)^AY)@eLO z9(&`zc|b})-qz#Ed6(pzV;7SO$eVay10Vv9wYNSNBA|*YfTLh#o!8&6B;Sr3Jn?E# z>$+c?d_P(e{<ymczzOW#{h9%hsgwTl(m=p*POEv>bLw;tcZzAala(8P*TdmEQ0M>l zXO5u@4(2xP00%(%Vh)Szo|MS9M^>TC(d|8fQ?OZz1r4m|(u}6LC|z{n2ue;t!2ujb zEpErlS!4BJe!#tGJ?Tax<^S+z7EODk9Y2O;e<H63pn!iTt(~aXnT0?GpxH7=S_oQF z8<z&25%6e$CS7cP?jO)Ne_+wYz4^o$bN+C(LMiC<S{4nW{WK)V!=0}cNc3E?^Nq~O zHl=%I-$0p#_%QAppr|Q(kuzD*VYl6<SqzMxf8NieD-_A=Owf(q*&exRW(9ZvxO!k8 z?9%A}us98Q;AD#{JST}xv5W>@25@9Q02ly9Bmn69Kfxu9)1>W7PEYVx=Yy$69(n+W zgrwtzD*%ioF*=>BcJYpjo_{%%xIg;Xu@R~B{<Ay4%-T$FD$mA0`yWTkPCjUs`egvs z1lOv9x;S_#Ux+Nk6#V*<D+yV2T>9EnR$$njDmf14Ey30s=CYArpa}&o;MVB?r37I6 zR<~Uqv)-_0Eh8C(h^|pT$A(VA9TbIEz$BGvq^TLmz%hRAeX#?ptP&c2kW;{-rl&`| zuk18A^WN_Pzz!~n&$XYs`=#H*jGuzO6p+<)&LNWVntMPsDAjJR3s%4H5MQbNbmcJo z$!rh<5eXc_1O0A3hXPZKIqLKbd7f5kRKNhdJ54a37JsVa$lrQ8iQy&89XXcdJr9Rh zdT?YS9tSa5BB-yi7$OY*$x(jh1Cj+I@M*O(0Qe_he~1*%;zqCN4_M6CD6HDWfmGL~ z3z*^L{pUY`1REh7h^53tY?wQL7o{Bp^oF87QBn%e9D3-a6j3x6Ot7-hQ}qM}OwpGg z7K)OvY`@&tMZOp5YZ`5W&t2s_99a83?7ye<IgvzmsC6;bo6eK|qRtbHtzHpP_XbY} zco7uf@j%142rM5}+7$a`W#4d5-4u7=(<sWD0v?h8wx473R!Z615?{c_VAVnG7y>o< zEJ^_X*61~a9zXjZ0MOG&XQAw@XuwGO2Pi}b&^c&Zz$Ag69c=0eZXW3iB1=*Tu{5~5 zI_|ifHUL1ImK#oDsUad%G!xa2TJUBt;EI&Ego%!vb1i(0yql{M>=(Z`thX5Ieu4JN zarp<paPVm#q;|JN;Qv2var!AxgxN0u4IBF;5gSV`qU}+S(P~O$Az|?C1HJt%@Ha_- zTCC1$-P|b#HtEXa{z6g7&Sa4ip6s*gKWf>(z6Cl=_VL3eXuF~i6D+?-Ho0sK$J5FU zN4Bg6qID|2NyPv9*=I!#>qU+|9a&@OLHQ8c1KEIt2#R$-mwt?Cq4NkaUVV?2YM?@? zN&%Cuv9Yn1R`0T=_R@~YwX<R+4RxH+yNeGeS-_Hh=2Ky}QnoR6ASU_7a_)(_Oge!? zEQEPa6slw7J_Yh&1mQWkx9`BlATOwWph7N>SNwkE%XpqX?*fB9FZ3n3J`e)$-hBhO z1DxSnSPx+AD*u{bOUsST7kl~PZpfy$KAct(o$PYCFbFfcKbq}tmZ0-GbiuJl=;^Y? zPsOY3XsPAtUx)AAJ=(bI=!(~N7JwCy58xEPGO=yU^R59)R-i0JZXu~dQ^4jFFzrA) zUh%F%8^{Zw>sCHr83me)`COj>rz@b+XME?AcC{h%+S79>=I4W$5~M3zfdmp|)6;wI zilhsPjjR{cAGZqk0y7IY)Z5{U-q11!VG=S--$$Biqe~Qe*5W;`BeLH;oyhy%pAM9l zmxCsc5FbB1uP-Iq>~mlqwUKzDod>H^b<|HBeIWR|kSH&XSDv22YG0BGI)N^sv_&EP z!sBpW>}-(sY42@QGv|+!K#MQ-z`6w?^#j%kqiUwS9R)C5zs(qD_>&WLOo>63l48_J zNSSd8Uf}c?f}VyK07?!-5hla&Lae~D=|yWzWu>yNtC!aespAjWb{?63fB|p%NgW3( zWSuR*_B>EAs=DVuyA9lXpo<V1G(t}Q88|YEw|>6!@DVT_g-1kB6LhB8R8hsgj9Q0q zMCRcRnn}({mt$PuZh<pG;Ghl`qV^d<<W~VldNhPaood)29fnXNrt@BIE}o0pG}LzO z1B8^(&CG;eCX7KLa2y-Cm#7V_#j~9Xdg`AX0Xg?Vz?FMefI!U;{FERN_CCq|zU;mK zEG_-qu~x1|Mn;|y6Ci-%Z3kc2^WVXaf&Fal8gn9Fql{iGLXs(BD&1G@Gv2p!<+_B> zjb*UU0F=cY=u#LpnpX!WsE~o99|IWpYGpBpS~}DRG%bL_dYoK(ypd^({^(g}@q>L_ zY+BhrRZ%A;-~lnkuUCP|mc*f0kV*>s?wnv0_-8_3E9va)%<pmzd<T0$?H7|uCp>s) zukznQLw3@8Hcr&EP))a9U!h8S0NaR8<`8!$S<AF?<j@R7C8mmT87Wbw$`hQh0PaBs z$bZoNgB?}iXovIHe-ptrSHDzpk<+`#^Z1gqxd7O_I|PlDl@)Zen0c`&>;{2C6V*l{ z1rR#3v|c=CA6t9-L(sc%wQJY`!k7eVg+r_AxxILf766HShuD9!;N^yBESb<5Fu~Va z^?^y;^3G1(3usk;1g405uo(mshY|>LxW5WX`ojrY8rMy|y7EiVEdqInj~7#qXem$e zb1;kveD-pC8>Hy-r4L1sN)dn`m1%X-Dd*Q)j(`=`0Kf-SSXW0QWDX}z3pBOSP@w}| zRw{NPR7s<YDLZYjm-GSD)wL(ESD!m@AOX+4v%m0&Bj@1o6|D9Hxtj_)1-~a>U+A;M z00Ee5VElq)5{DB-6!${l!^Ayy33YeBiHA^TAyu#&IC3GB#>K74{wrUu_~o3Y+mxo5 z3gR@(9*EiV&Ji$AU)fB&*5oPdPQxQhtkn3|qDe$Hg*&ZcaZFnQgMye`&WoX;sG&e0 z_*RYnF9)u_H3rT~_dD2oWCH>s4<b0Y@@O&zt6~E=>Q6tJ8W7q9Ttu08V*+d#c81aP zsCI)_E7L#jAhEGXZWZMI__|#qsX->UdgA)K*F;3UwV)GY0zU@Hp97tT*Q&^WYT|<f z-Q5N<N+wyE`Rnp~dsrB?dGb!hN+uuLd4#Tx#Aa>DT%i>N)l=OKV(>ZBxY~{2;rc&y z%0Dskw^Mq#=f2V7D#G>r<hQM{&`{*YD}&d@Qc7-+dlASHUW{T9x}tQxrJbmL&&V@c z6?Ar+kU>4y@WNg*uTRY@LNMZ2G~|tEa<MVRhxtN9oalOXQq`BzML5a&4wa%`54aO$ z%ngw*sJf2iy_kt`FRPuD(8}%RrKX}+aR?I*gk_lEHUoI;XF0#LZnkg;qcP8pVI$`% z7yY*V<IFbFovWKIYLDoTnM4E`fkJo{kXy=pS6vT?Sc^^Z_JBpBbQebw?PkjsJ)Na5 z)ukz9CdG4sOKVmnn3%+rJDy0(99HyatN!e(7n)#>42#6+s%CTYC%BA9+$opzFA5r0 z2rB;jaxcTWeqVm3Tqw;sN4YhFyda7ld}``194opYl<g9bNRZn5$Ma&_)e=XFT5p5O zEM#q2_MSsRgIAk-UV3M+?5Fl@X0q&{#StCe&vhcD7b#!UicMriTPS*+n@SX%9fZ-U zrFrM%Nipcmo4nk@%F|`XnJF{<*HqMUQsYG5eSIHe*wrSz+I@w$$#6C%t-4&yCh${+ zCjv)SZNvmtCIwPRRG2AVdWJh~GkTWPG;uSiSI~8v$5lbsrI9M4VVxo@63%Nq(Z{c+ zj{E0pLVX%a;8kmOq?Mz;lHuOY%3u2=<g)!{4WbYYB3Wv;x+J2=oo0&E;N2i}sflmV zs|8RdS0Y4eC8+Oe#tnlIrEmffP3$2>vg?N8df+vSlWgq@Pda+SCwVP1L&WNrIC4K# zZYav+0~Fr7eCG=iE<i4CuiltXF;b^E|2#%Jy5-XDSl&QH-kT!uJCNRbFK(G5IwOF= zwLZ8zt5Jx-Rkl<z?bDK1_B|>h(REArVBp(~Vj^;9Zw!vmci!zBVgxUGH*<m}i$(wU zSpZL_n8MsutdK#Rjg&cPP(?v$!~vP~RGbN=16+w{Uf)DqULP6C0RKj1w4iTgcc-As z0<(#n6+_9`_r_qvWESNM$@?nyDt^A*)gRnvfh6h0@!GZn?o>>}reCaZUb_uXNHW}( z(gc*l9K(cQp)YpkD3@c&ffM9&DJCJ|AxW}fGS_ek(L|?2A=uMDCK+nGh-vuvAG?)K z8C;`qMQg;JR$+4JzxxN<@LeA5f|JYSlS_(+u+0r4tGX$UI1S5buyhQtgC0gLKi^0x zkR~?_S^T8B5@{|i{lMmB%yW@&o`}q>nfreE6_kUO`(Di(0YJI<-+~uD8_eixAL_SY z5ne`EvM|u<$cn%4=a0hr#ykA#qk@5KgAlS{_C%EKzeQz+pd+@O$gjT^Z_1W-8oDKf zaz|}0T4R3Qj!RoKy%yAO(2xs3G0H@@D(3n?F6T@XBC|{5bg@@%=Oir~okg8aOjw*m zU!tl|P0XPXi0>A6vD14X--yJ+0v3acO{glajz^60+vV<C+^*Ot*iGG6%@TvN!rZ%o z56hF4TM2QM_{Qy-`3U2qFSTtwaJc%D7_0bJbz>U*zYDaMACvYiF!9V*ZLD4&9EBI8 z9qOL^j-z>HZJF+6kF_<>ZfN5kP#$MadlFZO_&bn9R^9$h7~Cujbnp+{5KIR0+Mv<Q zRElisxA?Q~Y<vWzy3N^Ww-hEDVA5DLQBu7^L`sAq*zz(>wnW(4gCZN?BMZv%uk9pv z0{36^W{+%P6`8!F5}N?(x<nO*Hya`M|ElOL!>U@MFic5YQlvw=LrOwArKL+iKsqI) zr9)D>yIV>S1f;tJBt?{v76hb)yYQC}Jis}#XV#wi-goW8_(%BSx(p#9fD->DThVTU z9J{Dp0S80Zkr>0X;oFGwq*1{KEqNmToLUTw)9O#<np}n|)XYrqAEj_*?S(T%hGT@1 z&;|J;4dwqptVVo@LxgH7+hA}sjrc{_x}b`=KT7W*Gyc#L(m<|iDYs{0Aa))`tmm4c z3Vnv22u~yjI&YMD>gvn3C399yKa@#w4;SB%-NXVB87}Iv31PaHaeU>Z2K%>68tk3Q zIicvR)q!-W+mDLJhNM6`y4b_OR~n<)zP8>q<h9gs{eFVs#GCTthL$+FQC9(1`3G`n z;L-&deI}Xb+<I7I+T`d)Bzbo{j*F4PJx@iWg3~VQkWWM%vB$q9mAZoiOPKl4Ekyh3 zD3$HIdU_~is<6YJAaDx~V4Dg|TCnc86bclw9_`;dyd12{^TBp|HzrAKu9+f|Is(R) zA7$Ue(V4M%WpVDc$>TK9BSeYBJsgw(<Smt9ksdjP37NTShb4LUI!i8V)Oh^5SF7~i zkcL;)Pf9D<7zNpB$mcmmvr+K|o`v+y5VltD%Gh*VYm|?SO{TxbF3FUc^z@qAd%Md} z#B6iMDlYvTM?3ycD|^&b&PS$KGEp-^@f44usk_ikwbHhq;)gtCo~L!_?pIVGli}e~ z;pzJm9FTy_kXA+=!r&W~hlGeb%vPdiAuKPUFuCEthZT8^^_XB2F&)td(LHC<=_e}l z5?_lfIrXE+9%h-heG6uz3iL0~5v!{Z3f3C%xce<ns=t5ocpr^tu97y-m5Y5)mBppy z@n6aeY8+a;sq^Y<A*v?FewKY>RMd69LBVjgxV-RhsS9;XXmkoK#tSa&u7=yfUOWVa z3M7*GF&xpgeGQz}d?&7AnWbE2NE_Up&2q8);?mfkUB7c(NY`wd(bUBxj0~~AE=H_D zWa*)m{H8%tmgU6Fcg$v1NQIC=9%QnHUNG-WnYZ{hN!80ePI@Aolzx&n+Ei-dZQrp- zBQnwsV`R9EG~O;+)<obmJm`Tq?c$MQ@E2410`9<67BZ@|Ugoz!UmDClCmLS$GMjBr znX@ZNWT@9~FAhF0J;|Q>s;-py)rloGgTy<N8XxaT((o)+$Ab)dtb?*xiG%Lq!FgqT zWK)Gb%!KDDYfnD5YiaahubWfO_J0ZK?&>UB#OE^gVfb~eJ|AluhS+c{)yR%R{&I>n zo|~?lUm<ARiA8;D(|6QG&Ix^{86IXpN$!;vk1)38c+R#L5h6&<D@pPrHH4y_yWx6V zCN)q$EN|JRECA#3wW*p=P%AZ-UhC7$?_#dCRP2|0p8s|EX6tkiL)a~CyENp2w# zUPNkoOJ^kk_R3F!JmI)_PZL*B+8#xl7S$$J1rPoyH!mJ`kX+2|<vdhX{cjzq(?emO zN)2f&ucPh1X8L04ymfSQi3YC6dzqdFsI3}g<qy-}k-RHUmTSj*5q^<tZD86pc(`&* z*A%B%poV0Jz{$w1L!`K&Ca26rgWqRrC?fccq9~gL4IgJfidJmw=UA;2yO7Kjg+8W0 zmzh3+Y?`il*}qp5td=fjCEOd*n$tgm@&EbXp7|%PC@+c=b33uUW80h?F$kt$WV0bb zv1aH_9x?~}^9Igr;AD)xUWQG(B7ySJr`^*!GxZ}Mj2AQ6IIMI|L#@BUsMFIibY=lv z0c4tjZM|`oy=0t+1dk~Fqyj#ptwCG(g5fEoV|U>-L_d2h*{W!!0g5Q{vh1AolXO&V zI+ttD#2_+kYcsTKctJ-mYd>ZxLY<hm{j~{8Fwae_Ack<AyodT*y~PMXx?khj&-L{e z;Jk3j@Hbfpu=n$iuYQ7`17Gz5OwFj0K|oAA;0)*DpXt0-X5L{s-fJZ>N~xR<b2XGW zl^od0afQ79dA*`A9S*S>#gOtQ9dHjArtyn&3D;Aa*ZA+lj>y$L3^v2k-PX`I`b5Hq z!UDqHbYg?8Cig1$v0Aniiy6)EP{MI2TX$<drEnT~Uv8Je8CmpVJrVSmSU$<H(gY%= zjcuC+&vyiQ@tR!>--D(>!dZlKIb)pzzYk-@Lx{W$8m;5)r&r6Qbg<KP<#CXWU$lAt zxxJpar5;-ipy2WWZvq&H|Mj`ECiA%FcRh2-^*pm+lFrvHIU_=~v1@k#ZV7iuPp`N( zFoHP=!=$V-Du4XjSsZcqg8}C@pkWvf81Gb@EZ6Y`h^?Ibua=BHdB~dHAw&P0<6O8$ zL4|~jV|pN(w88J6w_C#<oBBFX3HW~F*D(AzL>zfn$!uIY&itv5E!G63hESK#yFFfM zVrIHh1foTKi3q_SU3VSnN3~cVqvWL;eQi{%&7aATWwioF)QGyEgcEwohUkc5l8>Y7 zJG0m3SA2f{zgspb2E1U<Am8+cND4xw>j`*4+PX&ChK2x4R{NqpgCGGgxY2G7C;b4L z9>DFh8q4_Lyw*RhDvWK8wQ>fW?gpUGhD!@LZO>Eg<QK53zOq#``(C(gMN|W9zq!7E zXbn(K_HHXg&e`D4<cRu6_&s7{1Az^OPY29hNIaX@+}j{R$;il<nws)D{-q7Ej?Fac z`%M=i3L+y9y+cUYuK;$y3pIp)Iyy~&c<z9{(Wj=y#>S?mCU{*4RHIrSnTIVKAoG1z ztoefDy5eKeIl%F<Z(8~QqjYrSJ|!(J!))CI2M^A$$*HMxY&FCKe_&3x!f`ZT8qLkY z4-A~$+4pRmEMaqViU;#8Yn8Gu92VM&O$)=e2#3viU>Y0MnaM)u*6%c%^wWPJxZA=R z{F&IrI>3}!V911QIus(FwE!E)`RxV0j@BXE0>talN2t38axOT7Bmm0b%n#!xa30wO z@AjGK-<dcXX;k1|HoG!o5y@;i5Ro_XYc5q-uxWC5*z?L8K4+AEWv{Ti(fBfCn|}UP zBPTK<@3yhMp*qPz?AXGKl%_rIm;Hlzafpp>l?mL5oxu<G7w`*I<9tZiK103^7t<cN z?9JV}g-Fu$kq_WhP_vie)j@s$og6=*1>vsV+_6z~+(*W3o<j)?5MrOa@dq`CO{dBl zP~6Jx&DqY5Emn&+%%YBqUzs3pKx}(>H@N|9F9TNsPTU3x8g#mJ&AhFsV2$R&>N&i# zuyn>@0lN2-TEV$KVW}HV`n>)(*Kjx|CMJFc>l1t$P+~B84!`>x7&SW@0i1)S0xHdS zfHg2ykZtk<SB9V!axTE$VvwPLiU<f5Pc;i1hWUZEBvOBV%h5C-SCDUQ!JByjUKhmx zFtzLT#Am3+Pw<9gC3;_-b)2t8iT~Sv27%ulHa}l`clCD{2q_=vSwPg`D&E|6@%#ux zvtOzyFNbK*W3kC$sY1K*@9vy96dG(YJ_vrOzP~wJhAH;(<Hz#|rW`$(7=>~%FclJE zy`OG<>3Kc+3*r5j3T?K*eB6)Lo$!0CgilLiGI1zGUTrg^N>#VKk-f5+E`7Z-U;eSk z6LKN7r51>SKymZ_)_5oR0l@Gu@&KIm^c}_iR57OgxN^|6Vu40Uqoc5W6`!+>{i^3M z8Ii4aP*PwXX&y~+;D=&LOP6c12+?U%Ui!FD+>$bOPOf+6Gf~W07_@E_ASDHb)xs+K z$ull~dkwBMhjH6ET)*c4E}$ZbL-Ysfi=?;-&{CsM?jZL#`Ja7S`8qShZus#Kn6*>; z-;~`}_`!ClR!$#pQ28>I)41{*8wpm#Ktus5WVYH1x1+lug<Ap;5LlkF>L&x@H+8_z z(6KW39WIC2-k$)*?G(_hfLs-pPtk7cBvQwI(-P4m<LHCe6s2(KppoV?%(2g4u>wE8 zxjFmX>~IB+Eu?39z$tJ5&j0>&a5qEhs}h->t$x?h)%D3iBjrPhPggGSIQTB@$6v&+ z=>uk`Z}Z<zF!jxXa2hE@CVbXn1VC)%ww|OWtYpgZHG@($XXHa^=L0X05+bcToGtqW zBpxxCqTopT{`)&eNJt1p)dLR&BJ5>o{CbjYd?#7`S-T@JU~xlWjCDV0_hVfoe8B~# zj4Fs5N9#iXyGVU6esCIn8g#)LFKScpQdj?y)9%xjRGM^W{K34QE!SiU;DrnyE;p69 zpD!pX{7{uan;7=9vOg%-`tNd*U8hzFyB0M%Q=-%!spyn=OU2qIkdIA~BWxWd_~nAK zt-!EkDt>|GiSl1E1!fiI-gucvnQ%mDiUC+yJzH@QlHF;jkSUjyZCz~UTHQ3;Of$Mo z^?2~x&0^&)x42p{CXxbu*0#?R`~oZ(hJ2O6vF%U)UGNR-ZMsBda%EF2*tMprD!O0` zoUwKd_-+63@MXD1^2?ap;0XonSg!hj<>|g%oazU67^nkI!0mlNy8;Cj<6fBQ-KyyT zk;iib<mc`-#C48sw^o>qDGr3iQDpq~TUR$w7oC0O4Zy;!htduOw^QObIAKyBq$-&s z!4PPpM*j}N00ewc(b@|Nr0kZ#MS+`-r1okz<|C1{Xx;*5GN1}T67H-Nh#&9xYS~2k zjtT2)=m3Dld)I7nakMcZay6<Vu<Qo4S)LlR@THxdT~t)mbUELXq&p4wj<UhJX6E34 z{M;D?Y}nh(Kza;R>UKx>bGI86!Oy^vG<5n%L}%&*)UO!Dxmv7!^--n~7bVGQ%g;#Y z5zf&GDw$&&r!33z*G(Dwm*`F2w~Dx}Cl}ccO4_qOSw;87g2AaQE7NPRRDlZxZ%PPc zRfwgR;XP^*euA+|f5UG(gYGW<8^`ZV1oz?F5B;DpO0`D}t~vP~XWrpOP#asoCdV@v zB%QF%5WL!JxZ7Yb*`~8wgV2ZaRM_i?{x>|V2q*-}V_SlWBDlKSZkIqgZ(#v}EO)#q ze(Tj4fCzDUC558T*yFi7*OEQBE{zuRnISUZD|j^m_b-a3ZQOL`W@n|i??mw?i)M$p zlrvMvU_nOy^ee*-6^o=6+EtY0%gf3<L4vt6q<rRn4}fqFwBUMS!p|LK8*Cszux|wE z{uWAauIFk5Y$ctM?+PpE3Cm}nuEqt|qM`E<_9G&YmRH`avF0Q@EV1g0=(2}z5%ktL z0$}TpA-~(@9Kduc`y^*mefJ-jk3euhYfYtkbMobQLj0h`m?HBD&Qh#NP%QsgwLCf3 zj^a@wwqweH6T-Fqu(4zr2XE-C){%C!7cr5B2@*lHOW9dkK(QWuYEQ5QL+E)@(O^71 zc*`&%cgE(%NGh7-tM$SAqa3jXTUiYgfx0ziWrA*7lT<f{XyqjIG%fH~{b8*DwRD2+ zF36&RxG<;BmND(Ge7?OKXV~>YlZfW?=a_{uQFh?u;h{h^{r4-=2|6bxfg8cH!BtHP zpf1UQO3V?v2Jf;N7A@F?2h*h!a3eZwzw37dpdu9noE}ti_xV~=xJZVd{n{OtfU>14 z|AN9qt+3c+1T_jaS5Um_at6e#7V=1C@Bb29{kO5P0bk4YJyL-1AD)oOq?~rRALfL8 zojQgpc?kL+{Fzhed4N+x*U`oZ_qr#PvcZ=3EvFf<S%S-I18<|pi4=CQr<hkS?nVF- zS}I}pQJ%MLUt6_zVL__=yPAOw0^QSh&^l1p*f@jho7M$8Fqjo57vkdnpb5dw2>gZz z-M2ZL%g{xjl)`>-otvwxqZ142HyEezJMZ?QUvM$c-WlN5aAuAfG}%b;T72-;Ww&}< z*R*jZCiQA&N!{e#+WcQb7A=MBJ!*7{5J7W<>H6Z?<~=RsEG7jn6uzQGM2w@5Q<88) zuZ?7o+Cll}TO2{fCJP~@8p{v>)_s)&)+;pSX|AA4`#w-}gBpA{%fcV>(3RdChKmOT z4)MWm^Q3-+(`PF`9BS2_CkdW{82Cg0{uiKHcX<9;1z7kK+Ji{p`!F_l^%GbiELgFd z^EG_#-m*-%8=B((hMfa!5!=C#IfDj~zrd2C4`9kZHJYOo^F0TL#Hn?gagPhE!ZHhe zQSTGjMpGh11AbFK4O72|_>^%Mn|)m{GPzo04w<a_!^7hx?g`P`Z|{M2gYN@!$(`+G zhaDIXe;NqVNy}yqxu~}rTx@7_xqvD>o-2L}orc+5rrp)e-+`t=>)g{=iUpW|(2oTB zRv3$CHPzM7QT4-S{~7XEg}#dCXO1Kq=#P(}vR;9~FTrgG%NPI`bwLMIp!E`RC)$Eg z;}DoSH=F)9n|FOprrjaW9a}a+iH$o`TtKyZY%_&&p11bIq$mwl4=-DroyAci5DP<j z<5Sqr%r)Qp99pH5KkPC8s#~zhAzF?;Ml>n^AZsQVlQ~rxa<MgG?vM5}7KJ;MnzLyJ z&J#(=$=o{|B`;tTt)ml$P4mT_(Z&NBw!og|U}KYhSzFcpBk4y36m^Ss=_%A?4JJF) zFm*jR4Vb)-lA%Qpf`S41g|wCj^fQ4V1B(%MaEF$MQgBx$l2!NeYFV#O$YXy*)rmAB zU36ObyHm)>T3>dZtnwVxuD?n<OR+JQ*e6bOg-6J@(Eb7zSrHKj=OKKPRVQYIyoa)% z6$Vk%eUHR4E`yzljJip(8CY$==Zr`hJb1VOS%><oP-XSBr?JP85d;H+<~-sz=PwJx zVkqWl999H-_3|sf5!^bU(R$~l26P2c6Ezbov(1<wP?3c^n4wb%6~V%Llg_^b_h&^1 zY+e!lnV<CGdicEP=z~NO3uRLCh6Wlz`4h_$^%pyGJJFAeZ67XBCWJEeVc_p<6k-4Q zk@bhBT=!(UUPaJ3CSfyq>!YfCR`!%p3URhcR#*zhGzWP|*-x6qUr53CxENUR`s|s| zk>+UyapU|^b5$K%sQ-|(a$!cMQ1;z_O;8lgBf>yyWN;5baNR18BAuQlvJ2B<CdxWZ zfGC0PEzVm5Jo{Iax;CMsxU1OTGDc&trIxs}sJ8e_R`1(bnKVloj42~Xw@ZjU{O&d- zIpoa!>X~1KK~Qzd+olMF;ry_AJ-RF7-TJx*iXBtT8z&so+416eS+^4Gnyb<DuO8ea z(d`$tv0jHK9VQa7lUDOtwCw1aKen4{O8bE-`D4>pL>}+0x-U%xl93z5Ac}BLHR=*C zIx@P|Ptss=b7B4jswUG+EUZg3#o)eYalNk%wHQ=~vXg9B1TDVlki`GlLn{$x!RpS+ zJ$^$K7}6rFjuqBO6CX6Yi5Bu7vnd<{sm=qb@<_ke#~|~!*HIVuhMro@xxOTP`5|pV z-wTJRNpQfKuOw!&Qo#(hCs;~1D9>v0^Hc?WI#;0H2yr@9EdtAhbHqa@{^%LXuMF9= zKlw452D|ZaqAWO;P97v#D>Npkbh$`&lMgv7p5!$eWjt0wE~-|1KXDLBsbnCu+oN$6 z)`&JqBQIg{EHYkUk}LsX&o`ePm2|#0uV^Jc#8}x_rkL!Is|iQJuB)ZE4IbU~+K5;V z>yhf&kO5&fcN0s`7wrs(#{rLi*xje2nTj)>I?>lBGfodgxPj*fCB_B)vSeM#!ryRQ z=x5UJ<8f5w8pn5`s27s(HfxFdh<Yyhq)kTree@46J_U*7eRE&jW!!zeaY9wKLlX9( zi>af!x>pS3gBJH9m0}5XreB)bgaquh@o|b^4aN`np|3ho^rhSP*HJEgXj!LNsxyod zr9{zy#~NzO=WvUpFO0#nYt6K~n)bM`MCXo?U-ZeDv+Fn$$kkE0;tr5|o(b}zd@G!f zOxAEF$xIJT>3hh^C%H<kV=w82oQ`0ELB`p_ofaFN9gc^WT&!20ANx7IT}d=2q!Ym? zBPl0tRZasfSpCBnIlPXPoR2j#jaepaR1NEs3SRW2=1TYpS>d$FA@na4abn~5+vmG1 zH1m3kBG$PO5@T4objGz*>=j2*)=e^k1`DWaF@`63-nb&S#H8&#&HRCX@1A^rr%+%g ziY-Gd*1K3at<eZG`LMU7u@tU)MSNJ7r_|WUj(B9c<<u6>n@G3QOOITLp126lxh}8; zD9lHbN;I#Ycx^ohm@|-{GLv59OgdggmqA#>>LpRb=TQja5#~}ff&S}z8ENKm!#c0Z zcQl&+CV%csm0ywAWP19KAwye%NJULFew$Y#^~1vq_7uiK(}hWf0R=*>i4cwEnal(( zvFs;a&GsTGY}loe-=tky%nOuJg_gym+D#_9UILyK@!ZK3j$Lbcs7&$AU*tYB0qu@N z7gF9+k`PvYqXoH7%9#r92h-OH5gichaPx(p>?@dZ6)1XH!E=N$efBUU@_X&a7rU)- z^oLE(bO~f9kIaHe)1~I0kJ4v6!NP1qeDKW^Bh;Ow8qYnE2p>gq=ayslTLSr<DK)El zQugqTZfbIG)5Bxuyh0o+F~=5{eVKZBye&t*hZB~uo>yOP8PvjXDwQ$tgSfOF99Gfo zw++TF5}c(ATBam$w6ZX${1Nl#LlhoJE&A(U9T4{!i;R#v{iOOhzR2WBDSd|Q`ucIc zYs%-$Hv$ZZTbR}edvq@-D=eCat*%6JaGkK1^|gBj6!cF$Mf9eVIbT?1k2NKy6}V<t z`kvUPs=h{{X^@L7k9v#!**C;=(NIJwoE<6QJ!5Orh}(PZj@T=#$on;TOkrec^^M0O z&OARxz1oe1h;+V?n>pXcV+!gGHZ6>#9651TVy8dOMWXx9%0O4SToZwThbzg<W+Iuh zGF`uwY_zz(E|NcnqI@eqSNfhyz}GxC!X6%xQoA5@g^b@8{y7UfCMbz2b`e2V{j1wa zL{v+qSaw^bL6Tf6Cil(Rirn))bk7oI8U!F!C1umdoDnEmN4Ib(AT3_m=MG%{ut_;3 za|(7?5o@mVeQj>M`%o@jja6VK1r@<i^ud4)`TN}ZKfO5AK0{>$#XGYd_|7bHF%?Ao z{REZ)$95|R0#1z8tsB0o-b!P}DQ<>ib91R>aZe@q&C=`4(UweJWsrJF&4qP-qp4N- z%_eQ1;$f2_k)Zoe{QkS?`+`DNXdkhXH)5pk^@>rb)RTy`6#bi?XL(jT9C~TQ-c<ad z*gMB&t>GtbNK8Jxm^y)w#7uN;*|dMFE9>`YZDKWnTMp(|D|=0?nG3&sVrQ@Zq0Wu) zGt4-cvusc_QY~2>kM>@~ZuDv5WqoN0`(R4!p(1baL|=x`OX=yC7Y_TIy{gBg@%DI> zwOp@92z9#a5_+AyH*izry`Geky{QdcldUHlLNECv(Qh>H9&638VP(mp^i$Tkqukiu zpYejpsj)Jf&lL+v_(!HuPbQg{|Gcg8xc+G7UgI>4i(6cwbJmkizFvYfL2^G{T6gU1 zqAan=on1Tt6NT#@EmhgWTTIWI-)Y9R5yCCDRs7-)-|;u|kgRx!Nfn*xCU09m4?#Ti zl8m-(_)$mY!grmYF+7>_;r;gCVN_m}w(sv9R`hn?4ZPg``rdIke<x9ty`Z+nu7}|3 zsdv){i`>wrw7O8$jB=rWu7bV|_w2SJ$9$<NGc`6g$(60bx6o@dv|m1)#BkiwN)nsx ziC=Xx8DeBjC2Ccu-mpf0|5<JbCAlX?kf&eEVJVVPX3O<zVIQr65}8-MrGJ|J-@8ha z=jf5HnF{<|Z+iJ&J~@~fEXA6*_7#zgrMVtd_Vf3DJ-h0k>`N-W#j<C-X(R5QvbZ?s zmC>d5gSh4Kk<Del`uF`Sv9XPO_4Mz2R+~r17e#2VClTcl5YV0PJ|jTKzK9}k^Wwtu zd*kn^1q==OSHG}7@p-q1Je@KT;83a>wfEp%jQ4x1NcKymqk1LOM&)^fJsE1K{C_1j zdY82H4f~$`$}ba;sVoT?2GZTpgWg$U%DJTnQN+|dFOS6xUU1h43z=})n-O>|e)wR= zuC#^~H=m8XCf%Z4^Zrd&XpJqFwyi1pX432~i`t*7Hp%EU1bLy-j8Q2p#u&-Qh&Gfk z*<Kaz<W>%qBO{FF(Vxtn5BX}x*D;VYQ~cQNEx+aqD9$>bX+8O={(ZwOK7nXbQvVnE zRS7WzdM*Xsw;SqYRRQa{H~f~Rg^n%^+s^TF=r(?-M3y%G8LkT`%T<;MM5KyC_MJ_% ze8)py&`6hG&ks%D<o(UNCr=(Xnm_$d`k2kR>}(fXZz!+y;NU>2LoAmE&6Za*9)*CV zbn|!!nbS3NfK|uZQfjG+1uf-kc_F==iSQfY{10|&T^(JYxpsSHW(MNJzkAJ?#7w0d zt|Dy=6RJJWEKP4CHC({gTtHf$ESibFVm9+#DT~Ios{U}Xxyh8ztm3xiycw>;%8CA9 zx@hdiEv(N?B|F9?InC?SBC1{Bj6oW<Pe+lS*w>(;GAlO<_H$l$MWjsI(gW*)2U4Ck zc?XJPb+Iiz8y-_Pw5Cp0>(m@P878(rz2xoL!na?gt_Kufkm7MAiw2N;%!}cMw`skp zcl+hzb71f@NzFV1!%Le|g%^8?P;lJlP1Wq~y`c$}NT#QaBw>iQkzV_3%kSw|?;(!; zJd)O3B^+lv%e2JG3RxSj-`w0pODuD9pQ_4K|5PJ2zu0klw!1u+BdeG4hK21h9!{|J zE%7u1Q<6~4gkSCRXNjjW_{W@BQ#B)P(WZGii&B`3B_*tD&ZleZGLzphgzEYP$9CP= z#;T95uCD(5bI_q9<HAa%`Hg@eT!EGo6kxlF6OfICsld_4995{+bS&Q^P(Xqiykxj| z<o#Ljw^DqYTi0Vk#G<`>_l=p7k2w|ZtFnHxj1%LWK;$%N%IK_J>O&x@jlh4s;%=Nq z;xQKJh=0|PKe_g1F>MyV*ZITP5H4;ZJ!)?E$^OVX{lX{2Zr(u)hRuqEdlYVr!Pvj! zlyPbCBr!-I<wuyJ=y<Qtt7qV{2YY9vEnohcOtlJrGyZ*9Y-w(8?sOsKF}`!Naw%f@ zrC5#rY5y|+;~2XJ$*(jl(|jrpPsU%0aUOTHw++M_V<Acn!z1nnPV0Pcl>-p=giHAa z_`DfqcXTD0K6iBJU5cs9rymPWpXBUOf4Qf8GTKcw5?ok5v)T5HBw3EQg6Pr7JEG{< z!eepl<#iM@f3Dj+^VEDw#%WUDt1<Z0jjGY!uq+cuAKDb#&po0Qy>vB6{XFZCIPt90 zak9$NCV5k0Soh`(hlp_Ym<9XjH=@#0$~Pfc5l>JJXCxXc6Id?B`HtDKC~7_8*uTXu zmxQWvzH#K`-0E{~gwIP;$9MHAvdX((QD2E`<g(wd#N{xc_CfW4T>IA)@hmrP<zAo| zxp6szO{)y3z=F8ZtMUKYO2}T~guIIq*4be<GDmWV)eO^KO0f)Xq}H+^YcKTc#*>do zcWX{}a|sE^?(asKJ8EI1NitYhRz(%QNzyL<#lpLHTWWbx{!JHIPpqslu}ztyQZa#V zkT+d*3?n0^O0d`@F>Dmo$JY6SWgJe@-up8)BhmJ>&0{aj%#`0eNFm!wPD+J3FMss3 z)|^%lB=e4aS3StamgCqe5_<n%ar_6tJS0)0aa1lw0~uC7)@2f+t<Bz_hu-bKb4u1w z5X!50vTe&-qF;*78n3q09|@f<Jx!MjZp?j|-r@HG3)`eg<un58Ef1#F<s>0pcIK7& zp^7qsjI+m+)nb9;$;gCin+oBCv4_9Xak1Gk_J_DIk%wxO+|p;++|;+&6_S_*5x*MI z->d~-B7tRSp>O>8y~EPh=Sk7o`(I?W+r(!yejqPdO>-J7KHB$C3iNuIAUJs86&M@D z_Nera9o6agQZL%v{@teE{{+t*nB?dVCuvJR=vX*T-aIDUc%-jWI_s5mYkQ#dJPvyO zTk5j)cko`b(;R4AWsM)(A1R<%BF(qf$ZNmFW>FM-cYJ)KmVjxb5JQ$#zanQgO1yAM z^W^6+-nAl`*WrT^uYTmAEcq5D<^Ogyo(V+fxF^ltqML9s66&_BU||dOMMcr*C1uLs zvB48e)TzmiawbX@J0l-0sn{yJdW~sWMr@o5F}%PG8KsQptl1sz<>&%q+0B<w_^kEe zDY9LxsQ#tK`5`}@_|BZTIlbHDNpWiRB}0Zuk9l!E(bVO;xpyDVd9W;82%aBVH%s!a zNWZw8x@vMlw_+O*uUu+!$x|wo^XjtxLO*Tf%MjI)F_dIj@q{P3MN%a-K4GJDs!X=5 zi~nrz>Y0|{<6w-vQYpH>ZVGC+Iy*Y7JtQBigf&C574f~UiufBw)J(X`&*u(y|5Q0k zp4bV#qs6APp>L7Cd0d!4%<wVWGLx5N0{OnmypjobynW|mYKI0Hk?r4{X(OmhAKCQ7 z#@633yh;9#Bjk_Bua}mZ`vc>Djy5qx>`10I|CNU|PAmzD6)8^&h}dCc?&0sW3s`3= z9@Px3L5jVxP&sOQ8Ub_bU@kLLxl&){F~ms3&JQ&G1>O2uSC`edQL`VICJ@NWx_H}_ z&b?+0sZV>LEx%CuH}^trHCp2`y`A1V8$~g85wC(y29jcT#QF|O%?mGojS120jqfPz zaSdY1^U*w6jb(Hc10NfU<+lf<{XLV$bUKST_ZVWy8fDIUD=-^g8rG$B&_9&<L-tWm zb$q1B>2V=5Jr)UhK)JBSm#Nze&zxxtQCdqbmBfw0XNOc6n3rK%><-;`pHrzIt143? HWfJs1?HZlw literal 0 HcmV?d00001 From a74cb194954dd206f3b83adf6a5d1562311f39ba Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 26 Jun 2024 01:33:22 +0000 Subject: [PATCH 546/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 76ddef59a..b9b0bd780 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -60,6 +60,7 @@ hide: ### Internal +* 🔧 Update sponsors, add Stainless. PR [#11763](https://github.com/tiangolo/fastapi/pull/11763) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, add Zuplo. PR [#11729](https://github.com/tiangolo/fastapi/pull/11729) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Sponsor link: Coherence. PR [#11730](https://github.com/tiangolo/fastapi/pull/11730) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People. PR [#11669](https://github.com/tiangolo/fastapi/pull/11669) by [@tiangolo](https://github.com/tiangolo). From 4711785594c7de157fc1b6556140c4d052e691a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 25 Jun 2024 20:46:25 -0500 Subject: [PATCH 547/846] =?UTF-8?q?=F0=9F=94=A7=20Tweak=20sponsors:=20Kong?= =?UTF-8?q?=20URL=20(#11764)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/sponsors.yml | 2 +- docs/en/overrides/main.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 39c51b82b..013c93ee4 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -26,7 +26,7 @@ gold: - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral title: Simplify Full Stack Development with FastAPI & MongoDB img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png - - url: https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api + - url: https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api title: Kong Konnect - API management platform img: https://fastapi.tiangolo.com/img/sponsors/kong.png - url: https://zuplo.link/fastapi-gh diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 2a51240b2..64646c600 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -77,7 +77,7 @@ </a> </div> <div class="item"> - <a title="Kong Konnect - API management platform" style="display: block; position: relative;" href="https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank"> + <a title="Kong Konnect - API management platform" style="display: block; position: relative;" href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank"> <span class="sponsor-badge">sponsor</span> <img class="sponsor-image" src="/img/sponsors/kong-banner.png" /> </a> From f497efaf94625b00bd8a2aa75162f5dc92890d6c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 26 Jun 2024 01:46:45 +0000 Subject: [PATCH 548/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b9b0bd780..2c8daa42b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -60,6 +60,7 @@ hide: ### Internal +* 🔧 Tweak sponsors: Kong URL. PR [#11764](https://github.com/tiangolo/fastapi/pull/11764) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, add Stainless. PR [#11763](https://github.com/tiangolo/fastapi/pull/11763) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, add Zuplo. PR [#11729](https://github.com/tiangolo/fastapi/pull/11729) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Sponsor link: Coherence. PR [#11730](https://github.com/tiangolo/fastapi/pull/11730) by [@tiangolo](https://github.com/tiangolo). From b08f15048d1b6036b9c027408feb86cbb8a9eef4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 25 Jun 2024 20:52:00 -0500 Subject: [PATCH 549/846] =?UTF-8?q?=F0=9F=94=A7=20Tweak=20sponsors:=20Kong?= =?UTF-8?q?=20URL=20(#11765)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35d0fad1f..acd7f89ee 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ The key features are: <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> <a href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> -<a href="https://konghq.com/products/kong-konnect/register?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> +<a href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> <a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a> <a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> From e9f4b7975c2c6055d270b5a71127fda881ebdf04 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 26 Jun 2024 01:52:20 +0000 Subject: [PATCH 550/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2c8daa42b..92a1474d6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -60,6 +60,7 @@ hide: ### Internal +* 🔧 Tweak sponsors: Kong URL. PR [#11765](https://github.com/tiangolo/fastapi/pull/11765) by [@tiangolo](https://github.com/tiangolo). * 🔧 Tweak sponsors: Kong URL. PR [#11764](https://github.com/tiangolo/fastapi/pull/11764) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, add Stainless. PR [#11763](https://github.com/tiangolo/fastapi/pull/11763) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, add Zuplo. PR [#11729](https://github.com/tiangolo/fastapi/pull/11729) by [@tiangolo](https://github.com/tiangolo). From 95e667a00a93c96b0262305663ebd1599d2aec94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph09@gmail.com> Date: Wed, 26 Jun 2024 10:53:12 -0300 Subject: [PATCH 551/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/dependencies/index.md`=20?= =?UTF-8?q?(#11757)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/dependencies/index.md | 353 ++++++++++++++++++++ 1 file changed, 353 insertions(+) create mode 100644 docs/pt/docs/tutorial/dependencies/index.md diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..3c0155a6e --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -0,0 +1,353 @@ +# Dependências + +O **FastAPI** possui um poderoso, mas intuitivo sistema de **<abbr title="também conhecidos como, recursos, provedores, serviços, injetáveis">Injeção de Dependência</abbr>**. + +Esse sistema foi pensado para ser fácil de usar, e permitir que qualquer desenvolvedor possa integrar facilmente outros componentes ao **FastAPI**. + +## O que é "Injeção de Dependência" + +**"Injeção de Dependência"** no mundo da programação significa, que existe uma maneira de declarar no seu código (nesse caso, suas *funções de operação de rota*) para declarar as coisas que ele precisa para funcionar e que serão utilizadas: "dependências". + +Então, esse sistema (nesse caso o **FastAPI**) se encarrega de fazer o que for preciso para fornecer essas dependências para o código ("injetando" as dependências). + +Isso é bastante útil quando você precisa: + +* Definir uma lógica compartilhada (mesmo formato de código repetidamente). +* Compartilhar conexões com banco de dados. +* Aplicar regras de segurança, autenticação, papéis de usuários, etc. +* E muitas outras coisas... + +Tudo isso, enquanto minimizamos a repetição de código. + +## Primeiros passos + +Vamos ver um exemplo simples. Tão simples que não será muito útil, por enquanto. + +Mas dessa forma podemos focar em como o sistema de **Injeção de Dependência** funciona. + +### Criando uma dependência, ou "injetável" + +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*: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +E pronto. + +**2 linhas**. + +E com a mesma forma e estrutura de todas as suas *funções de operação de rota*. + +Você pode pensar nela como uma *função de operação de rota* sem o "decorador" (sem a linha `@app.get("/some-path")`). + +E com qualquer retorno que você desejar. + +Neste caso, a dependência espera por: + +* Um parâmetro de consulta opcional `q` do tipo `str`. +* Um parâmetro de consulta opcional `skip` do tipo `int`, e igual a `0` por padrão. +* Um parâmetro de consulta opcional `limit` do tipo `int`, e igual a `100` por padrão. + +E então retorna um `dict` contendo esses valores. + +!!! info "Informação" + FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0. + + Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`. + + Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`. + +### Importando `Depends` + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +### 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: + +=== "Python 3.10+" + + ```Python hl_lines="13 18" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +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. + +Você fornece um único parâmetro para `Depends`. + +Esse parâmetro deve ser algo como uma função. + +Você **não chama a função** diretamente (não adicione os parênteses no final), apenas a passe como parâmetro de `Depends()`. + +E essa função vai receber os parâmetros da mesma forma que uma *função de operação de rota*. + +!!! tip "Dica" + Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo. + +Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de: + +* Chamar sua dependência ("injetável") com os parâmetros corretos. +* Obter o resultado da função. +* Atribuir esse resultado para o parâmetro em sua *função de operação de rota*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Assim, você escreve um código compartilhado apenas uma vez e o **FastAPI** se encarrega de chamá-lo em suas *operações de rota*. + +!!! check "Checando" + Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar. + + Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto. + +## Compartilhando dependências `Annotated` + +Nos exemplos acima, você pode ver que existe uma pequena **duplicação de código**. + +Quando você precisa utilizar a dependência `common_parameters()`, você precisa escrever o parâmetro inteiro com uma anotação de tipo e `Depends()`: + +```Python +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: + +=== "Python 3.10+" + + ```Python hl_lines="12 16 21" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14 18 23" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15 19 24" + {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} + ``` + +!!! tip "Dica" + Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**. + + Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎 + +As dependências continuarão funcionando como esperado, e a **melhor parte** é que a **informação sobre o tipo é preservada**, o que signfica que seu editor de texto ainda irá incluir **preenchimento automático**, **visualização de erros**, etc. O mesmo vale para ferramentas como `mypy`. + +Isso é especialmente útil para uma **base de código grande** onde **as mesmas dependências** são utilizadas repetidamente em **muitas *operações de rota***. + +## `Async` ou não, eis a questão + +Como as dependências também serão chamadas pelo **FastAPI** (da mesma forma que *funções de operação de rota*), as mesmas regras se aplicam ao definir suas funções. + +Você pode utilizar `async def` ou apenas `def`. + +E você pode declarar dependências utilizando `async def` dentro de *funções de operação de rota* definidas com `def`, ou declarar dependências com `def` e utilizar dentro de *funções de operação de rota* definidas com `async def`, etc. + +Não faz diferença. O **FastAPI** sabe o que fazer. + +!!! note "Nota" + Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação. + +## Integrando com OpenAPI + +Todas as declarações de requisições, validações e requisitos para suas dependências (e sub-dependências) serão integradas em um mesmo esquema OpenAPI. + +Então, a documentação interativa também terá toda a informação sobre essas dependências: + +<img src="/img/tutorial/dependencies/image01.png"> + +## Caso de Uso Simples + +Se você parar para ver, *funções de operação de rota* são declaradas para serem usadas sempre que uma *rota* e uma *operação* se encaixam, e então o **FastAPI** se encarrega de chamar a função correspondente com os argumentos corretos, extraindo os dados da requisição. + +Na verdade, todos (ou a maioria) dos frameworks web funcionam da mesma forma. + +Você nunca chama essas funções diretamente. Elas são chamadas pelo framework utilizado (nesse caso, **FastAPI**). + +Com o Sistema de Injeção de Dependência, você também pode informar ao **FastAPI** que sua *função de operação de rota* também "depende" em algo a mais que deve ser executado antes de sua *função de operação de rota*, e o **FastAPI** se encarrega de executar e "injetar" os resultados. + +Outros termos comuns para essa mesma ideia de "injeção de dependência" são: + +* recursos +* provedores +* serviços +* injetáveis +* componentes + +## Plug-ins em **FastAPI** + +Integrações e "plug-ins" podem ser construídos com o sistema de **Injeção de Dependência**. Mas na verdade, **não há necessidade de criar "plug-ins"**, já que utilizando dependências é possível declarar um número infinito de integrações e interações que se tornam disponíveis para as suas *funções de operação de rota*. + +E as dependências pode ser criadas de uma forma bastante simples e intuitiva que permite que você importe apenas os pacotes Python que forem necessários, e integrá-los com as funções de sua API em algumas linhas de código, *literalmente*. + +Você verá exemplos disso nos próximos capítulos, acerca de bancos de dados relacionais e NoSQL, segurança, etc. + +## Compatibilidade do **FastAPI** + +A simplicidade do sistema de injeção de dependência do **FastAPI** faz ele compatível com: + +* todos os bancos de dados relacionais +* bancos de dados NoSQL +* pacotes externos +* APIs externas +* sistemas de autenticação e autorização +* istemas de monitoramento de uso para APIs +* sistemas de injeção de dados de resposta +* etc. + +## Simples e Poderoso + +Mesmo que o sistema hierárquico de injeção de dependência seja simples de definir e utilizar, ele ainda é bastante poderoso. + +Você pode definir dependências que por sua vez definem suas próprias dependências. + +No fim, uma árvore hierárquica de dependências é criadas, e o sistema de **Injeção de Dependência** toma conta de resolver todas essas dependências (e as sub-dependências delas) para você, e provê (injeta) os resultados em cada passo. + +Por exemplo, vamos supor que você possua 4 endpoints na sua API (*operações de rota*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +Você poderia adicionar diferentes requisitos de permissão para cada um deles utilizando apenas dependências e sub-dependências: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integração com **OpenAPI** + +Todas essas dependências, ao declarar os requisitos para suas *operações de rota*, também adicionam parâmetros, validações, etc. + +O **FastAPI** se encarrega de adicionar tudo isso ao esquema OpenAPI, para que seja mostrado nos sistemas de documentação interativa. From bd7d503314faa7ecdc443303997a24bb11d8dd03 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 26 Jun 2024 13:53:37 +0000 Subject: [PATCH 552/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 92a1474d6..32e6a49a4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/index.md`. PR [#11757](https://github.com/tiangolo/fastapi/pull/11757) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#11739](https://github.com/tiangolo/fastapi/pull/11739) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add French translation for `docs/fr/docs/learn/index.md`. PR [#11712](https://github.com/tiangolo/fastapi/pull/11712) by [@benjaminvandammeholberton](https://github.com/benjaminvandammeholberton). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/index.md`. PR [#11731](https://github.com/tiangolo/fastapi/pull/11731) by [@vhsenna](https://github.com/vhsenna). From 898994056987b2b0be591f11722fbbe5dd097827 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Wed, 26 Jun 2024 10:54:00 -0300 Subject: [PATCH 553/846] =?UTF-8?q?=F0=9F=8C=90=20=20Add=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/advanced/additional-status-code?= =?UTF-8?q?s.md`=20(#11753)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/additional-status-codes.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 docs/pt/docs/advanced/additional-status-codes.md diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md new file mode 100644 index 000000000..a7699b324 --- /dev/null +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -0,0 +1,69 @@ +# Códigos de status adicionais + +Por padrão, o **FastAPI** retornará as respostas utilizando o `JSONResponse`, adicionando o conteúdo do retorno da sua *operação de caminho* dentro do `JSONResponse`. + +Ele usará o código de status padrão ou o que você definir na sua *operação de caminho*. + +## Códigos de status adicionais + +Caso você queira retornar códigos de status adicionais além do código principal, você pode fazer isso retornando um `Response` diretamente, como por exemplo um `JSONResponse`, e definir os códigos de status adicionais diretamente. + +Por exemplo, vamos dizer que você deseja ter uma *operação de caminho* que permita atualizar itens, e retornar um código de status HTTP 200 "OK" quando for bem sucedido. + +Mas você também deseja aceitar novos itens. E quando os itens não existiam, ele os cria, e retorna o código de status HTTP 201 "Created. + +Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: + +=== "Python 3.10+" + + ```Python hl_lines="4 25" + {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 25" + {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 26" + {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! warning "Aviso" + Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. + + Ele não será serializado com um modelo, etc. + + Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`). + +!!! note "Detalhes técnicos" + Você também pode utilizar `from starlette.responses import JSONResponse`. + + O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`. + +## OpenAPI e documentação da API + +Se você retorna códigos de status adicionais e retornos diretamente, eles não serão incluídos no esquema do OpenAPI (a documentação da API), porque o FastAPI não tem como saber de antemão o que será retornado. + +Mas você pode documentar isso no seu código, utilizando: [Retornos Adicionais](additional-responses.md){.internal-link target=_blank}. From e304414c93e68f0298ddd9e23af0abfd3b8cd4da Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 26 Jun 2024 13:54:46 +0000 Subject: [PATCH 554/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 32e6a49a4..0e4677e20 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-status-codes.md`. PR [#11753](https://github.com/tiangolo/fastapi/pull/11753) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/index.md`. PR [#11757](https://github.com/tiangolo/fastapi/pull/11757) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#11739](https://github.com/tiangolo/fastapi/pull/11739) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add French translation for `docs/fr/docs/learn/index.md`. PR [#11712](https://github.com/tiangolo/fastapi/pull/11712) by [@benjaminvandammeholberton](https://github.com/benjaminvandammeholberton). From ed22cc107d55975dfe1015fd89e59fe3ee27f852 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph09@gmail.com> Date: Fri, 28 Jun 2024 11:57:49 -0300 Subject: [PATCH 555/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/dependencies/classes-as-d?= =?UTF-8?q?ependencies.md`=20(#11768)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/classes-as-dependencies.md | 497 ++++++++++++++++++ 1 file changed, 497 insertions(+) create mode 100644 docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..028bf3d20 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,497 @@ +# Classes como Dependências + +Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos melhorar o exemplo anterior. + +## `dict` do exemplo anterior + +No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. + +E sabemos que editores de texto não têm como oferecer muitas funcionalidades (como sugestões automáticas) para objetos do tipo `dict`, por que não há como eles saberem o tipo das chaves e dos valores. + +Podemos fazer melhor... + +## O que caracteriza uma dependência + +Até agora você apenas viu dependências declaradas como funções. + +Mas essa não é a única forma de declarar dependências (mesmo que provavelmente seja a mais comum). + +O fator principal para uma dependência é que ela deve ser "chamável" + +Um objeto "chamável" em Python é qualquer coisa que o Python possa "chamar" como uma função + +Então se você tiver um objeto `alguma_coisa` (que pode *não* ser uma função) que você possa "chamar" (executá-lo) dessa maneira: + +```Python +something() +``` + +ou + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +Então esse objeto é um "chamável". + +## Classes como dependências + +Você deve ter percebido que para criar um instância de uma classe em Python, a mesma sintaxe é utilizada. + +Por exemplo: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +Nesse caso, `fluffy` é uma instância da classe `Cat`. + +E para criar `fluffy`, você está "chamando" `Cat`. + +Então, uma classe Python também é "chamável". + +Então, no **FastAPI**, você pode utilizar uma classe Python como uma dependência. + +O que o FastAPI realmente verifica, é se a dependência é algo chamável (função, classe, ou outra coisa) e os parâmetros que foram definidos. + +Se você passar algo "chamável" como uma dependência do **FastAPI**, o framework irá analisar os parâmetros desse "chamável" e processá-los da mesma forma que os parâmetros de uma *função de operação de rota*. Incluindo as sub-dependências. + +Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Da mesma forma que uma *função de operação de rota* sem parâmetros. + +Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: + +=== "Python 3.10+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +Observe o método `__init__` usado para criar uma instância da classe: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. + +Em ambos os casos teremos: + +* Um parâmetro de consulta `q` opcional do tipo `str`. +* Um parâmetro de consulta `skip` do tipo `int`, com valor padrão `0`. +* Um parâmetro de consulta `limit` do tipo `int`, com valor padrão `100`. + +Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc nos dois casos. + +## Utilizando + +Agora você pode declarar sua dependência utilizando essa classe. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +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. + +## Anotações de Tipo vs `Depends` + +Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +O último `CommonQueryParams`, em: + +```Python +... Depends(CommonQueryParams) +``` + +...é o que o **FastAPI** irá realmente usar para saber qual é a dependência. + +É a partir dele que o FastAPI irá extrair os parâmetros passados e será o que o FastAPI irá realmente chamar. + +--- + +Nesse caso, o primeiro `CommonQueryParams`, em: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python + commons: CommonQueryParams ... + ``` + +...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso). + +Na verdade você poderia escrever apenas: + +=== "Python 3.8+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python + commons = Depends(CommonQueryParams) + ``` + +...como em: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +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`. + +<img src="/img/tutorial/dependencies/image02.png"> + +## Pegando um Atalho + +Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe. + +Para esses casos específicos, você pode fazer o seguinte: + +Em vez de escrever: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +...escreva: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python + commons: CommonQueryParams = Depends() + ``` + +Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`. + +O mesmo exemplo ficaria então dessa forma: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +...e o **FastAPI** saberá o que fazer. + +!!! tip "Dica" + Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. + + É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código. From 2afbdb3a44b6b5af0d6b07d435f4f7c7d9bea1bc Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 28 Jun 2024 14:58:12 +0000 Subject: [PATCH 556/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0e4677e20..e76cdbdcd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#11768](https://github.com/tiangolo/fastapi/pull/11768) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-status-codes.md`. PR [#11753](https://github.com/tiangolo/fastapi/pull/11753) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/index.md`. PR [#11757](https://github.com/tiangolo/fastapi/pull/11757) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#11739](https://github.com/tiangolo/fastapi/pull/11739) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 172b3dfd43eb499396ee35ba32b118d108a23da1 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Mon, 1 Jul 2024 12:45:45 -0300 Subject: [PATCH 557/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/advanced-dependencies.md`?= =?UTF-8?q?=20(#11775)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pt/docs/advanced/advanced-dependencies.md | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 docs/pt/docs/advanced/advanced-dependencies.md diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..58887f9c8 --- /dev/null +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -0,0 +1,138 @@ +# Dependências avançadas + +## Dependências parametrizadas + +Todas as dependências que vimos até agora são funções ou classes fixas. + +Mas podem ocorrer casos onde você deseja ser capaz de definir parâmetros na dependência, sem ter a necessidade de declarar diversas funções ou classes. + +Vamos imaginar que queremos ter uma dependência que verifica se o parâmetro de consulta `q` possui um valor fixo. + +Porém nós queremos poder parametrizar o conteúdo fixo. + +## Uma instância "chamável" + +Em Python existe uma maneira de fazer com que uma instância de uma classe seja um "chamável". + +Não propriamente a classe (que já é um chamável), mas a instância desta classe. + +Para fazer isso, nós declaramos o método `__call__`: + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "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!} + ``` + +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. + +## Parametrizar a instância + +E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "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!} + ``` + +Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. + +## Crie uma instância + +Nós poderíamos criar uma instância desta classe com: + +=== "Python 3.9+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "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!} + ``` + +E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. + +## Utilize a instância como dependência + +Então, nós podemos utilizar este `checker` em um `Depends(checker)`, no lugar de `Depends(FixedContentQueryChecker)`, porque a dependência é a instância, `checker`, e não a própria classe. + +E quando a dependência for resolvida, o **FastAPI** chamará este `checker` como: + +```Python +checker(q="somequery") +``` + +...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: + +=== "Python 3.9+" + + ```Python hl_lines="22" + {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="21" + {!> ../../../docs_src/dependencies/tutorial011_an.py!} + ``` + +=== "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!} + ``` + +!!! tip "Dica" + Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. + + Estes exemplos são intencionalmente simples, porém mostram como tudo funciona. + + Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira. + + Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos. From c37d71da70e01eef3b2249652fdbe4860e015f13 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Jul 2024 15:46:09 +0000 Subject: [PATCH 558/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e76cdbdcd..e17ca2f6a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/advanced-dependencies.md`. PR [#11775](https://github.com/tiangolo/fastapi/pull/11775) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#11768](https://github.com/tiangolo/fastapi/pull/11768) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-status-codes.md`. PR [#11753](https://github.com/tiangolo/fastapi/pull/11753) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/index.md`. PR [#11757](https://github.com/tiangolo/fastapi/pull/11757) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 0888b3ffc02933bbb52ba7c828fd71fa483cfefe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 1 Jul 2024 18:08:40 -0500 Subject: [PATCH 559/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20add?= =?UTF-8?q?=20Fine=20(#11784)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/docs/img/sponsors/fine-banner.png | Bin 0 -> 11458 bytes docs/en/docs/img/sponsors/fine.png | Bin 0 -> 21925 bytes docs/en/overrides/main.html | 6 ++++++ 5 files changed, 10 insertions(+) create mode 100644 docs/en/docs/img/sponsors/fine-banner.png create mode 100644 docs/en/docs/img/sponsors/fine.png diff --git a/README.md b/README.md index acd7f89ee..ea722d57a 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The key features are: <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> <a href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> <a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a> +<a href="https://fine.dev?ref=fastapibadge" target="_blank" title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"><img src="https://fastapi.tiangolo.com/img/sponsors/fine.png"></a> <a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 013c93ee4..d6dfd5d0e 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -32,6 +32,9 @@ gold: - url: https://zuplo.link/fastapi-gh title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png + - url: https://fine.dev?ref=fastapibadge + title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" + img: https://fastapi.tiangolo.com/img/sponsors/fine.png silver: - url: https://training.talkpython.fm/fastapi-courses title: FastAPI video courses on demand from people you trust diff --git a/docs/en/docs/img/sponsors/fine-banner.png b/docs/en/docs/img/sponsors/fine-banner.png new file mode 100644 index 0000000000000000000000000000000000000000..57d8e52c71b067248db4f383d72051a94e8cfa47 GIT binary patch literal 11458 zcmV;zEIreSP)<h;3K|Lk000e1NJLTq00Arj001Zm1^@s6M4QLg001nBNkl<Zcmd^I z3EY-Nwg1nX8|(K`ifL@Fxv;q;#imfXU|@RHD+*d>i3wu4qL_L`Q^ZWcCAI5<H$hFs z1xih2v#w--KyI1vVI`UuK0r{DZ|<CV=FFTk&-0<y?RS6oegiM>^UgENnKN_#^FL>v z_r(CPUH0sUH(q`Y#u)q~iR)WyIfp*wr9xiuZs^@m9dRdo=F*fwZJO{dTN0h4GR1~W z`W&wLUrT>N`^}Cmlry20&BtYt2~@t9w~^XOdg3yCt@|>eWZnkU*b1E$H}bNvJt|t0 z^Cjj(i=D1Tn^KlsKUz;pLR2;`Mkn=}&q=(`<MIoIMHgeBbt3eUuN_md7JQ3B%+gvD zRb(EoTPWRdhMZZJ0jSbP-rwd^8tdnFKL8Cc&PPj0HNN;Lg_)8y8c{FR=fz>-goQtT z#!XhY=$`wPYtOggtFR%ZnsLFIBtuL*hPZBw1~XG(=s`Xya{^3Zcws^6MQI}FdJw4i z!+lzm^+-A}CTS}6DY`JRA1#w=hxK4>H0n4OF<u)R4P&%PhBzNAtCCwAYwXktd2DLG zXhZ8MNmTTo3^)O^8YKf#sFSADpcZ6J#SJR~a(z*~nph{?rd427$X+u=*<!3VHfJPi zb2~x-76LEhT1rEY)m43=6N}B-UVblqG-zq5rasham4!@L3{?!I04UyR(jt^b!sUEh z5MUHCih8=gwCiVv5;~KhWwo#gK#<F9v`~7K@x9o+ld&7Ia~lCt$;^^5NJFiFH3eRY z8A%Y<V1XzDRGWIpNf!kW)Rg`O43=I+A*+lg-V>ksU4brdR6>p%nt*B@#5E%q0vIUd z`UqvAQ_f^q9(j-2YO+mfZ6fKomVuRCM*-v%ph}RniNOiz((P%PAjV{KCYITi1U5>! zUH+q<(EsJM1z!}bqG}6;pwua^Sa2q~2~53<9XDnb<*kKe8i<U_MleK1|7)2c#FX!h zLVoU8x+W0}M1BDZVO7yzt4Cbr7%Ah6Os3eyBSOdBS+<p~rToSwqvCvH^uBEbI7gjU zjXx<nwZZRPUX+P+5dsXXt<<4bj7@+O+qKHYVp}bh<2xc;V2rNg!C4r(0!EZUE3R3S z++Zv9SJOym6QZSl;@E_ECS_KEgK|@&F4NMCZepqcxr_4}<F<HnW;Mknm3s@Zb}6&P zqzK(5H%IVbc9FuSlXlPu1PRpGjVpHOSP;2e#*8HGdV0rGv4XG?O~r1Mc#hn;j2Mf{ zYf3CAiBMBu8^tw=1w=qn9VVlzsjc5cmSU7!5_D;Dy_)E<7$IA(TM1Sv-zEcKzs?Gv z5cDd#RoqCN$K?LSa&m5i0jYc*M-Gq@gm@HEr%_gx%chqapKzgNeaQZ5x~Ez#frBx6 zc|_0?b0K7tY?(nSxxpDAWFIA4gIbp+&cCTz_u-x26iG;Xm#8LVf@uq}EfcS#ODI`{ z)P^aqGo&4WfuN+wFj-OWR;n8!)Ku2Ik*J8oHh599th~@v%s})K4M8xA*oL6<$@LNW z)~X#Gc|D_D2u6$ut^yR)E-yeM1%Yeoz9J+^JS2RrMbM997Pt{zGiJpJ5riIX5}S=x zYBA)gjm+v;qSmMATiK|Tvkc&onHnLaNJg~pOXQXs**brQ(rIDrs%Tt6(sfMks$QpZ z_(=~a3CZCQJ=a!`ySON|ZJ?IBU};9oLsA*N)l6QiWuz_ShlDjXh^2_k8gvU*pRnZ= z+Nx`Die!wU=uF=^sBPpVMWajkqWiSatdP$N`9+HRwlP)q0f^n!|7(*`6;+LD%VsUh z%jilc%LeNxfmH%+ZciDXN#$+U4L6W>d#l_MuMjrCeA=QKviYjW^Wqze#5%*6V%s*h zR~1#TQBI^$@|;5Iv1qr36n;ocujoIyV7%TKa72e`ASHJnCY>7Q<7bsAcR1~Jq9J{n zsc(r>Ua?UsoD=<)Ajev<nL_|Dmu7&rXwiTrG0CgL3d6D~o)Sw~2`WbKL{?8+LKEax z4*e*^W_FFR;}lIK10-l|;@FunSr;Y{gA{v#5VHyS(RjL-pv`IwG)W!^Rv=x8fUVl_ z<ND_d6B&bMAOh&DMJaZMtR2WWPSVR}1G79o6-BDRO1f=E^v{ojaJ{0v@}mu`mqJV% zRj1T$<vQX;#Me!_f^1jBe{8k}GxX*PVhm7gT8|AG>oJPW>9L_SUNtz`kkxCYqNA|! z7P48@o)rMr^1zCcU|5p71S*;t`jJO|9rxZh4gVYIly9AiJMWsBV8lYPwU8YE3Xlwn zskPXs!DE!JfzORVn-+%^ZTQbtvkguPe1v@&v8xv{RM(d>AipP>fyk>2!UtLCbg8My zX11<f=4_`D<4rn(EYEd-WLWCH$s6I8(&mw|3sd?4<susK2!nFtf-7l-SnP6ZofzE_ z$2KzI6VBOYb(5M&_X<&E1F0_~$Hhz)K&e%|8>I2c`4wJ{W|b``iBm#SrdVt~Qyb%h z56!^r*>kY(p8fIEjq55K+-F!Tbn3MwW?i`sAO5X8*>&503J0Cm77Om%fIlz$8$K%a z`$iiyyt4#%O}!hX7>gB;UE1{6fz8>RNgr~SA`M8nsLU9o8*0<3X1-X;Ov%-0YD&gU zN7Ei;s{kg+W=pI<GPuMfv@NA_ss9@IkrOUa)n}qRHh~!<J4%!??)-9`O%=w|90RD# z7vks4rL3tmAf7)iTkH;c6O!v8b`#kx;&|j*NTs9D>7Dx%8$pyk0%ejsN*6ZRQnZ!Z zFoGUh{n(Bgpqy&c@*pb$R@_;lL26~N0?$7CJS<r7Ykyq@IP2cpgkvVv<1<}9g@rRV zmhMxX&-L6AU3zVW-`=|cn@hX&-3r@w+X8*RdO{E)y;<R^aKKY8(j<5oUj|I3%7kk* zwO9mPB%m=mE&`z&Z@f)>oSw0vlE0D!EbKrWZzDKX5|nIeM&@&1y($)kyp7n7$@)%} zny9TBfo(J3B0-XI4q6x1RsbF3_*FxNJx3hZT1VE3=qdIWE>Jpgi}M&_fZ24!^$^uz z)HD@f2f?&+b|`>a082cH6pX0UhApjvBwOf{*K`D6Q>~kpl+>Ah)dIEAK`P!CEn1B0 zuA73vr?<maZORXtu6w%)3#M<x0mIv%L#I!nD$W1*cTwM|hA$l38qEskp!7>4+T!-x z@5G0jn$pf6Nr5TtSlhMkf<3qEhpzSAW8Pld_s7va&c$|ZyYL`m9h(_%MpA$Pgh?$% z87#9NtH4CG7vJRz74M9NMzv!lZ4l*@T?)b`$0PGT-bP&XQwxV5d0b7pXtD-hu`Wuj zn(|mRc!e#eRsm#U>?Y1d`mD+YmS<$YQc(eb;vXYoaJ;5uUl4J)&~Pnd&@gfxA)>0y zhXDiS8#2f%`E=WU(`W{)3VB*4V0kUjcM1Re>hq9vTWt<jGm`rHI=u4gOL+D1E%Dp? zs#(&Jm(`<blf{fn8Y}Pj8rll`|4VD!d+ut-%9={|_xXA&>~io13?6ha+O%tj-#!1k zz^uv-^KIL@GrqI`6ztWpU$HjaWWV_KJly=BqcM5dLRx9q@WC34nX#{XZ;V6dv5A4k zdzH${Y@nQM20FPOtFDU={q{N>yX;s1?fQ*t@WA|^#6_Bb&}vYWLEzZ0)z_iJ=pNei z89?<WmAQP;vB~=uGO6;Bc4?543=%>X6<mhaPt|;fJ6Q!F*HvuW%4g$jsg*pSuH55T zPM<_ZFv&nsQo-08|07sfSj-<WMr?+c7AU*p?)$ae?-IsT_=oXYo@`NC)3_EBCR~o5 zhquDk?W(`dGv~JT*ly=7u;-Vzsl31Vk&RgWr%f32-FBsW?K;+c+mo-q0k6FBDi%7h zl5*N?_quT4j09FFUN5eikB)7+#*?cyTi2sohwexv^a+;%Amc<aUk*Jt%q(eEl-^A= zs8q(tHr#vPy@ueV!RO<oFQ12h>3^D9+>)i_Z7Cx_1#qc(O`jvn$Pictvo$+1$OHZb z7-VCCTs}6sd*wEgoDy*J`6b3DhoRUmvo6TF%hoaF`meU=ep4$(?LypE=`cmGL2IkQ zDls&a$&fLne6Y;Td?k+cA(tLYQPeYNX(^o&TJ@IgFhOO)zqs+nn=xwCsg5P>i1~NC zTWa{76(3@e1EnvGY=hSqe1P}XmRZzX2Wm%ORgXOeZH<?nem~~#e{^fS-S`HsylRrz zv`pOP<eKbKw>P$Pz=W{ltyr@J&;NNQe*33c?s_R6SaLP??>q!^{&){weCt`Udsi&V zL_rY!&v-vA9#&K}XtBl;FyuRS^Sh}<vkkHi#71IG^X)}oYp%>@>iXuJVI?*T2rDD3 zkkw@4ro3+5y80>&D;f${PSoq#wF?>>8?k!znlw%b*5v+n=unTkx;n3~w^qH4_ukuB zF@h8uOycvwMjBHr6R#t+LmayTSrNwyG0&pq{CUJQpK=XQ0F+9Mzvx0g))mWF;IhlE zfTm~RJ+LsD%X&1{D!{C-ulKL2w0!w;{4*2xy=KiC|EjttQ(mrHw{G~ja+aW7@2)1B ztTg$XKHP-UMveANXve*`tZe*+$2Q`FcP;w6lfJ6-_Uj+I!2AaEJ*h3W4)L%KpWDI# z*fzLm{KaXvixQ+=j$f^}tP>MwF?G>+{CwHfXlPvKbAG;bBF4=+2s2;$35wlOvyj|1 z(grN{vwY{Su=A=NH?bTecGuKy0zR=jmr{~9B6h}9WP7oeU@HdAlo#WR@<RL?LdL+# z0B1^hd7R0Ju@5_9C|-VLsbkJdF=otn72_fxqkH$>caP7nWlV>!CtiJJXk!_+-@YTN zbQf%0s|v`1`^6!NyjMA%*m6;}XRn?Pa4ta4o;_5Vd;>&Ds-lTWldi%=uKuuLL(!{O zugcBCM65J%z3?A)rHwG(AOHBrc>VR)ORuM&ej5L1BEY%il1uRQuYbMrKJ~%<<*7=p z)vH(I;)^dX)&Dq2JUD9PMieq3Ljg+n^m)#lxtKG1F1~Qg7cpa5Iac+-28*X}UXNiv zXpi6j>b=TS#f1-T#IAj}!599u73R5M{NOQd@%ZCU;NE-hN7=Xn*9!8C?Q^Gd^Lj>k zsMz=W--Qi-Ys9tlPekjj>M^R%^#yo1`uwBWBeDFymf_+<X1E}HXP-aw_djuYOK|MI z=c4<Lg<JXiH|Jx@GiTtfbq$C?SC_hft}l-3a~^iyt_Rw*YVYM(`o?_xYS}&b)$ga3 zz)mry05+ek?}D?An1Wq*=#I9n>hRjCrI_^KXjH%ecyImer#s{50jJ`y1CB@A)^)z@ ztAAOF`=7Z9v!0vg%N{#;6pk4*D(*3(uN{Ur|JqO(tot+dk~wJGrq1hd;mh-J>20TL z5VMH=g=q)x^2O(D_m4`q>2Vk}fQ%`GG;G+{;`LB>J$dqtVs3Skj6$|6+ZZ|W1WdT> zhY857{xWtn?kJ9S<%(ZI$R3pDv7<V#mjf&UoE45CzOeWO<Od%zlu+cQ$0g{!SMOdv z|9~%i3CmZkDCXLTwatAQ@$H7tN0UuoBPweQIP=UiJwxS`GoHUE5nvI(+;PVpc<7;r z)IDNHy?ghL<qkUNAUyNTGo>~zz4TJgps38)v12^|u5e?gHa|&9Uw%#`C9ncSV`Zfo ziSi+xa>^*w@ANlx+kdOd4*s;{11y=f(LZ~&b;YUT`;LLpGhICnYvs#y++_=l9(|@- z1ipI}qbMY3;{a*f)}6$Cc*aFRczUNqr-KAe+qDUKt{7cYUdMJ_(CyRRap{m5*n5Y5 z(XjS%*Z(&3As_c*&>6hPahPz_!|2|rAKGryKCYG?o%`X;!=~W)zUQ)}fM6E9Ba(dE z*LA_f6K9}Tw|;2t+Mp(Oalkd{<QX2kj4%?ezpD$x-}e34IC|h|u1tOGVz<wA#|0y9 zaIYyoYvymJVTaFj#tshL=>5Q6L*l~Ut#c3e>R#O6wlki8X}$)fqEj`qJc>mA1YZiQ z*VHmLo~;eZ`lt*Y){Go^JQgor;x@Z^7&x%MbBnqvhM6am<rBzJJ5%ra4`+;x7<u9e zkk(6WQM>ov_cJ{4<V=5`K<(DsZbE&B`dH?~6Gz}a$K)P=;xT`pT~2a0Z@uki9C5_g zd|hID_uW4Y2Oc=k>tdM8r@E9*9617$u9@ib$q)&|?*I8T-|v_)r$<*P&8K5m*Ib1z zU5XRyi=10{(upIz=p9_y@#8OWGEKw%_f0Rx6~@%FXHWd}r?>dA|G?FG^2uL#y;Y?d zGiG=Y;FkoLZ+zn$c<{joJ)^ny+G{=7aAHv6`&5<^ff1FZL|}CL?YAozj{uU=b=O_z z-%mQ}q)NF6#7G`uT;KfWH+^1njBRr%A&3H~;Foi-(S{vgoaXQ(5K8{&N7tkO$!#hD ziPD1U8?a3~gWf}{1MtMW8Ww$kJqK@tn{U3=`SlHvw&#a1K`?Jg6svmi?fKzGv70{s zr<s_ue41lfYXvh%E$}#sW}0x&ZpY!>57uIZV_vdo$M#(?==1;T>kzPw`O1_i!wW0t zVcLIQji(%|V)=$U!0Oq#e=>9>aB(r>z;m&^V_1BY{_cBgG5_~7vEIG+-QzH%7)wIy z%TAi=0J6@H`7iId9qE@79jm%0&cR`QhWpq04QsIQ)%j6x19}euyD9tb(GUD^3gylD z-D4<0fjq)gev}c1ejKx6+Rb&vC<X8tkw;fUhZfA}?x{cXfJ2D@3^u`C)R;-EFNP`H zpA$zG&*V*+auXhT<WV078aQx3l$QYI@h4{bJTfeD-NuhU--8mxy(mqZbfo|=;{odN z#~<@S!S?Oj`?6O%w~bskYJ(UZwMigR@7f^1q(pt!*A;EtcmF-UFS<uSO29;b2(5{t zjbQLyyLE9gwMRFX_uO;8#zjB40Nr-#;$6<$Zu^M`G#YaU0(u8v*G!s-F=veS^*(7L zFk-MF)<r-=z{IjFT)5D)9*!?jSq3UDL+=vgC>?Rc5wSgDPy|BF#nL!2>*M+OBq^N| zLVQU#0F*kp3GZpINNMu*Q?O~v^)8-O4M@bI7EIfK-bc1ZhtAc{X03i>lc(6%{^-YP zxm&1sQ#7Jr)Q`V*3m$xFQj*!_|KinKaO;AxKHy$d6ow$_Lr8D0Ux{-b8iaEm9E9&q z-!JA<`#W!2JZ3Po_o&#%TWcFI{(&Pg?Kcx~-7m*@(Bjl*x5Hx0%9un=Ij^T<RxJN2 zcc?J(+I?{8JtyIue?P*3R%09&2Wk6tAL87>VsR3veeb3taK|qu;>vr*;Eq`nUHqju z$T;ka!+qU(i)VuA#_o<)G4nWZpTnapvlq?6x{YfSqB4yVpdi_bim_R4Cg)-D6fMk; zx?jlQS%XWDKJu6Yo5uu0k^qS`Z}ihKrWSQy=L~n~u)~8Zw!{M;B?2j4m*dBe^H&Fd z^>Fk#pg#_A?{&;{U_6kGcCoX`*Wc*M4Dl~=DF+@nz`gn_(A@L$J^cMC!EGhLo$C6e zx|A-Pa0R}7%Bdcts9j=?RQ}jwhP(Vxc=+K*J=mmVaLm!e@xlu)_)lN`$`J1o6VMR| zoqg8%&Q0ux&+opM54RA2b?w$w>6Py7zT4hj2UQ0qGM+>)W-;U@l3O-t&>$Rn<dL2c z5%|!3Vo`KW?2OnC-T&VAzURiX7>gDyij0WZ8r5gOA;v}Zn8n?B=bav`HpiUkKC`gD z=P)4uu_r<Ck#Q50j_kQCDdU=Ju0_wUwL<IqYL>NR)_ZvK#lK<Tx7wEO(PIqV58cM? zAlJHySXluqMG!bQAQ_M^Y&`esGY3TgFyCGNUrX^<2U?WgUbhm<-&q#xa6DqC&vZwm z0q&o%U!9CI4xWs$hfMZv9=ApAp$&?&Azs3=wb{DPmF*md^~9oku;Kl6{==JVR$~5( zv!K3a;%@ZbxqpzOXz&|{oQv~^PsTX++SR#)JdWKub@y#P_UmbJ+~i{JyL;j0?%HYZ zcmzKCw~r=JGFnR^A{E)TifIPyq5LgAwFP2q&tpw3={2aSCdN)z1rzG;je5B=w#LS_ z&TyB+{K{kz<4*KqhW3a90!q}D2fY!;N5G{(IOQ*KZBt$9i_6ntAb}F4`VMs-+~`#o zKt(b&ip^5nG|q=Z{kr=0O1we`#*c-(f?mCPcqT?|5}-_(awFC_+bH3&AhUj+dl$j` z$&+u0YhcEVqR#`pOhx&-?z-E{lr^Ig0Svic{9<q+SByRr6C&nB%!m^K2bH5datWyn zwewN&B?cY>I!YY7s&WenNNH>oaA!6~0QyOj`gxg1-$MkuW}sa%W7BO&FT!BrRoCFq zLk~uu6ZXT?H&lPmkYZKGPU?VO4%ikynvSCPKc+QSzR`eNZux0w7|}H<*opZ05^+BX ztp*S-gAua3h_c-D<{u<Ai3PkHJ{y5r+qLT)*-yvzoiVuXxL~M=u@8C?C`G2qMjyV% z({7tO1q^RFhLs*#Wun7urO0d7sxIocZR>g*`i0@K-vlbwgOd#|=I>se=Yfh^-e>oM z(Y0%xcKJDrevwWab3KdX^TcyLR``9it5PW7!w)|UVFKyO%E?GiY7YoNK}NmtJsk)p z)<iKa=%6Kw7y)zSiO2g}#E|GE)4&1!F?a4fkt1};ISha<c~`Dmx=YN705ngDDFTvx z=82fqg%^!;;8UC+QlfzT0gmPI1H8G8c>3$wbF2&T5sStEOx|rus*m=W$9OprGpb@P z1Q^7K2#EN_?j3>EKKtzBT|zpwWQIf_N9{G2s69#qa(O<xo}38$Xw7hc^!e{O5Gb7z z`fvG1Hw<af6s1C0RGg}~lYmPm_#NiuXWnb(dxlN^fzkbrZjG1cyzigQ+F`FPvByE% z;A@AU8G0zbzooyol_+tNBEW<IAyXlzJd#$my+PKBgQO<wA5fHQ(I&+dAZ9yx1Ey2K zr(T+_4Ln?Kc)wBUQr_gRHu0yOx8GYa*#dN|1|u7(8eVg!f<K>oOKi)SY@DI3dCuh{ z!1A%H&-X{WHuX_Iv!1=j#kv|1fA1`+wY>6^OPj{QrCxjOHC;|zOV?e_pO00!boqoU zRX?YXKFu?vbI-m2d5UYyAq_JzVlM0o(tTn|qg@*w^c-Lj1EI3yVl7|3!prQLQ&3dn znzjCtSku(d4!Lw)T_Ai#LxTg4_B>pc0#z)X%h1?7^K$u@Pxv7koQKfG^-nP}lDA-d zFO=4<Y-_P|5lLPOuKThs9eCh?aBoS*&WiP5@}J7sOd<fG7l8!3cf@iSm^kJ{fJI<O zKt=#ZWjL5#)h3lARyBL}?3mAhM?rf6JWk{;R-GPx(xey`Z2Ah0WFeIFZpV)nhzA4R zJMEHBKQ$YDj_Zd9FRDh*7aX(dw%=A5aB^Eb@#D4rJBfGSeUCf&cna)>l&2OECDSeg zUz+Wf4PD$Wz$kzK$5;$AE^d$HugQCe=*KagWq*1WJ8joJ=)>UY7pI3}4tP5Dz)l?t zmvR03iLUqP+!wokwg;YlWu{|OD?Oun*WLF4bk|0YZheESbb8py0a*9=nFsQRzbwNc zh43y|-x>3kx&Zyg!r<sphu*vP1t8-^)}I!haqI*y8!@c5ZQ6rJPw^|rA!cryl@Ch> zMRLC0404(wHU(i_j9py<*ihVQ!i1~T%noq*bZ@}Ge%`H0E$T0`v)f3qFWCk$kP!~> z2oNv7{7PJL`Bj*B^%eN#<B$5lKE<Z$L>%evyMN}G(D{x9jq|b*z|l1U%OMAU%>yD! z5cOJO^Tox;Z~*YIbKhQmWr?r*?Nd%G0I+KjDrjs>8w790`P!y976tYxaDUF(=lP&J z#rCMZxh|G9fB_dKYzpC%`FMcEjEiDb^x{VgI8hz}6tOO1R19ELj~_*#L_kDwEdoAv z`v}nFNhARol_U330@nXjQjaz0|8h#qQ}`f*uk@;AzY9+3%rnnI>m4^>xBk_SIef6u z;@PS1V%L6K;VWmfL)&fPf}U5z`zCcLa!lM=^x|Q*lwJvRpyP4sS(?J=Bnygn1;gR= z-11*U!|mRwFUEZJdi2@lFbvyw6vhp`!^N_$!`MTw$5*-^=gWU_*Te9`;Sb`JFJFeM zM$B-oVtX&glZ&UvHVMq`Jo9;+dgx`i`s9c3*$$l}&~ndDJU`t5Q~`o*TeZiv-+c)E zyB~@}4>%6jjhTUQCrri#Bd*7gFCG`iL4daK)n}u@@7Ae^kF0adYR>Ow#j)3FCNUx_ z!7Ay<{}z5zt~YUC1-T@M758glBN#e#h|i^sDJKhePc2S7i6NC9*c6{f1cpZCWhsgg zJ@W8l9+Zfoknx{$_Bam|Wb}_dJktmHW%)1l8R)NXx%DRh_yav=Ky@f?C7<t6F;X6v z%X{R};?RIVbkfyVVy%l|9eYe6A3Y{PZ4!`v=iA>60LZaP4fL%0xo)FB=j`+SH9bZ_ zF)#|clbfkmVj%<DXgOwEoj6`Zz(l8k<iZi-;Y7@b?lZHZ`{b@s@ZIaoUDJI6E`A(> zK#B76=d!3R>W|&R|LNpcFMauW)gKloY6AWJu4XG6y=XZQd*OxW<NKq}!?f?MaVLaL zm38}nvkiI-Y2|jst1#i;u7I*u9XQigTyzyT`aQPoi*W-U@X$+HKb&(EUixeC^EZ2T z?28KrKTyc#jAz1=NBOVkTzBLGbZl1u#O&9m<ED9I<9IGU{O8zfhra&aGp|g?4bPnE zuaDjTEF9P8oMg9#U9sZ&t+gw0;k`%sQ^e!@pW|P==uf_Je|IXl(g)pd_|C7;hMu_+ zb?LQa#k1(OQ(rIVDi?%5Vd8%N{!#tDgVT?g0LdcdJH@TOHE}Th@=ilk*Rg|7#Tmz3 z76dF9=B!^&$AsI@DAZ>&ht)tl5ikEK6kRq9c1y%>NCg%a2zclRQ3vum-IJ4<^}y~i zv@CH+SPhW!%gH@^c6afprLmoR@Ba@6nuohnzh3D<P4|aR@Y*|I@u0%{A@XHt1=D0* z6@3*3X`SJ&jbPNxF)O<Ar+7lQ+^!n4j$`<2Iu&eeT;rKvJTW#^x+yZZ-=*ir{_-<_ zO=feaa|A||s>*zv`v2@C{@0w43^T3rmyFY{ny!=0ndpYmGcq5Twaq@};5**J6pt}n za~<N0#92*N$&Xi*p3&j_$cPdXOmQuXs_0}iD3urL392QHYx;s~aQ%~GJut=OZqVZf zPc55{@%J6&P8r|ub$+#EI^J5-;00UK@T><b6F_bBtzX6;S1pbG6X0C)&{({=dSw(W zxnKql%)1poxbq~u_UC0$MVuD>;aQBGd?em{r$MkugP9JT)@@h|-b5(>v1g~Lv6}F% z*{s%I0*Lf3AKca7oikd`(rt-Tkb@OU{DCX-oToz#6G2|HL7grfe;$7G++4?=Zg8w@ zxO4Z;_h3b9tzbL6ZjC#!YV<Lu$i~4T2|3<clv(Sc=0Syi2*8+R19ZyW(6BP<5>~Vq zRa{H@2e0j7tQ44Dv$|2}G}O;^X7RBZ7AImv9|bn-2L8SE|Jf-qtk+(Ej2jd;bsT|G zPW<K4iPuiiqeh*At0!LVSXTMxW9Tu45jT9=Q)UW$nrxei!B$vxuQ{TXU+0Gbyx2Ft ztLr?;5;Su#XuVZC|Mi?zj!kX&V6A_KD&Gmo4eaO`)$6O4A+n6njX&9Qu`GH~d`pFn zs_oF<Yuma#cG+QXtXlns?~~(M%_h;VJjs*)=VN90W<FP)CYGA8vY%R*hlpO)<z-h< z-jqyL9&*M~<Wd0q!tv*OH<aQ?1S)j;H|jg1ov}5jvenmO=%wu7+6nMV_My}*{xJ$< z6+0|<3-udVay`briYqSjNf_4uhok^2X4&-1qiF$_r&u(RuEm<9z-PC%2jH<EYQq|I zdRwe-vkU_Ud>QdH3_x>7?A&(Q6+lUvk2PQ<V2!d{l-*#<u?Ix?WGcy;D@UxkShfP3 z@{OVNpA$rPMH`78m#8P?mA@jJhMJi^A2NV}%p%{sWIsF}t{wqV&j04XSEO8rNl#X* zGb^KIY97qW8<iMISWnG~THg4$6)QjJ@^TJ>AW{Zi0&*^-ORaax08>)_xS1E9TN+@g zC*7l~z|Y^<L_ejCF@=q2FWd?_@t0qACA#dpmHIV@-3Dy!A7l8|$)`rJlCB2-x7-Yp zdf}y&U~*R`OF8DL<9A`0#f2%A;gakcMkBH*R+3ZoLM6$4m9A_p{HLiAq@-WU%C%`1 zjV=+(Ai%0TcHznx6TjofqIsii62D9#{;**rcPO<dOUChXk2Ry*Hs!vs>MG_ZtsTc0 z+qQ*#^g;DujL=^)Vvg$=F)wnXVb|0kts%sz(d#Cia%(r3%UFf~di@yGN^-<|a)U5p ziJ7b=Bgc&rSaDEZT37TujFzdTBpt&Nlg6<PX^*v-=T4t?-z^lYLEwmrPt2V=9}hn8 zFb15Go^J0myp4a3=G8y^G1SrEm*P)|u>qhQS4pW1HYsjm6fnp*ONxWlD%;InJeIY_ z|A}d~`b>pf7Ug?607zM3<X!0TL_4k_nSCmsKorRXL()O<HJ8+~4daRbbFu<-{T{(k zB%6^8qs=Of-=YjWq0GDM-;E=X52hx7%H}Ww2c;jY*8oZYl0e90U`V(4)HDuA$f?jr zeFo4BXvBVD)E`^L<hdOyTC>bpGrhA+7A-OfhK0DR@^0@x$;n2_TmJfTT?T2A(&Si- z8+Q?EZP%lxI}zMt@HSZg;VN7{VPbMS1ybg_EuvWl@CuJzNEg+}diml;-d>U9T+0Bi zQ42CHj1nwJ+8032W@eqsrV@jbU_p}Q@FG?7!7W<pj!6&**P?9&=2nys3`9PG9mgqj z8%4|Xq5wOSz@lRO+Ivhjja*Z;1R&h2F}V|`JCylVxFJE+>NOViVQo4{Qb2`RKE05U zAQP{ZG?|{&T{+L(kpgBDHzg^j^lqdbwzMREts$6YzDWh}Qmn=Op|53>SdB`>1kkTa z-r!CR_dm9^|0U5WQ*L&rDB`rHWOUMy*v8mc)p7^q0#_)62$-o@GI$<WVmMYCPZ~B9 zD--{!<hM<e3{upw3e+X&S)Ct-CZQk!F(BiLMu3+r7p1eph)njybzvYJ6wd)%g1(<8 zvGudQjGmzQZUk^9xlD!jLOW82Fk;g}0#+nL)j(+?SS7GCsuv!#QSzny$eKlerRz|E zfz9i#W=eCL08F?ESsPFqF-V(4Dr==5DD`fNxu`Lq<;}N%<ktfQ-QW7-(ro+Fiz81l zCRov=(KhLSLSw;i=V4P*6T0uUA2w~;6w2seqs>`YRR=7ikTvZ(2?UD&Kva()-`xut zBacb>wyHBBV;CdrKpz^2W;8tzpd{<+GRi$t24Pj5+&GLeC{3WapUQC47G>s{eycnh zQ3M11{WS&dl9?EJh$3aRl1!KNBD0KUzPiVX)ZAPOAu5&)Y~FT|RiD)5?Q#q$=|p!Y z76$7qRJK6@8la?9HnorPY^EOqOr3VzxqFKWx{LovwfN3fH2&N#2&EDzNCVAOYxVM4 zyLKJUI%}N&Eukg?tJoGwJ8IhDv)G1^QPwM%kQIxqDEX1U&)?kQ4w=PBO=`F32+HY; zveY1tt>r>i%u`+(tAIy|p;&-qJsE%k<;9<GI@P-hsx~7d<|L8RG~Q;0BJ#^<RILwr zG8dGc<>g===e9ZAvTAjvf;RCp#z3i}G|yIpm0+~=#o$E?7oqfsPw0YTyG>TZp9FF( zx6$!GW~*wQhw-`%-bP($J4hO9St<Lq1`QtSj?wOo-nnanDOEFoM<1CP*@^5g?qcB| zeyFaBWu!6!SS(+N-OXnEX}FAspA|bgr+nix5kw(wlo^Vt(AVaZ$@-P2f11t67@d6A z?L>i*KG}+G8l_#jv@r;9)a+Fok7UHAW=iuOpT$D9oGRc_xv)XsX;ZSXj)i7#+!r4R zA+pf4Mp%HFVs07J5u2S*mH+g{8*f0sUVN{G*rkP@lN1w#Vxm!SNU#es#knnHx4{-7 z1grn>qB$-8|4&;qe@m)cem06}@ZwIJtjTuY=8PIT#smRM(CrtPWc>dWk^`wC_G}r^ zNDWgkRmLbLmyOy~Un5%_%`uebo?U9PO_hr}2lzsr0f0r<31p@5iXOs3*G6K*&+8b` zR<1{+Hf_ctvOXnKh`<)*GbLteVU;VS)=>l>)2!<%WeFdOcBRfL)`0}^tT!>Da$QEk z7>9J%e|`I}YMbQ-ifKyYWLZ+o&-e{hZ4kVNMweUY(L#EYL9fZav~85vSxZRSZ@L?l zf|{mGNg;MK6>A6-I_fimg$Ra5unTS1V(2mSnNn$Yibj%^G$y+TNIT8zs2I)1NErlY z@70S|pGE<E3dTljt!|H17YfI!`hwdj>qat^Xl#&18Lq>9gEUpL8~+Smc0+?#%1HpE z+kxmgjxC;i*-{w>pV9_mQ3+lqn`?E_Yb4_gHB7lZx#l3X5jH(j0q9n?S`%OVM_SXC zGsUK^HUYJ4vvp;}N~_R+x?xeJ@s^O(?_p6=`)l||eZf_@W1dZgUB+gM!U|5T)NQf_ zE-NBY?xJjHA_89m)>Orm7NW$@Qop8RA*1}2l|pp+lOTfG2nOf7ZxUa<sTiv^yfU*> zfm#(?6JudZkS<NQZ#0FF=mieoGQcF9O!J_gvX<_2V6`@rQ|Z|MQ%kJGkE8gUG^R$I zrp;zL;1;=0gUrngIuL`^Aix*Nl}h!}d`q{rlJyG#V?596S%8I{Q#EH$3om!&i~zn8 z8xQ@K4pP*-#8K-7-a?Z4J!84^dW>LtkMiWEg<>SHNQO|Wsn6Vw=q&7HP{tpRn1RU7 zqHIR*#D%<7yJ0ev@-CW}O6|%8lr2FRxk#9$<X|axNE`YK<<n8Ocu6^vHHjBWWAIER zsUDe_LT94gAgj$sW4U-}H})?YHG%=>jE4<76C%1g$i@`p@<wZulm<!WbTTQbS+N$y zZ%c7OW_pq}$#qc+569*wkJTZ89Khr~2)%|Yt98ZitXB<IfII;#^(O$eYF#9q1jXb# cWD7|D4Z2E66^EqPlmGw#07*qoM6N<$f}$>aQ~&?~ literal 0 HcmV?d00001 diff --git a/docs/en/docs/img/sponsors/fine.png b/docs/en/docs/img/sponsors/fine.png new file mode 100644 index 0000000000000000000000000000000000000000..ed770f21240df78760840a5c8d5e731f3f1418fc GIT binary patch literal 21925 zcmeFYRa7L+wk}#|<L>U-xH~j1jXRBd<L*x5?(Xi|I0X%jySuwnxF7z#_c`m_hx@P| z?!z5p)yPVlGrq|9V#bUa8Ij?N@{)*fcyIs!08v^>O!@P8_4zk}0sq`{_0YwA9>P6U zHJz0W-AL>m?aVB#O-Y<R>`h5b-7U=k0QVK$n03THW|-j3^aAp$!@ejL@%ki0USEeS zIvL=XR?#E>`$?7~4pdhV79p(t_Hp?oS~m8;*AZ5)`M>kuWh|FR6OYk`h|V4g_=GG% zVo-?!LJ%|6+b_(_F`al@%$B?<FY~Tt>kbM0z8t~7{bs<nt>Byh0N|i4KOai-yBx2v zoeiU*iJg%tqq~j$=hFfJ{6g;bhQ?N=&Ll>r=9absWS1R4G7?J@0WuAa@66xrMNKU% zr92%?RXpWYjXkZ5c}&QJ1mXDIc|QScOq~r$+-<CFop{{^$o>nL_w)Rp+e~C6|E1z= zB|xV6U6Dl8&e4>Fospf9nL*s$(v_7=5RQc3(Zq~bSxn-8AU>}I$Sj<l?RlA)+}zw4 z-PjoI9L<?nczAf2m|2-vSs6Yx7@Rz8oekX?Y@Nvef%tC>F;gdFM@xHWOFLVVe=rS= z>|C4$$jCnBB>w~cPX+uRbX%wYA>oq_rhg<%ER4)d|F^ocrP=?B`ahC?ssEFhSJBel z)LK)_(#F)*>GKf;$XMB#{|oG2Qmy|>%EJ8L(tnV6rELt&O*Je{oGt#9>|X*YQ%iG; z&yxH<k|;P@ntpQdPia3TWK91s$@D)|e%1`r|EZdP`1$|-_n%DuEsp;~*MI2xw;1@h zl>cL0|Do&OV&LCW{*QJ2|BEiTe+74@wx1E5+h^$Z1H$;>Gwg$K`X;Rk0|T?Vt*`|E zkN~8`L{!~Z#(g~8Rn<VQYHsGF0g&LZLufFWBxJI2gd!qhA_ih2N)EU#&T|g9gStwp z7=$hHN`u)B7#fgJP^hMxBI;nKiGYAQvmj@w(rzK!O{a<po|eAX?#rhfeInxEqFJBI zHkT9CuDb;t7(m<k%h`(y<!9EA-lQa8q-3b&m!tp^_f6ruN=Qh57_qZVl8@sq@SzXI zx11||-+WJ@OSt9DCxs{7GP}Yzhga<?zlu$E{ef=U3xqMhz-GWesmE#fKv(%?Wh{(4 z*B#{Rys%68-exV3RVu~{=Jnn0MjXW153#k$NrcQo4;mY5;W~8e0De2`n)ZSp)qdTd z68dJ_6Lvz3qmMQ@x0@O;_WFh#@d5FcYxF8a*7xnKlBF6Y{#Fniyua0u1U$j5JPhVY zUufl0^k;9UIoNwHNI6ayz0DQ#8cG$o<B1i9v+02XWc3?HIp=$@`)V;;$oj?P6q&{? z(i6ofoPY^12>)0JUK)<GDSD58^ig^t|4x;@Fm{geCRuidj?Ud3r)kvn472i8sVmzP zw?&QY4tYj{0wFcs+CTDclix&>zTAxz@Ovt+CSoaY_`Ga0>rry(CfH8#<2t`x$%u*c zUH#|ivjUP2AK8qRlywKbUji@1E0BD15+-<ua4u*sbwXqA#YK66)DC@oH%iFOrkBwT z%MH=<?e9Py;L=z?Z|5HOBQdy_@1fHZCa3aVfNL}04{LMiy`Ib~S=f`gB|3%1%x$YX z-fCLYhq9T>PCVI--~k~ykZx`ecL@pb6ae_+k#|S<jgT3vh2osnA7PfFSv~BaPs9qJ zcC%`oII!<1x)`0h*%{q>(jrooD0WFmnt<vVYJ+x=6Qlf55*J*%J8Q=<3P>D>CLX=e zvP+tDP3(^vUGN*wwjT%OSN7`JzlO=$d9#-EFwF}?g(X;siWM%448sxc5AaYe9mn3U zr41#xmDqWhODOP>m(?LX4hyf1wNzURjqvHc2X0R$pASF?8_6$Ya>f(ly=avBiuLP$ z{n<g@2gS1sGqp+x78WO@M0N>M>KFBVi@G}$gvnBhM%o`g3<1SCQIoALg5mbkgWwAv z)hZvq1ryN3FlX;b>xj<wX=x1b*YGO)+n8Rvu?B*7@x@2MEMED&nowgM#<7~=mJFW- zOJbA6C@<p5kQ7RrNS56<6)B**l&-wGuL-}ON_z>jE5k9z$bFFg?VaqdMWzt0%Pj&r zTkvy}5w0#7!o?bzAP_V)ok<BB$Qp|Kku@d5+YLyIfznCQmT3u4goD2r&;$)W>R&a* zeKE`4J2WSd5N>`z2#pD;RiPF{MUENbmTH|9-PU)8Bzpz(iWA-vB?Fg40T#uhq@Wab z(>jN!m&p^|$vE%XnYeRfY$k<9SPJ}9>-t_I44b2ZdQ-@|Vn7q;`%6#2=u1(jaQb&< z1Nxk9R4x__j|zScoGOub%BKZ9A>K8j)o8UcHf_GQuz2+6gAkGYSUnLCve?0KD|I4j z%ov<1Z+MSxF*m_-H+fSW8wOI!Sd;3O+Qbi3hR3k3u2vrx@S86|NjN)@a$x~E2VCf# zaw1?0Oe?sx5ygt{nQ@mU#BS3=RlqP4lGL@x#4iWh9@QV2;L55wIZ*_(w(DRhB$8-K zE0qXs{$#GU=~G~d0TFp(`f>Z{RGg=FI3MrBxKJ6_^nB0G-d4E88P|bBvm{D1ZoKN0 zS)q`->y?xO0>hW_;k_qk(cnx-404SFiRjr|1)fwVIA9*a>Bn5GcJhpq!mm8x{&DV# z)TBQt$Pnz?dPtlwER)bhuuIUT&k&?`8!<v1VYz?U)so;ff5~<|>QP$v<8OFa&kiHs zLyaw=FUHfwTd_wBZE<h^vNo>SB5{p9m(_OaW-6V<JE%n?$u9@PZ2J3V`cZsyB=C3n z=_4lq*PxD3sRs;-qgtq5zdi!SWEs}!$|7~AGdTJjzaCk!h*3lzRpUEcv+;ggzSC(T zq?Z^EOf(FbxC@dC24yD_l*utin{r>M<>Vg&ZjuX*M`W#mOYX`fE>a`X#5)Rc+9Uzi znJ3;1SY}u^*&=`6<}Or^Y|OSpNsn2Hqf0&<W$2LC@8MFAI5lc6H9$lKR5m^KIxpKt z*f>Oxm64dM>)%=P(QNowOf>sg#4*jO!sBlqh*LCVb;7A%U^mQvk#7$~<Kt6yeKb5r zQ}OoE5uPC!v@v!_7+?`FO`{y`1dO(7Z6JI_7FYA$xfZI8I-$Q3(C$PMB^&38Pz*b` z{zid<&^P;psg#|czk+hK2%K|!MHe>Efg6^`nY_v<2(ZczTfv=)L3)h}s0;%q5ciqh ztBCw-BjFR$?t-9&9SrSy&@<WzL~r0Gx+806Ku#|w0f_yH9~)~g%|yvpOMkc&J-1PW zl11A$a<f!igUd+PRilu6a*s>pN6h*zqE;m*to~hLm0eq$_$~*!?C%Fgn%vY=a0!>{ zV|s;o#!)A+S3kTXO+?2LjX0Fq4=FQ-KukA=0WjV~u<O-@Z~3QvZ$W}P@+34{1#fS% zMYF1i@XLncb--weLY)?C!<5jdSTrG&@j$Tl-+b+C(!@hpuoPS{_bPR0=7YI3l`f@f z2u{yD{Ta%$c!J>L=$PoLIJ@bQ19;3NHmYF0G)D!hSQIK$DLaeae?W!eLWD>ZVXAm< zQn0uB2<)0_51lXY;lF-!)uMiTjz=h{K?2~Yz0bzrrm-cGPzB^ANVVeFWFe!^idSJ5 z=9y=Gl0|1q@ra>|_`5U7;hwB=lwyTQq&a*R@G?c`SP+DDpzr4C$$QKjixiD9QXx=c z7!^jQT^HROQKe~HBgF@P?F>mBeu0}Fdf=O7t%0pfn?pCfG9N(VUv65NVzpRRmaGo{ z&gG+~D%RmF=(bq1juRTkPX()`#cSU)1d!ZiK`z8XLxKAt2Z*##O<kt%wa4vo<bl<t zwH}3?)h<%S2dih1)8(gQV$$gCFe$1Bp*#A9>Zgz%*7t!IaSK4l)r+bTjz^3_t;c8< zBja+QO^-Ui%|ftXU|c`Tma!@{pltg4e4~&-1Ms<>dEXHyZu>1S3h8BcS}k7sN`uXh z(=8B<tRNygvv2o+sD~<#$)NVlIY!(>4ng#SNw*_Z!-*y-qR*01<i~aldzP`depE4e zQ*^?xTw_*i)`U<hZ108+G+#`AhlU$*B@X{WFv5`J1Q)h_5&X64=bC(WmVr2@=%z># z9}M+#vAogn?PTCPo?V7+{Y7RX?AciXaADXMcll$qocKd4Wy=(oXIqwdv<Ky@cZc<4 zyGp6uAR&|dIeXPYx6ez5^M#(aG9Bz)f{=oG#ovn9z~b#qzIsQ2APuOkQXhJK@<v&3 zxj4$4D%fvn7EmOoOg%HE?<l%LWa_>ee(#$e2;za{s^%#aT0<towW@JyIyJP1S8Ti# z1<U{wv%?f(0Zn7!5HpG*MYe$&QuBh4<m745P^4HKo=)4{s{uQO6vFbFuhfTrp>Ar; zKoSme>P|Z+wQ0N3Ks|MB3|aX;33Dn_j>xK)XA^PhEqu^Ng7Q_M&>}4Lwt(Aai`kv_ zI81b|C=HpHZz;hP3Gp6_0db-rU7ugj0=d*17C^Yjhp{w78v%>hq2Z5sKq+1lgi;_> zAt_k$B%Ab%1xxhL26Lf!^jmk|*`X;3iUvdktFOjjc3Q&GqKU)3_WdBi_TA0YZ{yrl zKOOFOM(>BIb89v0>39%3V!tcYA&K)<aE|f90^V%p6lA_PxmF7DDY>?`%gdL&q&3Yt z;|UCuP|yFtq*wQO9>!)pRg2<_w6mhlXC)W_beD7mTg0Vl=3J7k%l=8(!<TB$@?{5D zfZw2*rL?x+#VKjnPJIo%nIKW^|FYUYEhnl3${GG6?LwG@4W{U_Ng@No;a>v|fJS2Y zhV@h)b`(|0o~EF#rPpol;&S)q=M@&Vf+%I_Y^F>m`*tg4spN7Folm4e$@->(+4R`O z3OI6?uC7{>ie6Z&vzbYMQwck=dl0~=jDb~e8_-28o2015Ptu55tdnx4mp&C1c@kS* z3?74yw?W?1fkpkZ%^a3Ob!=hkZye-wMCY3yAbTW_2pdrVX2>c?O=nA+Bk#jCHJ!oW zVFn8gsnsJ!_&9-}72op9JD$dr+55X~Lq><H{ojb>Twf3m;I^A_-TL=V3SP1JWeQl& zvZylt9%aLvZY7;tO%=i~!=Buq)b65y9+dkwK|+9F`tx#yTBXvQ<nAD17@GgIMyNr2 zn{KpQ*_%&v8Xg(<4<Nqb*yt#{p_Eg9KnI(N&Nq?}PU-l-sqcDXoPj?I+XLt<%^0#s zRLmhyWq$fQPb<l@R-~@^H4^co%#XVx=(^tKvE53r7c%ujGDIACTKvJR(r!K&z^@(U zEmXhmU5ei{7HQG=fm69ip$znBRaz~o77{P#ouWgs7MS-{{ApHr6~60iA*nVsI>FD> zy!*F&e}7-&hl7ijW%}2#oCOVT49odE*`LaumbVtne{5Pqg!7((<8?8F0<J4PjY~uW zxo}4ud}C8Eg<6`IMTSS(8Pj7Ws8-W?v~ar<F=u(;je|V#HjQP8vP$!6(7L{7Btzh^ zR*m8dV!2^-dybf$a$o#4wUzP0#h#J5YYk6}^bgck2hp@opvqkwza>*2_52o=6>v$A z&kjD&O~h}OeYR0D-Itcc%Ss9qy_l4$`8CNeU^#Kt1{>jV$j<90_TnXx<?@iXu$a5( zIF`;MfMV}A93$ZZ%E9F|*9=_^$+{aHNVieP9#bFgut$@46aUpXw4QOMnDm`4tbsYe z)!2H6AC@$JFrF4r+Awqy0uzi<RU?<Z4BL;O1*Wea%ku>X3K?d3dhf_S{uTc-j0|>d z_u*{u$qnLL__A2`)8epDj9mup3JU<3lliWDa|7z^#Hs{xx1G#_AZ0fV?W=EW<!dW~ z6)t(yl`$+{@|pGS<;+|whhj{VH-V}~z^%1u%k>(m)n==QwkIF?EN)s&<@aXlUn=iw zZ_%$*qKc7V05b1JQ&8z?Zkt^Xu!FM;<=b`WRqU@8#&w?ckaYy>(6B7QA?pH?fHo-U z3>4#b-d=%4(BNg0-=eH7o(GV1tibr?(#OF%P<zP_Vhs0OsNuvg4JE!8%?;B)QwPr~ zC=icbbSNyJMa2G>K|iz9))6CX<x#&joHSoSA|__6AS)4o7r8b$9$mi90QhPT>iJzE z#d_PuBG7xSN>~VGm#j9Jr&han@H9N2V6}+sf}0Kvh!x`9-WyIt8=T4Xa}Jek=OhBh zB6m2Pz7w0OlPB_nzMGwl6XqN3Lsdf+pOW<8wPQ2cNiA4sMMZvfm-|`vUDFxA{`FeF zIy+^Vv&DFIt#S3h)q1tlxU%HDH~5a(F#WlSOwJL-c<dYSNZ8~RpajV}Dp6!hi2kcX zDsXgLuuG8@f>P%Tg@-Jq>>gQY-OSQ$ZFjnmpCJXVXS8gvu_DKqU*lI-IPE>^mW#x! zt>jQwb({BYaKQ71L7<P1Z5g3_pm=18Tqb9BZwEi1=XP)G=B5S;crcbb6+>=?YVaOY z9`Vbyg17zm))%Clba($^i9pvI9-asr{x?=*<e<k80&_Iivsxew``w+?Ha*6g9tw9x zIEsNi6lzbz+*2&1q2A8viYG)2j2a@v7J*M9b)l<LKN9tP4zq)8U4-7nbBZvJ%{m3s znBP@^Wa`(qa?{v7Ds$@dRSeA&zTYh;hqdy~_}L4G&$odtrF0|Uvwg|ANi9PP6BalV z#L2&33*9MZn~WVtiH60THwBPchrw^WEt8XTG31rtFk!BGGrqVHuPQQ~M-@`TfjKNN z*@;z-bg&buVhQk?ufDuQwpiJ)r%tl+E^zCLVG_D~!J?Nsa798TO%#Q4L<DpOgH_Qm zcIcx#a!q-rWqnu-rUf^oj}X=ldMSAHDmv3YkAHEEBnc-+Zt@J+9EXwM`!S>>D3Tjp zl%}ptEv#Ky4qlQPPqAfsd5(C>_3kwy37C3#UJ0LUX`WTU!XEf(8se#!Ih3uDlSfIM z1R-2%*nDy*(Ye&V*lY>7diVO+XnMjftQf==V57{$moPlO&vkt@Uz|p?dYDjRG~K8r z?!MY><w{xWI=zD400yHmPk*5#549&jc3BoHHiAs>4`|;j8^J9_d?@HEO2bW{Q5eF* z1<4><wZ|jyO$6?l!XaQGB=Q=gaS9(pL!!lCG0MG?ut)Gk*@U`MnJXgwI719N^{>H4 z*+lm#x!OZl(0BN2sx@xaLY($Iii|0eg2yKgzsX2^uPM<1Mhj%DS_1M+WnXF&uD6jD ze^#Y0SFzulm~_XD3f`W0L@c%t$F>$TJ-LHlx<-piVw9`RN$#kRvNBDve&n=2O5xJX zx<0sYYDv&Zkx6;Wl8cFGZ+*4!RDo~k!5tqBhSlLVB9!EBGJ{o#r$hGBR3-Y#&W6WD z2rI5LEsV;V9ilY1ghl!4RmxiZn=IGka@=_gKKD+8-Ah?F;x#&V53_2G7HCk7GQdI= zsC5~G%{e|Csitu*(0S8AnJccK2DlWuA*4$czS?MZaBaLe%t~EsvY{XlR8s2p+PtT< zIwWKg81Zy5c!bgj?lVjlv-$8jEwK^0>7i<o9({H4bmV<^6Y|ydE%<6ka-kl{Dj(d6 zy~x9wPANd>n1?VgLL=$HWaFp)!jRcwPYE_y%*|V%6o$-vX@4}eU7F)*J9DGp24wXa z1dUkObJx2W@BfCHc7;%$=xDn?^y4Gq6BkLpn4#StpOEG)^ie*HZ=Pr?!UFKW-4=<8 zhwdJh$T^|bna_?wx3q`rlY_HM*||DBq=IelmG4k?0LA=AC)<GH>Y=TfFukGlgV+SC zGJy3A<hFv-E|iFlY~+*}rb=$lQ-7e_D1Lw6x^5^JkohL%&u)k5t?;mPx$(>U-Oj5+ zvkIGgGm>c2P0zt%w}*jjFCOgh;};=O(JAwr;J$dFX!qL)c-xp@@)3t<e8<IIyN_YI z_Dmw`TItMCTi<-0P{FMh7LP@z3OZh|YYnDuu6K870w3a;4`c{WBy|lwzrPPH0<2hC zj6U;2__pmQF^{Fe2Acr_`V$#=v2yOKOp4Js@OG#YB`sT1mI2(9NudN5Ty<8<tObNX z8wIg8h~<$1B?*!FSl~e9=7#rf^*QjoEIItC@TY++Q>L<SL+}X)tQ%3zQF3vp5xo!( z7(k##rZPDkX!~+r?bkJGhy@t7HQ?9MsSs(@;GWqP#UgbfNlZ~|bGy=cVt~fg@*6#C zq>f3~15V%)d@s}J*dAT<a}&Shvnn+iO3L-GGc81#{BY0)#-xG|qDtog8z2SWL%3=Q z+;zAy4ygSKp~tD#StzM1>%-)vA;r7+5MSMA6rRlQ;w_-Sg&iGF!U8mWK%mY6#7vLP z?2bo#J;4c~4s!~EZJtvP0q7HTlfd*%1(ks<>ive6Xjw0^j5J8Rbu@J-CFTBa@?%h6 zS=0elRs5J=OGad+pWC(aXsy2Z5@@Mmc6`_&LkJI&HlJ`vtM1p(RO;~-BLF~5vX!gc z)AU?E`VQ`HohUa~qPxawEb6o0s3nGVSf&?Tc7|C|VZfA3Mrfxx?!sKnoxf;o>UZ5{ zSv~V_t@D9>)_LgrmHG|zd2kqf>Ycb09JLVt^Z5NZ$m4f(!_Qg-C;NxdFV1aA0l%N= z>B+su@^qwrcF~m1R%mqqH@PTzX#bw<f;J<{9QsN=2tFJrvLFFMj4zy6k>&I?Dtv{r zTI+L{Cg%H1!&ZYTqv=k-ot`w&A7U^J9iBwdgWIMSVS9P{A~b+}_!%r#0Il*qvtERl z3N~CIghLwJVJJ`IVF=ll0|T1(+wax}gY|NI*4qwR0TCiCUGaU%O0caLo*T2t9Qv}S zESFyZm`tSc56{(6A#C5t@!Hm%DUD41=btySY%Q;B-QsPFM$xO#Df1<U8USup<vQ1g zPEkrPEkQ}Z+(*@D!XMfVH3UI(>ldo^H{#y%iX%yQ{q~o2S)%vJWFecZl6GxToOXw+ zzO0tKM3-XqfG~g`!86JAy-pw^pSpbd-3V8tV1&8^o0U1OyRZ^(*F(G8+U&42EnLG& zv)hX()5mcIQ19x9zU5M&ZZ%e=-o^H1I`v1Wf3YcLq{if~LW{=Y&D`wSqA`j2#YeZ> zV#+3`^aOsT7`}g@;XxRV0sn;=r*P9RvnmWRt4IeZSl|NY4kmd{P6$eP>snSp^o@GW z<6ptosmB|pqs=NO$4J}Z4h;?HzL}<@^@eGt1*;X7@^z?korAWUA*`q2@eV2t^&HRJ zZR&U{o?-IA$RaLGh9%XeJcSEPU3_G9iqM^if@5IknI4}QJ7%!duZFOz;}PucA2)OW z3Q6UUrH^tE!W!juTEnQOvEwVN?MX=X&eiWHbT9@pw?a&toU1Q+E_~Qvf1t7@z|hEC ze=c{-;}W`J*m8QqyK$KxxY{PoM~!a0x0($EKiJmR#DMjf-)wkX)-Tfz(}E-b0BsJN z#kaGYxq6o?sqJQDBteG;0>JO{mCoBkVxYT?VNewTi9gB@hv7RFpa(VzP=~q8Z?g9% zqSyYz$6*q7C)ee4TkJ(Mc-s9r^;W{VBRT8d*|+;&ro&oAO(O$fS8xRsMpFID1~ki6 z5*rQ!^GLz&sS$%MHg9+9ZY2QW$;#P2>2T)G9f<noS$X$bx$50AxL@Q)m{uEJZX+oS zI=ZEB(9DTbx}40xH_caE<N;6hYxy%>`ZZ6X4>u#9<|CWS5duvit_)KqlFgQ3(yUIq zvO&I@YM0rU`mw4;Jdj901~{53=s?v1!I1;9=E*ke;{1G{OqvyvmYeNPv-b7To;=Xq zzokh5d^&y%E!VO6z8;zUg>{J_rWbgg1=*>6kv?5>MQp$W?+wJ<)KFKa36v<kf5L5M z>zX{7uLc5tLju?i<r5RwVGSk4aNY76t%6AhVnD9_Fj$y<qWeWiehMO*L_#UyzxcYp z!D){>2)1%xryok{3bK}3-fIOZbNQy0Nm{LQQR_U&504-|v<dobSQQT_OyXr}w>Ugr zZIde~q&edy>!4-15)K!vYvy0(prU&t6Jm?gaJNUpW{DgR8=Foitd!%*<$VFGb19S` ziYp$_^2mL^OMSEq^@rKEhYVxJ@Y`W<T)9pP5yOl^sZ;7Ip{t?x4=gwjjll#z_0@eF z{j+^Y3kpf$v7N6XRJg4r_BdS1Z?X5L;^FzFAq2|!&Er^A)>LJ3eUb}(-?sEJF2z05 zY#jSEdhpwNqr~tYcSN*ywbOHQL-#jzaz;K(!!EqdGWlLR2Gw7vG*x`mUvhv98(6B! zAen)`>hb$W{CNoK$$#Re$qcWsP-6)B-sci0!Ft+^XO!8{F!zj;o3^T1$t=9|WM*Ru zi1g^m=gu8te_yLgONT3^K?MnnStOW{r53egdCNnArOS~Vbnb3em*8-R_&+wRb;rsm zjBhDp86uRHnz?_>*CfY(B5?4Gzc63wvd%V&?Xvt7_;E?~v(yyyb0I!~Z0a;t%)V)_ zE+6M$-D{oq?v2P6+<&hqiT4=SWrpo%srg)awi2}fIVEK>Jj+7)IT$Om@kQw?^k+Nx z670Lqv_+BL1`kxp;`6EiZ>)Z-*&Rm@m_eGjqt;bJkhWSdRb;11A;EV6UwFhSCYMZL zf-kTh?g&zJv_QQQBKGaPIJ~1hcE7;nXi_Cya{amMh6!NaT3CrU@rnN&6UtTxoi5ls znw%W|#Ll1EGa{DrUIX)|tq%nxjM^k!5z1i8({XDKK@3z>o>y?hGg6hEQUJ){LjQmq z@(^C?8tCx+Ajrt1q-D0*Ng!cD{~!d<-(6K`su_?*HKkCY#GfdEiS<xc`h8`fS2EWI zUSN|L)V|)NN%4B~*|iUiP(+91-c<SJsMJlxDEBBO>}6-+)Q=Mq^o>u=#0c*M(MoYr z1ew7lQci~)Ntjkt7{&6x?p0luxZq^9o92XUWa(E5GT5!tx5>-Xe1MuTiBlnjgF1(_ zf>gpSUJDg8)YP81u~jxm8~8DXNEKoXt&m0vP&rVokSJ6pQ#p{1+4tN%P+8|}R=aa^ zA8)lQtHnOpBv>-@@}PrIgdLWZY=gcx+-L?M0P;Kv7i2Digu)B|iu3zsy<YcQ3dvo= zVwk`+p=4FjJk&5~<LcHKUDSybb`l?OSY@wL)OsCmoQy2mXgAi{BWnmM*SDhB&Y_)_ z)HTTq!F;~w3LHWU6s~CuzWS=flcdWF^ScZQ=72*x!croc*kSq)B^&SwNp$LS<kioh zmP~E2-LVgtG8L<aW+3zb=dL1**?895Y%IJpftWwE7Li;znemW6_3NK9j9@eDDpjq< zLDV#*P#`yko4gm&$B2(a;&ZjUdP=HBQi?`W(tm9^RbLfqF%=p|=w;{&s9VjX5}`dl z3(URl__4iyhLb;bTg7POb<M!lx=7PB<4f{*{-FQJvs@s3Is-~*0403xXV58&_bJ2D z60#!v=j$~sJ;FnUy#^QDZc1<XfQGlZvp?t6-8jtOxg<JEVd>=SY1D+!3j5@a(F7Yu zEtg68@D>uJPD%;p6v=t23K!0pe`8`<ovo9(U%d|&PLB)_CTQQu$rHGrX``-pwWEpt zW4a7pMeKs~<ppHVL!t_S3T4W9Y#G{qFlNBKZ-B2nqCt_Dk@U-%-{3hb<q;7qTmH~k z{-s8;V_M70@$r-ySn_?i(!qD@-P{0rEn_3wy}!nfZwlzzkN0@(N`I4i?#KVQ>3xe7 zbT^nrUj!y*C7t-(KA(>o*V7Rx3UFT}mn?g%?QEF;@3jChI7pJV?|pBC+6R1TqA-zu z@1$6>)Z1Gd<e<ruYEEm<>e~mZiATec=U*x<3~%0p&stwV8O=(JPQxd}vZE36A%tw+ z1fh^-Z_Hf->4DJGs$RANEhy1Bgn~Z+rpCp>Jdbmv>=p$@zuI{a11SVh(c=41#|BJL z$TfC|1O1!K6?&~c+;_Wy>+?4!x1VnfAuRC$fV!jXh7!WY1|4z6&JH9%r{GiddWY{| zYhXLd1Z#ysO+4z)85sOulHgNu<La+H(^Ow6@@N?^Cz{K50m~;X7x;o&+q8u*@5N4| zzE*Byu}W%(DQ^?Qr^SLD4Hck4m)XwKF0(CxC!3c+j}3EucH672%P~(Z01_e7kDJqi zi}Nou`U^Cb$Ds;em;Bt_%+5Vs*c$fon4+tQxjWr@Pk11_knT3vcxd;DW4&MBW^no7 ze{)oAS_n@@s{O_H_kFVItLa*uANgBR>Gy-vd~a)7Z|bi}p2Pg4ED{kNWUuJ&Ls-o} ze%%cT)=_bXS;AGg5DR{}aS&hj@P*4mU|F0mPO^SSA|Z#m;^V-q_2(u(fFctgu+AzI z(Rs}+5Fuk5$mi*WXutR?;=sWpcRoJ&L4Hj!c9U+?q<5K}72AhBE|%n9Zv1sBjqFT0 z@V56oBeKP}(PXuSzk|C`I<@k7)9L)l?{ulNbTUU2kk)1-vpv1pwb*Rqi3Ci&AMdEp zaraqCOjb)?+x#WEy(Ur3dTN5&dys84&yd*fqW@&?Jstn;F6T44OwAE`zBnZU{#+W5 zcFHJM3saZK^}0dbmCEk0ry@r^Zhm=wVJdFMIq?nW?Gg9OPs<50c=ackV51O5V2$%) zX+Q_#b34XJo8zNH`&ugD)*|k$M@LUVZlq;-oVZI3F8p4mZRsK!ZsYmVP-d<aE5Mpx z)ieg<mnH|RZGr|h*;cGPW$^ZV%$QNn0@s0swv+WsRIJ~4M8kZ&(c+XV!o!5d%ZtzO zAi@v$@#b{$b<NA-i~gxTJZG6xOP<AGBk_isM+NwhVoI<Jkn!U+)XfG{{Bj40knifS zw3ddyNn=a`JC7?l348NpEE>P1S{!xbPr|$qArp^8fot&RgosC^c_df|4Hd|qh#+GY z644)gIzQ*nv((p2BpzdkqzLL0Hcp!*0u-=DK|{f#)xYo9fub}AB9#j7J2%Ib>NV0b ze{(bzg|CiyI0;eJYc${X5A_S_&qeFl8=GlEC_3b@wW^S4wkj$cEYs0o)e}#x!v@i& zv4P!AJE<+N4Q?DPGz6$d^Yv=L39q9!`pvXE_bT2J&h0^=?~GSAo`diDf=|aTIfhI> zxK3kIC2HPW!XttzjMUh$6@2VLccm2tC|}Xl?F}B%UY<Wr8?oUc@1MEOEf1%!XN+eL z<q3Tbdy1_NWlacCn6V<qb=haRbJc5fTst3W+DpQ;vy(`nEO1sN(kvQUSug@x;2w21 zC0*_M@Iags?!WuYP?X403rr1?;QmB!%TCl12~1|+^dX47p2Y7!0NbVC5LYR5Ia$yF z(Ah%PcNNW8Cr4;92sAjnw1AX|nj?V&zxqQa8MN#nWq-`4PGD*Af~7W4t!ss6UR6!m z*ZQzmpRSVbwFOfnl|b4uca;MJ$!@8he}mm%UEIvGi;9N<V6gbEuOKn18)={rAK`Zx zb!Ik>*IcGXUk&;kYS_CODh0F@zK+z37nF%KWz)dCHPuEq6!UOS7MQ{re6RE#)*u#W ze_0fMolxaViAX)F2{uNg%!SkpWo!f9P3%o;=(%1kR(zIAzDC46^?Oz3EHCJ(bk_EL zHyf$O716W&Po4AgP?55fqa^wn^fPhTAVtlfj??zq!`|e(!#ez?R4Eh9NIxvU$-oT! zyuZR9JxRy7SUGVcC#ojJyHqf70)@W@qptCZtu2S-=+k93PGK;FbQByqY#FTduPC?g z@BNSA`=<Mds}d_YsXu`tt2fF{+LH1){7?P6=+!+E&Ry`sUrSp_h^fbvd<=pD&Q+x6 zU2J^BBK>0}umYgTRXHbd(GPp^WTR3*g;5z&s*q<kS%7hIr6~4zLaMt0FPZ8S!ooiM zW)+r)WfusllHMJW1=rwj%n3d+Lw6q9tqL@I^)-+t#V&=>%C`-L#&9tk_MON*;`uAU z+N)x0YKVVEG6_G!=M`#x<s2PFGIjp;+XRD1+gpW&I0IN8>ogVdiO}JpIcod!oc7K+ z3vYmA3`RH|zp>$i_kt|C4O_WOlnNsB)0BcRi;S8~W_nNBtEFQnEpU^^%t|6g=}O8} zOq@7Lm-f82ZDGa+!OFhO<Bu;}GulWc0TG5N(R|i9e^KN7Qc9u%88NY=i15TpTL=s< z?KEp_uHATvXm=?d%0dM%T549WEa&U;xqaL;w|w=N%Bba0j_-;=cA?~iP1VK6{ex}> zUyLEv!keDlkFbJ9U<6Z6`faeXM(`sgesoA2UumI`K`$WcNb%0(l-Q^yTMk#s2`1yE zlOqk&M6PJTDSwLOtqq>>Xa*O{6?|dLbnbZy8dPE06^+wN>NfnNHL|}CA6#*272HCA zhSSz`zg&_i0|3ZotWKV0W^7cYralWN{qF9lEG`aZ-$jNB0Z2{R^^J^<n(BK+i8hWn z)rLk~5y7TU6<W{ZCrkt9h6YHMV8?l~N&vGXeg-4vW0BYQJBi0Hcj7FPu!S<x^BT#1 zA2k{!V#;Q9$C}b6a}K5fH2jiTXdY8?Asu|8|B+peV}<f`i&|KC9@mL@y2UANC4tN{ za)WB-`?kI#KANChf5_ngQ#<K$yltY{WWO9`$=1b1%{-`>kTrU&Y9SFW_XTMbZip%f z%(}_)5eA9STNRraWg73`S82X}g)LjKvIqL#N1WX`MZ<cIF&Tr35c%IR0E9b>K``4y zMzDYvM|KK`DUR8}GzKba>cZiD`|i}l&O!51xI~uF#?_kPyCJ9ui)<JFSV4ADtjOk* z__bD1<;2EBP&+mHbRRN5m>FJRjTDEH5}mO3Ca=A?uJGufe-hs`EbhqQa68yIB`Gtw z$0%v~U<AoCB%2FO{Y=6z>f-K?Hf6jKGlL}QY7?e{H+%FQI<noQAh&6E81<oGqa2bK z!yoco+TLTXM6QX+$9mb4Meu(T>0&2->+ND3urqMG*Ogh$Qf2ezW@o3)RjD{?uTO=l z2tL`5%t1E7+5~Z~?6k3SMTUH1Y_V2qrXWNxHL8;Qoqw>bB{2kr^S3Rw{a}xXGT;cn zt4L945jo!GmCLY!(;oaZ#x{q?*+b_DUA_j_kE)9ju*`EBb~BZ+Y5k%PayZ%rUd9!p z7qTp*y@<IEPy2rhn2kqMV^xgSG`FTH-pX%YXlTT*(tJ@_Z%+r<zq&h2+F}#%x@!j3 zQeoppi<EDjREyDDIZsxTIZ?r%=qZBdtBBh2>&3Wz)3bE^QSz=^B1><eZOmG6qOj9g zA1LlvEK&WuHj6Qj89A;NG~8;PUny=a56J(!EOSL0!puUPYs%ars;>S;kdZV%0s;~? zCo0&{j8&$Vs)0Sg6(@o4;I+6fG=~3SOm;(v`nz}A(H3bC7qvM*sWCEMqRS&BM2$oY z)wkh<uaizU#Pw8Qq8$YL7RZtc^qC4Kyh><Uk|lNUVFnWpy#NOIOmJIthPPzoYgKwM zRVGV4&O301I*2e0{4jS;(*`0GU2j$|GaQ+5yrehW_shNCmrkz_*#P+_%7EY5v+xeY z$oEy!MiqZcRrFP=n<0~ulA0`*9{_W}$-l|T$$yfU16VBw1P4#2&Je;Ex22m#-ht)M zZy#@D^H2FWRVMMK;g3T7Rn|TQ%br*L(74Y9dfjmrS73RE7!hRo=a$)O&W;?DBhwLo z!a7^RuOLL6mBDiHV^DsqaKdT7qva=gHie#jQ#`B86ni9L>8VgrixmQ~qgo<T<C?$> zyYm>Oo-2RTns<F7lG8lnjP;|cBBwhX_*U-Nj`@6avvd@{O&-kC#UU(;G8Ra`!~?(D zBj=Z`5LahAw?}Xa>lplJMVF|z0;i&0jHWhdiQmFcv*A7L5qt^V1=m?_MHKsT*_63Z z4ymC2J3AZkk3ZcUV~<;Cb4M^lZGFOAvjKrKvmapffmWn}4b(wn#*X9Ym7kM2VCbl+ zQC=+}vm;z$+i`n8v=WoRuY@vL!3M%$?d4((mNDaf;0>Vm!Q{{yGy>%~Gd<`}lI%Bx z`x`KCwPYubNyZ*%i@yoE^a<ZkN)OM1;lpW|rGPwa5Q^DkxrL=&;&EUZakX6_2i&En zd(48xcd$(F>2wS!1?}!f${r|~A@`MtXYg{MQSr526)*wrW=EkVyp^0q0>9|@%?y*S z6~&m^%Qs{3ZBo9{s^X4s%`zI2Xu5;Z@nWFQQo7`wlt3zbt}1^Mc>j&chW3!%387Vp z7eF+q^xZ6D2vfzqwe-e$oarx0>k8Tw0>YHs5|2+Gq7<r*^}a}31JX4;M}hrTF#%!P zb(Y+-1^o)OirTk2#P6Z83%NZ5U3e?<6(izuMIxK%aZEO)bAB{6$_5?*aTxkoSfpl9 z@ju`^vOoLhbD!_I(KSOT-m+mrmF^U1hd6YRjx^LzkdXudeRvTVCInH+^JzRTIVE+l zu#PZn()Ikhn^-xhzrLbN`H+(GNW{Ebt9GS3!ZdFp9yL?b^@NZoNJ-4k!A_7v7Qr9I zjKKa)HxZ2wDJ6AmMcb>~cP~0}J8P(h2Nfl-vA5>4nM+UbO!bq0vDrDPt4lKKzw!+9 z*P`l~B+HJDZ(~Kh8C(!%8K&N)kG^L;O%jVyG2hVm3Rq4;g~hy%rzofwwnh0eXRPt- z2Xr9+Zh}z1|GSj0rjoE0#@IH!NP5-}9-ocis_RV$$hflsrPGYwj3uLXQ3(A*n=X_d zvH8<j*e%4QK?LIbKURtZsEEFP4cIDiyK86*`#PM@B6Z!_VRgD)H8h4M$7FNjaYJ!& zUX1KWbP%2ohW1+hED1!(mjxp3;30kfV4|c$W+;py$IAHXedfWm1;!-N;dUtY+Xk5) zB_cjpqXi=A8mUsOM;P(k@x;6tlk;J%UnMdHinHQgC=rg?)*~Aff!TIIlMAARhHt!a z3;wYLR7JroOWo7e14pZfw43{qk{5I8SM0y|{)8dKpH16zlEsE7NSNs+h{N`(@F?+f zCU6=8DDTCDVy2du4*6oTY@^a?fBG`mlaoi2lV*<gjugTuKPTHU`bEK}>o%aVvBbIi z`d<&2B;EyR%YA#uVKbw`zTe*t7*SUmYUX3sx~S2rfW2?ayMYn#MA2g1xrHJNM?qFW z(h55Sobj-ljGc9F>j@^{pe_7>nvhBrK|7^xfzWTt#@1RDFP*7TW&^nr(u>p=$S@02 z64ErP$d5Tv4wlFAH{MU0zUPxBp<CjV6T*D6u&^CI0dsVpL-><L=V8_sb`CaAWDw*7 z=eKuA!3MLJ@tiOsNtRA!9=+0Y0gJn2E1U~f))uf#Yw_#X*MsQ+iNAkE;^J7NJhkq~ zN~ozvZwvuj0saeX#$Fw(QjG{C>;UR|aPlzc>-VrCBEI?-W@<z!4}95SrZD0Wa3;q+ zz5dnrHtXbMd`0=fvuCZlhzKM?0Y?JynGsY7m)i`|@{eOu<94ESB`SZ+w7MCzhFM}$ zl+kPeX-F_e-sv{$5?@YUB^`f$JY%E`ZlkgzVZMoaNZcviHKB!I=Z^6plr=RU*mUd} zH&_5emxlz4|LhMVMCmv!RxZ=%i>K9d4~9%HCijcu)cZ@mJc4r}y<9QCuNP$gmpR$9 zxfp$qT`F__TZ<oxR*N;8`o7zUzfM6>3%$uZ_EiY|Hk>3(xOMMH;SjK>gfi07Pm5km z$ZaNh4~4(SCmCoN>$g!TnkI?;%2B}@P8RV$<{(n=OaHum$@O_QRqs=9rc0PNsw^a8 zlvS{Qi#EQQJU{bU^0M=3^<AebcDe7LMK+tCRJK!AQ)@PxZ)XzBM6E6Z_zP_~+LSU9 zf^CIM=JGl2l}+&B{-8FLl&lHl3=CFhNjd%e=tHF0Xf+uV<H|YdW(bXyU<!Ia%ab!k zxey{HFe_yFwB;*O=x#P`tibIUQ13&y>!x=X2-Z^)tpk0JZ_6Rkr+?A5AAkMe0mO;? zyV7!|^y3FOl341|t=F{f8c#FWj8&=M+xj4&&iOiGkjQf(mB*|N6&z*VarF*8$7jeZ zXuae9_Ka2YkM=+vTbxoiqaXXIP5aM2{uewhyEWdr%`g(Z=qlX|A>hS8<-odqam$=6 zcJ17j21TdC>P*%1U8kSChu_KD1AmRt0|)*g*Qkxr4~gC!AM#K=-8%Ejq}a_?_oH8c zxXt>H904!gR}t1q^^+Kzijc^LZ&>l7zj#q`eek9!3eb5;iCSf85Q8jaX^^!BSJ9@4 zB@k5>5CG(oh(4#$w2WvKg)_`1M<jQ<_T1jrQzE&(uWG`1h$M~9&|wj}5e--j?H*uc z+ft!1=bh%Xl0NXx)E_?-Y~i4@xg1wh&cpaic2ai>Xvs&kf&u?n4PzEi)wBl6>z)T; z8I_c$WcYB;BzL`D;Bzsh83<1JQcxg?1EQyxJcQqS6H=i_Q&;;d*2~T;ZoE{{rvC;H z4`RkXr^k7;^k+dCQdjyddEx@sP76q)>(&-U>gK}`=|~})WHyf$e?!#y?H-}^pg~W2 z?BuF+xO$3<voo%a1%CDML;-Bop^A1UYd_o!yxL}ezFS%P+9LhQUW|tUD`?ninIEWQ z4$%C#DUsKmfc7^e5AlA!*7(W5NX+KFhNw|oL{<Cax7l-(9Wm~Q2H?^9L?dUqWys2R zHJi&F*m{?`x#4@WnaO1>5{z%#ZMJmP3$VX&aa(sijDCZ@Wn`lN_)L-O%ikqB=!%}} zH}-OS(bewzG!7*8dt4sJZ^45-$-L}dvJ<wu<eLQE?q#T*{v(m1;Qx7hrBui?K2o8f z=WDbN;;4On8wY{V0nCOwqJ+G^`ILNj+RXK`A772d#Y1hoFBlgBzHA6=_`HaoF;j@a zgeFQvci)0o`WhQf#0#fCr!>3Y29iG4HGq-wP(BT0*0vca3SCNCsaN}*MkB-BpLN{i z=nO=?1wG^-3wk~bDW$G??sn;|v4TLY-n$v|r=Sj(iIEDo4gU?H37vjo5s&3?;Oi3@ zKuSSDzw5fRs>-wL<$lOA4UsCn7l~T2q34xizRI83BGz4~q1gGaOi_H^IsGHdz_0kk zfKVK7>%-qe3~PQ{kM+AIO1yLT)-#V$L;^Qm=&zZ$PM>)ph4!V!;DDa3E(;6{Mv+*= z$nbdR-T@n4hlTid-R&xejZ8RmOl)k0MMW5Z!FBunqSTx#y{Yn><)=f}i<N40z*n74 zG(h{q*vDgJ%k1pz9K1vf9`D774)%n8N^0tAhn*WB?R5eE5c%x1E6;87LQQS{(`KD7 zm*-#P)z!N;d^*g{%&uHO?`JF3D(dRGS06;t>SR5uDtc<99Dq+fmwwY!gtn~+W62no zqotZp2+F_3cHJ+^r<@*{TsAIwyk?lNU|UbAxj0_u`zMsT9WL$Ow^#YtF|?lr4~o^( zz`lI5m`jso!n5}{<z!IXo2v1_w}V1q=HS@h$qxeL*?$C>=eRqpj3I+<?HFRev)k3@ zdtD0Le%gVK-_y8G+4I-moD+250PGrT_N<qA{$5iNjIr;I>QZ1?frkUF5Q){}eAjW! zg~Lt*7F_+G>tu-dJlCY8DN^|_a=^9*iLu7B**0evh<JWlY_-ze)AohvLjtBP_Rq9# z%qG&%V|ham!F!}A95;j9+<~Bjy@$(}QDbv<+kT=i^4{<Dx3^877B#5nJ6b0DIicrZ zB_reL4e^+}R^yWyuF&0N(d&4byK9TnXft}x_pw)OQRjO1j9=U4w3@PMV$4al<>MyM z?Rw{VY5K5!_gGY_Psr*VXFg7^QPt)Bcz4<PL<;!ym7t+VuX)_;cr9uH0UHqg<=7)g zr-psUN7sGY-=;&O;)Ai%LRh}<EIw5i9KcrM<E0my|Jho;1Gozv`dEyatWs9z8V`yi zHC%ZcH(TlLBL5m4A0Ma2;=bQ!e&n#6>s$&@13~u?4}#meewW?rpDhNgXN~7ZgHhk> z_J{?5!?{x+MG-}XP6Sr>eN|oW`LiE@dmwJ&Bx-2K59_vcOP*%A#Vm?qKQ&7niNRsr zb4K;B!@4})$#yjBYaDJC*=eRS5ZJ0({7&N!0N3N)A-lX|Gavgj0)yEBh8&>vLT9<C zVn8+#11Q6*{%mC5N+v?~a8l>2YpfBpV54nz$PVxqhfn$Le)beA_`35~I&og7*=}>; zW4*b&oHjk(C52H77Qg^<T+N+VU*9Ev5E6KrcdO}sO|fX2X-qDZjCs3y1HUZ&bQI>3 z8E&^j4(rh8cJrT**iY3)kyu}K+I9|6Q+0RVoc<UyebsGp{IkpCj>Y!b732g&b$})( z<=s6%m6wj2`K-ZFW4tH8Pm?&>+FlrM=NP?s97|*}J!CJt3<YZ4oeos&?0#Lzo_Ae~ z)&LiNaDv|FIJq6!++6E)IKAI=eaip)oO{3k8Z+)Uz23FGukxtZJPYNy=~6j*6?uDH z%DG*!yuljRtg}7{G-Xp!P5|5b^ar1OC~<#1=T2LT%6ANifn_x#E;`ENH0!^9pAM6{ zBghWiQnw%pA`Z#oH_1)NY8$@>|J(mFWwpp_(i_12=_ylIYjzjykHaE2+|LDs5dv=| zV<Ix8WMoEy&56MSEt*&<DW5*`{|rl1hQ}|my*gJ_;u*osxU9F{e2%VqMMIGfa!);I zFDr{$F#wfD^%mlDUhXM7QF$s2M6lCRApo9t>i6zO0IIQCeV5n0x#|4qNJZrzBEX~R ztolHsshqcebLFCf?>^z($ma?9&biyV^WZv{smTIMr=H<<?{ICW(?8dy^KYjREtUFh zcd>r!I(3^!cq+;&O!u>=q@rK4h3ay7r$P{kL48?JJ@?6n@JV+ccTBOZ+9Gk}3nuvo z*3c{<GZFDUk!5n)(v)k=gj=O=)D2it#iWh+P=qk)z28lr$Wy^c0GN=a#ii?C5j{UW zSm*W1%LH6<XhYdpiPvNeUCo{P>&!N`%?1Y7=3|hEszMk*K55XL%$L*U`O_`9XIr19 zoQsAaCBb%#+0iKCPn5sx@?=<ud#l>22YE`y5`FRi41POr+F7-6;}TIW%NXf+Sr1op zAO9i{3O;UMKLC0fC@Z^P&oV98pI0&ylTOng_ePz%-|97To%mdirz-6ps;b&Qon^*n z-?m%R`90V#On9ntvhAlvREHq~us$*rsr|BMu);f)I9h$fZ_*vIEKI%T!(;bC*Na<b zdjx!X47_@O1|_IqiN+++@}&?!7OyG7N`||qz8^wb+gTaGlFkCKl*rT><ba7jtm^y| zdg-T)8eNgL9W{W+=OV}#<FZ7Hy1h)e+B`IRN3ubD@Kv$H=&ZRAuvL%`A(YA6)%hys z>ACV0^c>TAmayIdchP;RekY&FW&0WCjt^DMwtpXex}g#)Oy*j1p7#&%F|J>FcFAOj zfM~D6Ix(NG)E7D(iZ?!xABd~I1X}bqfI++fdYTtwaX+q{u=UvUv}}z5nr*M<ru6ql z+LWaAAUNF4!+Xhpy6KY@rISUk+Y#Vh48F2*0`S%QU{7Onc&x0^^uZA@WV_^VF0;(D zd~9jCPc2U~$@;SD;q}n3>kfPun6%!cB5#~{f_V9K`$D!;nA4Mj?{Ea(V9P^RB&yw) zd(P&K_u*@;&1qOXA=*b3+{-jy1`)YyWv-In2zNg}W`bw#hfcu35GMgxr>rgo5#C=c zfAn-Il;sXo7`1FT1f|Az4re#T;)kGwKE*$n6D#=L{q_6n<3!=TE&kT%gqOvYr{Q^i z>-YVAYvap10aECu`@<!mCw9f62{e!Wakmuw((cM<zP<qU*^_>E!iVUoz!bW9h3?I> zf*?yt&AsL9YZK_OezZ}VoWQ1q-*RD*ej6+&mhad;sQ;eH(S5vNHK4~w$IzAHhRgKb zQ$YAmqDcI`G}OIxV1Z$E7c;KB7W+bIsq(Vz#OJr|@<#J2&oU1pG{TwJP4%MZF(klS z(1jOp_GnZ3Fe%L>AZXpcbz0LoF01)Dbq#zy?rmsrob-yu<pb^e$=?zMgYW?U`Eh7B zl+^Kn@rX{wO*AfkHO6b)d@vOtqGPT|5jpz40fjIlig{D`=({f$EjZ$_{CbB0%`Q23 z)NNy2y8h($E`*ufi@Z2tpyW4RAc4d3-;EY?9|4Uw+p3EH6)z0X^ZJK53%#gg=<vZW zPI~>(2cFryY1{5y1)oiw@!-7^*j3`cCQo_vfr-bC9?!_E(=@knEEfB0>Wn{La~HZY zasCynirst1qb0@h@ys1MwiAs>XzYTxHz_G8yW-Lt=Y0DU0C?8C<G0<{Uv>Mk#j7Al zdlucesJg<hr_KKQtJwf>X8YD%yPb2-?P?ebmK2v>KKzEYt2Y3^Ih{M4(YWE!qsO0m z{O|9-Jrw|FeLeT<ufFr~$_~BzcK70q<x5s&WM-<==(}%!^gyQ}mkbO?A^~)6L<dQb zY40*6T@-S?re`DztL7)Wp;Tk)fO@6xllu;!$YyMke4@5l<<te=(n0(&6#Ow^eH>+9 zR&WvB)%wN5obEllW@OemcI3GCT>B2_`N_1m0pNvaUVHV$x71nJtXY$k)RcnX_eG;o zKfWTHsc+PmB9Tbr#yQ2srOL8h7vd;7Wn^Y#=hQDLE-flLY<Euz<?o=n6=x9;W!3t) zk97b53Z6+sK~%4oUOTOD-@&R_l{LH*GBWGrG;B~&5iQ(*FjiH?Zy`NBEvtULqJxK{ zey|4swQ8lFJbBVyTGq`f3DLTIFNDy^zGxDS!=(ATfr9}OH`toXo!h?8$$baWCWvxU ztbwQ_W2|z%rwb<`tDb4M(QyePm-MT<_HD4zvKwY2LeYUk;)4mkU--pYXP+63R!;qJ zT5)m7=&MGY(YPT1T-5)HUp8$6SHly5v)?^v6DIuCMBj1#$i784MT4Z)fN0wV9T}4I z{wUCH&@Rl14-BwZ(T?vhIT<boy|cO<O4#5d&7XZ}+@LG=7g<mpxru2~O8^7A=3ELJ zMqz|E76(V*a#H~WDJu}9q^2NZ#mNeTwB5RO-haM$qiM6o9EN*#!Ylvz;PcZq*+8id z(Ho|+XA(1|&=Rgf)^=<6<tKiYXp5}4&BCEZU^o*p><<&UznV0=$fB}K8lAZA8s7@} zC{xLz72CsMT)FN0ME4i5r8fzek_PG~5qq|qmY!B#UM~7y<;)VaU|QR6xlG3#*9m-9 zAQ2!W;`jlkq^5N5(WO<J7LiD#V9&l~OICX&07?+Yu%n59(By-gDt?YZ-L@A@@OLmZ zHxd|@sw)xe(+&~~A&2jGL=n1YkdHpG7DzSEN=8@B@c_v`B$Fz!^9DojNuD3XWMs5K zAF?rKttv&rq)pW%+s>I7jRnw|AvQUH7_>}86Dc`3WL#JcR8YfxGD$0N&Ibyb+=H(3 z#8Sq=1QsML*Z3sXr>@$(42dN^a?Ag{oJQHFPMtb-^f-S#_s{`Dh#+Y5nG=E3(g~K3 zkyZr-Dj?aT%C4-qg6V8H_JT!TvL~iS>|>6|ATg>yLy`|wuc}~=BPiSj11L{2u0fdv zN+n1RT#4a2n2--8v12A~hOA0Y5bw)iomwVmRH|eVB#OoiBCUy)vg}983R|t|B&-)n zG{%r7x+52&CP1h<RTYa>3*9S;3nLjAsz$#2$7N{EFk%B+e=-b0><C1Qdu=K{0C{>J zto@OZW67~Y;!RevU54w^65~imgzbucYInUylSlLcB|RKlZJTo{+E*PXGRoo!1}Idx zP$QSbpcLUG@z$uDv52drg6U+n!UWG@O&1o-*Vc{D7Kyti2p@$>g-oI&GtRhgHalBc z2pM-ZAs`YChzUCy=^$G&68)`)v9hUYz`-tw5=+SkM9~>3cZ53bRKtYX8_Qei*r-TD zXa*hO13I3X4Q}wJcZ1w*45gAtwWDVXtdoHI7v0Kep;>5qb;-#kJN?8UF094W<U33Z zKI0jo;-oX~6mk7D5%O9}T(+#U(eP&p2AdG2)F43T=HZQ(R{f0I7%QR?uhNMTXlQ(2 zSST4$4tsW{bbyH7<m47~uuS>Ut`7_ZiZ~%>M?mZxCI{}ygML)D%S1y&11*Q=qDDC_ zUXo-3;#=<W2`n`sE;GZgoZl|jT?d)2anUB}HAPXYQKN<j3yb(mO*$7DBjJn?7mZFs zt%_xWa8T12cH}~Js70Z~wg5vALL9_O5g|klWQ5Tml|F=Ti9D)77KB++m<BS)G95oq zM8}PT*5#1Lu%!hmm`CKw?aan}l!8<o<C9X=DlBomn-C+F?%pg6Q;pD@@-#wK&QSFv zi)KQ>!jQ;A8TBa0w#tJC4jJe^-*IH<<`{ich*HRdObKJ-Xl0#CQvZc~ZV9@M8?yZf zxo?VC5`u;>kgKj`sTQ$7ffc~DSRUuh_};`-4`<s<rN6GOZ!i@`d0Ct>MS$lhf)pxu z8OqEuguM02Ar;3`5Fj^u&Dv2~tp?4gS{>O+*iXvdA=ivTtIml=GGg(R<kh$aRZ+kW zQCA!i&e6eLWKv0JO~&JzmzvpwW}6(?a+|<V@Sq|m*+psoK|;L&Z6r~}n`HY;GIW1H z@s@xOQ5W_mr}U6vuNKO|M1z2-m#WPg3aQ|g^>MlR999v89kRqD4z?4_I*Vh<pK5Fs z8`UW%&0Z2hnI&qNSsb{&Z3QZLpJp;=0fpd-($Ff<Bx2<F_<)HQf)?E1@VSv<#7#Ve zA>t?);|*(e1M=QfL+_8<B<lmw_KlL5B?OBtWeBYSDFP790k>U(NXL;&8502)Ym|S; zr2&a$5L2TKs_Th^-toGS!I98H?};!C6epG_!gES^(98=fSSPfUcZFWPD`Oyzi2Fx7 z5%Y^?lal<AC8I#L?ky`=5Scjvxp#{j9!Cei9c8GiMYp(i5X#y%N-t;lU8a;S(jFZi z6M!kv#<an8J}EL34PF>g0!OScu7T#geWWJGV=aU=?ZGaT2x$-h#`O}R3q=v;hep){ z?375HL`r%Xjd;-2k}d_gjVT^vNAPZlP!HlZ!f7K^R+9|{!YwZdO^yPZD<1>^iKB_{ zG?m(tMt_k^R<$p->?@1QeJ_&@byABGeaNp+qBJ=x&P7caWu+lwmZ8MGnCud-6-lXI zBQUg34tqnRp7awGOPG^c7{dv{I161nClZO&t(SS^a9m}_LEIz8>64uW=)(QbU6zcW zdMK{b68|z;5(emI6<lNkI~hrpA$^8{-9UzJp9OT2h0Js6KZ-^;W7G->rw$GgDO0YA z51=6y!st+uP3i?xzz$_)LZ}Y-X@EYmc(0V12-!(0gLmX4!T24SG6t*+!6^lZn250i zB-QWbtI^yuGB`zy#bQSe9p&XH-B&|$f;g{Tic9d*WD@7TJ%JuYH<K}a(TYX<_{d+( zkX?}ncef);Af5izDnQGSj>E)iN1=Vf@p%o3>}s-?kaVETq9(q*1sy=EL7N{9T$UNg zIFwK#@u~=GgPH&a4bUv~kWgXN>*?T-=oT266oNewLuDI?XzKhJxxEm`M5odt6R1JI zX-02M*;-4$Zya5jHz3#XR5>x4;I*k>B1D|f0v{=$rfv`72q_>88F5f)aTB@OBf!Pz zO#oKC8wy6KQ}~(DF3{D`DJtqxW;}!;(!Z!jPHA9X*HbKvQT_$^j#6178ZyQ95lA2> z6Ki?^J2sI}Xr+pwAbOk^(=D|W{1I(7AsVyBIN&eL7ZVlT(5$O7BewKn(d6HuIYEdV zg)=UoC~*P@$A>wckgV7RRE&%o0vXH@G<2PLs4WG$dF5BKa1AvGG4e&O5)te53@QGz zyKFD_y`e$|U}j>h-el4Vx#pgYen@Oc8={=$MLbGnWd`DfMx%s_x`4oyH95~EZsHM} z{{vu@Fa)7T>7`n1esqQtQWRI1v$H@LLaAjRkDIkqK;+Zmg?6475-?cT;kFbu$m@UT zC~sL~$b`U^aoX~GlmfCw(ZW>(3Q4?|_yL3h-M3~a=<URts&z5XucTO5CmYCT5F1oY z4pG$hQ1o*!O<6X8fqfgz5maP@;&CVBN-OPZGa7o~29?T>@)IS6hRD1q0Gj8HQ4wLw z8*mt+nNR9yhv~7asqu!$A2<s2Hkkt<!HhLDQWuU&$-u*fb|8<fU0_7WoFOSIXGS$h zhR)&ulH+X9Jwyn>aFMzghiEWQMG?-Ay<Ln0N={9wI#pF&T}_5*x>!9@71y|51jhgv rGUjfGRUr@=g4pT;H&Z~g_rL!G0}@<EOO!w*00000NkvXXu0mjf2&MAd literal 0 HcmV?d00001 diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 64646c600..ae8ea5667 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -88,6 +88,12 @@ <img class="sponsor-image" src="/img/sponsors/zuplo-banner.png" /> </a> </div> + <div class="item"> + <a title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" style="display: block; position: relative;" href="https://fine.dev?ref=fastapibanner" target="_blank"> + <span class="sponsor-badge">sponsor</span> + <img class="sponsor-image" src="/img/sponsors/fine-banner.png" /> + </a> + </div> </div> </div> {% endblock %} From 42d52b834add728a62ebb53b1ada439d92a1d55c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 1 Jul 2024 23:09:02 +0000 Subject: [PATCH 560/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e17ca2f6a..c2fe10fe6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -64,6 +64,7 @@ hide: ### Internal +* 🔧 Update sponsors: add Fine. PR [#11784](https://github.com/tiangolo/fastapi/pull/11784) by [@tiangolo](https://github.com/tiangolo). * 🔧 Tweak sponsors: Kong URL. PR [#11765](https://github.com/tiangolo/fastapi/pull/11765) by [@tiangolo](https://github.com/tiangolo). * 🔧 Tweak sponsors: Kong URL. PR [#11764](https://github.com/tiangolo/fastapi/pull/11764) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, add Stainless. PR [#11763](https://github.com/tiangolo/fastapi/pull/11763) by [@tiangolo](https://github.com/tiangolo). From 6b0dddf55aee5d11557354118a0ed37f35518b1e Mon Sep 17 00:00:00 2001 From: "P-E. Brian" <pebrian@outlook.fr> Date: Wed, 3 Jul 2024 04:15:55 +0200 Subject: [PATCH 561/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20image=20missing=20?= =?UTF-8?q?in=20French=20translation=20for=20`docs/fr/docs/async.md`=20=20?= =?UTF-8?q?(#11787)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/async.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index 3f65032fe..eabd9686a 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -103,24 +103,41 @@ Pour expliquer la différence, voici une histoire de burgers : Vous amenez votre crush 😍 dans votre fast food 🍔 favori, et faites la queue pendant que le serveur 💁 prend les commandes des personnes devant vous. +<img src="/img/async/concurrent-burgers/concurrent-burgers-01.png" class="illustration"> + Puis vient votre tour, vous commandez alors 2 magnifiques burgers 🍔 pour votre crush 😍 et vous. -Vous payez 💸. +<img src="/img/async/concurrent-burgers/concurrent-burgers-02.png" class="illustration"> Le serveur 💁 dit quelque chose à son collègue dans la cuisine 👨🍳 pour qu'il sache qu'il doit préparer vos burgers 🍔 (bien qu'il soit déjà en train de préparer ceux des clients précédents). +<img src="/img/async/concurrent-burgers/concurrent-burgers-03.png" class="illustration"> + +Vous payez 💸. + Le serveur 💁 vous donne le numéro assigné à votre commande. +<img src="/img/async/concurrent-burgers/concurrent-burgers-04.png" class="illustration"> + Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant "magnifiques" ils sont très longs à préparer ✨🍔✨). Pendant que vous êtes assis à table, en attendant que les burgers 🍔 soient prêts, vous pouvez passer ce temps à admirer à quel point votre crush 😍 est géniale, mignonne et intelligente ✨😍✨. +<img src="/img/async/concurrent-burgers/concurrent-burgers-05.png" class="illustration"> + Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d'oeil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis. Jusqu'au moment où c'est (enfin) votre tour. Vous allez au comptoir, récupérez vos burgers 🍔 et revenez à votre table. +<img src="/img/async/concurrent-burgers/concurrent-burgers-06.png" class="illustration"> + Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨. +<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration"> + +!!! info + Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + --- Imaginez que vous êtes l'ordinateur / le programme 🤖 dans cette histoire. @@ -149,26 +166,41 @@ Vous attendez pendant que plusieurs (disons 8) serveurs qui sont aussi des cuisi Chaque personne devant vous attend 🕙 que son burger 🍔 soit prêt avant de quitter le comptoir car chacun des 8 serveurs va lui-même préparer le burger directement avant de prendre la commande suivante. +<img src="/img/async/parallel-burgers/parallel-burgers-01.png" class="illustration"> + Puis c'est enfin votre tour, vous commandez 2 magnifiques burgers 🍔 pour vous et votre crush 😍. Vous payez 💸. +<img src="/img/async/parallel-burgers/parallel-burgers-02.png" class="illustration"> + Le serveur va dans la cuisine 👨🍳. Vous attendez devant le comptoir afin que personne ne prenne vos burgers 🍔 avant vous, vu qu'il n'y a pas de numéro de commande. +<img src="/img/async/parallel-burgers/parallel-burgers-03.png" class="illustration"> + Vous et votre crush 😍 étant occupés à vérifier que personne ne passe devant vous prendre vos burgers au moment où ils arriveront 🕙, vous ne pouvez pas vous préoccuper de votre crush 😞. C'est du travail "synchrone", vous être "synchronisés" avec le serveur/cuisinier 👨🍳. Vous devez attendre 🕙 et être présent au moment exact où le serveur/cuisinier 👨🍳 finira les burgers 🍔 et vous les donnera, sinon quelqu'un risque de vous les prendre. +<img src="/img/async/parallel-burgers/parallel-burgers-04.png" class="illustration"> + Puis le serveur/cuisinier 👨🍳 revient enfin avec vos burgers 🍔, après un long moment d'attente 🕙 devant le comptoir. +<img src="/img/async/parallel-burgers/parallel-burgers-05.png" class="illustration"> + Vous prenez vos burgers 🍔 et allez à une table avec votre crush 😍 Vous les mangez, et vous avez terminé 🍔 ⏹. +<img src="/img/async/parallel-burgers/parallel-burgers-06.png" class="illustration"> + Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞. +!!! info + Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + --- Dans ce scénario de burgers parallèles, vous êtes un ordinateur / programme 🤖 avec deux processeurs (vous et votre crush 😍) attendant 🕙 à deux et dédiant votre attention 🕙 à "attendre devant le comptoir" pour une longue durée. From a5ce86dde58b85a6a5b2bc210db1dfa81a1257e0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 3 Jul 2024 02:16:13 +0000 Subject: [PATCH 562/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c2fe10fe6..4014491bb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 📝 Fix image missing in French translation for `docs/fr/docs/async.md` . PR [#11787](https://github.com/tiangolo/fastapi/pull/11787) by [@pe-brian](https://github.com/pe-brian). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/advanced-dependencies.md`. PR [#11775](https://github.com/tiangolo/fastapi/pull/11775) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#11768](https://github.com/tiangolo/fastapi/pull/11768) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-status-codes.md`. PR [#11753](https://github.com/tiangolo/fastapi/pull/11753) by [@ceb10n](https://github.com/ceb10n). From f785676b831f127b39d0c42fb92342906f0492b1 Mon Sep 17 00:00:00 2001 From: Logan <146642263+logan2d5@users.noreply.github.com> Date: Wed, 3 Jul 2024 10:17:04 +0800 Subject: [PATCH 563/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/tutorial/security/oauth2-jwt.md`=20(#11781?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/security/oauth2-jwt.md | 134 ++++++++++++++++--- 1 file changed, 113 insertions(+), 21 deletions(-) diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 33a4d7fc7..117f74d3e 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -26,29 +26,25 @@ JWT 字符串没有加密,任何人都能用它恢复原始信息。 如需深入了解 JWT 令牌,了解它的工作方式,请参阅 <a href="https://jwt.io/" class="external-link" target="_blank">https://jwt.io</a>。 -## 安装 `python-jose` +## 安装 `PyJWT` -安装 `python-jose`,在 Python 中生成和校验 JWT 令牌: +安装 `PyJWT`,在 Python 中生成和校验 JWT 令牌: <div class="termy"> ```console -$ pip install python-jose[cryptography] +$ pip install pyjwt ---> 100% ``` </div> -<a href="https://github.com/mpdavis/python-jose" class="external-link" target="_blank">Python-jose</a> 需要安装配套的加密后端。 +!!! info "说明" -本教程推荐的后端是:<a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>。 + 如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 -!!! tip "提示" - - 本教程以前使用 <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>。 - - 但后来换成了 Python-jose,因为 Python-jose 支持 PyJWT 的所有功能,还支持与其它工具集成时可能会用到的一些其它功能。 + 您可以在 <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a> 获得更多信息。 ## 密码哈希 @@ -62,7 +58,7 @@ $ pip install python-jose[cryptography] 原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。 -这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 +这样一来,窃贼就无法在其它应用中使用窃取的密码(要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 ## 安装 `passlib` @@ -112,9 +108,41 @@ $ pip install passlib[bcrypt] 第三个函数用于身份验证,并返回用户。 -```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="8 49 56-57 60-61 70-76" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8 49 56-57 60-61 70-76" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 50 57-58 61-62 71-77" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` !!! note "笔记" @@ -160,9 +188,41 @@ $ openssl rand -hex 32 如果令牌无效,则直接返回 HTTP 错误。 -```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="4 7 13-15 29-31 79-87" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 7 13-15 29-31 79-87" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 7 14-16 30-32 80-88" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` ## 更新 `/token` *路径操作* @@ -170,9 +230,41 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="118-133" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="118-133" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="119-134" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="116-131" + {!> ../../../docs_src/security/tutorial004.py!} + ``` ### JWT `sub` 的技术细节 @@ -261,7 +353,7 @@ OAuth2 支持**`scopes`**(作用域)。 开发者可以灵活选择最适合项目的安全机制。 -还可以直接使用 `passlib` 和 `python-jose` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 +还可以直接使用 `passlib` 和 `PyJWT` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 而且,**FastAPI** 还提供了一些工具,在不影响灵活、稳定和安全的前提下,尽可能地简化安全机制。 From eca465f4c96acc5f6a22e92fd2211675ca8a20c8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 3 Jul 2024 02:18:33 +0000 Subject: [PATCH 564/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4014491bb..b2196498c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#11781](https://github.com/tiangolo/fastapi/pull/11781) by [@logan2d5](https://github.com/logan2d5). * 📝 Fix image missing in French translation for `docs/fr/docs/async.md` . PR [#11787](https://github.com/tiangolo/fastapi/pull/11787) by [@pe-brian](https://github.com/pe-brian). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/advanced-dependencies.md`. PR [#11775](https://github.com/tiangolo/fastapi/pull/11775) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#11768](https://github.com/tiangolo/fastapi/pull/11768) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From dc3c320020e38fe988d9711bf5ae6cac3500246f Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Thu, 4 Jul 2024 17:53:25 -0300 Subject: [PATCH 565/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/openapi-webhooks.md`=20(#?= =?UTF-8?q?11791)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/openapi-webhooks.md | 51 +++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 docs/pt/docs/advanced/openapi-webhooks.md diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..932fe0d9a --- /dev/null +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -0,0 +1,51 @@ +# Webhooks OpenAPI + +Existem situações onde você deseja informar os **usuários** da sua API que a sua aplicação pode chamar a aplicação *deles* (enviando uma requisição) com alguns dados, normalmente para **notificar** algum tipo de **evento**. + +Isso significa que no lugar do processo normal de seus usuários enviarem requisições para a sua API, é a **sua API** (ou sua aplicação) que poderia **enviar requisições para o sistema deles** (para a API deles, a aplicação deles). + +Isso normalmente é chamado de **webhook**. + +## Etapas dos Webhooks + +Normalmente, o processo é que **você define** em seu código qual é a mensagem que você irá mandar, o **corpo da sua requisição**. + +Você também define de alguma maneira em quais **momentos** a sua aplicação mandará essas requisições ou eventos. + +E os **seus usuários** definem de alguma forma (em algum painel por exemplo) a **URL** que a sua aplicação deve enviar essas requisições. + +Toda a **lógica** sobre como cadastrar as URLs para os webhooks e o código para enviar de fato as requisições cabe a você definir. Você escreve da maneira que você desejar no **seu próprio código**. + +## Documentando webhooks com o FastAPI e OpenAPI + +Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webhooks, os tipos das operações HTTP que a sua aplicação pode enviar (e.g. `POST`, `PUT`, etc.) e os **corpos** da requisição que a sua aplicação enviaria. + +Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles. + +!!! info "Informação" + Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. + +## Uma aplicação com webhooks + +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!} +``` + +Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. + +!!! info "Informação" + O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. + +Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`. + +Isto porque espera-se que os **seus usuários** definam o verdadeiro **caminho da URL** onde eles desejam receber a requisição do webhook de algum outra maneira. (e.g. um painel). + +### Confira a documentação + +Agora você pode iniciar a sua aplicação e ir até <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Você verá que a sua documentação possui as *operações de rota* normais e agora também possui alguns **webhooks**: + +<img src="/img/tutorial/openapi-webhooks/image01.png"> From 8d39e5b74a9d3640402b4d3f1866f94ec76e153b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 4 Jul 2024 20:53:46 +0000 Subject: [PATCH 566/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b2196498c..d41e370f8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-webhooks.md`. PR [#11791](https://github.com/tiangolo/fastapi/pull/11791) by [@ceb10n](https://github.com/ceb10n). * 🌐 Update Chinese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#11781](https://github.com/tiangolo/fastapi/pull/11781) by [@logan2d5](https://github.com/logan2d5). * 📝 Fix image missing in French translation for `docs/fr/docs/async.md` . PR [#11787](https://github.com/tiangolo/fastapi/pull/11787) by [@pe-brian](https://github.com/pe-brian). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/advanced-dependencies.md`. PR [#11775](https://github.com/tiangolo/fastapi/pull/11775) by [@ceb10n](https://github.com/ceb10n). From d60f8c59b9aa931f84aaaecc48e25178bdfc3ec7 Mon Sep 17 00:00:00 2001 From: Logan <146642263+logan2d5@users.noreply.github.com> Date: Fri, 5 Jul 2024 21:46:16 +0800 Subject: [PATCH 567/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/fastapi-cli.md`=20(#11786)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/fastapi-cli.md | 84 +++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 docs/zh/docs/fastapi-cli.md diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md new file mode 100644 index 000000000..dd3914921 --- /dev/null +++ b/docs/zh/docs/fastapi-cli.md @@ -0,0 +1,84 @@ +# FastAPI CLI + +**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用程序,管理你的 FastAPI 项目,等等。 + +当你安装 FastAPI 时(例如使用 `pip install FastAPI` 命令),会包含一个名为 `fastapi-cli` 的软件包,该软件包在终端中提供 `fastapi` 命令。 + +要在开发环境中运行你的 FastAPI 应用,你可以使用 `fastapi dev` 命令: + +<div class="termy"> + +```console +$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span> + +<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit) +<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font> +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +``` + +</div> + +该命令行程序 `fastapi` 就是 **FastAPI CLI**。 + +FastAPI CLI 接收你的 Python 程序路径,自动检测包含 FastAPI 的变量(通常命名为 `app`)及其导入方式,然后启动服务。 + +在生产环境中,你应该使用 `fastapi run` 命令。🚀 + +在内部,**FastAPI CLI** 使用了 <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>,这是一个高性能、适用于生产环境的 ASGI 服务器。😎 + +## `fastapi dev` + +当你运行 `fastapi dev` 时,它将以开发模式运行。 + +默认情况下,它会启用**自动重载**,因此当你更改代码时,它会自动重新加载服务器。该功能是资源密集型的,且相较不启用时更不稳定,因此你应该仅在开发环境下使用它。 + +默认情况下,它将监听 IP 地址 `127.0.0.1`,这是你的机器与自身通信的 IP 地址(`localhost`)。 + +## `fastapi run` + +当你运行 `fastapi run` 时,它默认以生产环境模式运行。 + +默认情况下,**自动重载是禁用的**。 + +它将监听 IP 地址 `0.0.0.0`,即所有可用的 IP 地址,这样任何能够与该机器通信的人都可以公开访问它。这通常是你在生产环境中运行它的方式,例如在容器中运行。 + +在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。 + +!!! tip "提示" + 你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 From 4343170a2846bc36603fb43e5a302279fe62262b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 5 Jul 2024 13:46:40 +0000 Subject: [PATCH 568/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d41e370f8..419b4af2e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#11786](https://github.com/tiangolo/fastapi/pull/11786) by [@logan2d5](https://github.com/logan2d5). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-webhooks.md`. PR [#11791](https://github.com/tiangolo/fastapi/pull/11791) by [@ceb10n](https://github.com/ceb10n). * 🌐 Update Chinese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#11781](https://github.com/tiangolo/fastapi/pull/11781) by [@logan2d5](https://github.com/logan2d5). * 📝 Fix image missing in French translation for `docs/fr/docs/async.md` . PR [#11787](https://github.com/tiangolo/fastapi/pull/11787) by [@pe-brian](https://github.com/pe-brian). From 4eb8db3cd3457efc11b0ac11927e3b95f871ac2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph09@gmail.com> Date: Mon, 8 Jul 2024 13:09:45 -0300 Subject: [PATCH 569/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/dependencies/dependencies?= =?UTF-8?q?-in-path-operation-operators.md`=20(#11804)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...pendencies-in-path-operation-decorators.md | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md 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 new file mode 100644 index 000000000..4a297268c --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,138 @@ +# Dependências em decoradores de operações de rota + +Em alguns casos você não precisa necessariamente retornar o valor de uma dependência dentro de uma *função de operação de rota*. + +Ou a dependência não retorna nenhum valor. + +Mas você ainda precisa que ela seja executada/resolvida. + +Para esses casos, em vez de declarar um parâmetro em uma *função de operação de rota* com `Depends`, você pode adicionar um argumento `dependencies` do tipo `list` ao decorador da operação de rota. + +## Adicionando `dependencies` ao decorador da operação de rota + +O *decorador da operação de rota* recebe um argumento opcional `dependencies`. + +Ele deve ser uma lista de `Depends()`: + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "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!} + ``` +Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. + +!!! tip "Dica" + Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. + + Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas. + + Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário. + +!!! info "Informação" + Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. + + Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}. + +## Erros das dependências e valores de retorno + +Você pode utilizar as mesmas *funções* de dependências que você usaria normalmente. + +### Requisitos de Dependências + +Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: + +=== "Python 3.9+" + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7 12" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "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!} + ``` + +### Levantando exceções + +Essas dependências podem levantar exceções, da mesma forma que dependências comuns: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "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!} + ``` + +### Valores de retorno + +E elas também podem ou não retornar valores, eles não serão utilizados. + +Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: + +=== "Python 3.9+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +## Dependências para um grupo de *operações de rota* + +Mais a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você aprenderá a declarar um único parâmetro `dependencies` para um grupo de *operações de rota*. + +## Dependências globais + +No próximo passo veremos como adicionar dependências para uma aplicação `FastAPI` inteira, para que ela seja aplicada em toda *operação de rota*. From b45d1da7174afaa1faf116d3f33d6bb65609238c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 8 Jul 2024 16:10:09 +0000 Subject: [PATCH 570/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 419b4af2e..9554afeb8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md`. PR [#11804](https://github.com/tiangolo/fastapi/pull/11804) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#11786](https://github.com/tiangolo/fastapi/pull/11786) by [@logan2d5](https://github.com/logan2d5). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-webhooks.md`. PR [#11791](https://github.com/tiangolo/fastapi/pull/11791) by [@ceb10n](https://github.com/ceb10n). * 🌐 Update Chinese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#11781](https://github.com/tiangolo/fastapi/pull/11781) by [@logan2d5](https://github.com/logan2d5). From 7039c5edc54e3c4f715e669696cf8d7d53aec80c Mon Sep 17 00:00:00 2001 From: Valentyn Khoroshchak <37864128+vkhoroshchak@users.noreply.github.com> Date: Tue, 9 Jul 2024 18:45:46 +0300 Subject: [PATCH 571/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/first-steps.md`=20(#11809)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/first-steps.md | 328 +++++++++++++++++++++++++++ 1 file changed, 328 insertions(+) create mode 100644 docs/uk/docs/tutorial/first-steps.md diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md new file mode 100644 index 000000000..725677e42 --- /dev/null +++ b/docs/uk/docs/tutorial/first-steps.md @@ -0,0 +1,328 @@ +# Перші кроки + +Найпростіший файл FastAPI може виглядати так: + +```Python +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Скопіюйте це до файлу `main.py`. + +Запустіть сервер: + +<div class="termy"> + +```console +$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> + <span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span> + +<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit) +<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font> +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +``` + +</div> + +У консолі буде рядок приблизно такого змісту: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Цей рядок показує URL, за яким додаток запускається на вашій локальній машині. + +### Перевірте + +Відкрийте браузер та введіть адресу <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>. + +Ви побачите у відповідь таке повідомлення у форматі JSON: + +```JSON +{"message": "Hello World"} +``` + +### Інтерактивна API документація + +Перейдемо сюди <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Ви побачите автоматичну інтерактивну API документацію (створену завдяки <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>): + + + +### Альтернативна API документація + +Тепер перейдемо сюди <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>. + +Ви побачите альтернативну автоматичну документацію (створену завдяки <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>): + + + +### OpenAPI + +**FastAPI** генерує "схему" з усім вашим API, використовуючи стандарт **OpenAPI** для визначення API. + +#### "Схема" + +"Схема" - це визначення або опис чогось. Це не код, який його реалізує, а просто абстрактний опис. + +#### API "схема" + +У цьому випадку, <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> є специфікацією, яка визначає, як описати схему вашого API. + +Це визначення схеми включає шляхи (paths) вашого API, можливі параметри, які вони приймають тощо. + +#### "Схема" даних + +Термін "схема" також може відноситися до структури даних, наприклад, JSON. + +У цьому випадку це означає - атрибути JSON і типи даних, які вони мають тощо. + +#### OpenAPI і JSON Schema + +OpenAPI описує схему для вашого API. І ця схема включає визначення (або "схеми") даних, що надсилаються та отримуються вашим API за допомогою **JSON Schema**, стандарту для схем даних JSON. + +#### Розглянемо `openapi.json` + +Якщо вас цікавить, як виглядає вихідна схема OpenAPI, то FastAPI автоматично генерує JSON-схему з усіма описами API. + +Ознайомитися можна за посиланням: <a href="http://127.0.0.1:8000/openapi.json" class="external-link" target="_blank">http://127.0.0.1:8000/openapi.json</a>. + +Ви побачите приблизно такий JSON: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### Для чого потрібний OpenAPI + +Схема OpenAPI є основою для обох систем інтерактивної документації. + +Існують десятки альтернативних інструментів, заснованих на OpenAPI. Ви можете легко додати будь-який з них до **FastAPI** додатку. + +Ви також можете використовувати OpenAPI для автоматичної генерації коду для клієнтів, які взаємодіють з API. Наприклад, для фронтенд-, мобільних або IoT-додатків + +## А тепер крок за кроком + +### Крок 1: імпортуємо `FastAPI` + +```Python hl_lines="1" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI` це клас у Python, який надає всю функціональність для API. + +!!! note "Технічні деталі" + `FastAPI` це клас, який успадковується безпосередньо від `Starlette`. + + Ви також можете використовувати всю функціональність <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> у `FastAPI`. + +### Крок 2: створюємо екземпляр `FastAPI` + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial001.py!} +``` +Змінна `app` є екземпляром класу `FastAPI`. + +Це буде головна точка для створення і взаємодії з API. + +### Крок 3: визначте операцію шляху (path operation) + +#### Шлях (path) + +"Шлях" це частина URL, яка йде одразу після символу `/`. + +Отже, у такому URL, як: + +``` +https://example.com/items/foo +``` + +...шлях буде: + +``` +/items/foo +``` + +!!! info "Додаткова інформація" + "Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). + +При створенні API, "шлях" є основним способом розділення "завдань" і "ресурсів". +#### Operation + +"Операція" (operation) тут означає один з "методів" HTTP. + +Один з: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...та більш екзотичних: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +У HTTP-протоколі можна спілкуватися з кожним шляхом, використовуючи один (або кілька) з цих "методів". + +--- + +При створенні API зазвичай використовуються конкретні методи HTTP для виконання певних дій. + +Як правило, використовують: + +* `POST`: для створення даних. +* `GET`: для читання даних. +* `PUT`: для оновлення даних. +* `DELETE`: для видалення даних. + +В OpenAPI кожен HTTP метод називається "операція". + +Ми також будемо дотримуватися цього терміна. + +#### Визначте декоратор операції шляху (path operation decorator) + +```Python hl_lines="6" +{!../../../docs_src/first_steps/tutorial001.py!} +``` +Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: + +* шлях `/` +* використовуючи <abbr title="an HTTP GET method"><code>get</code> операцію</abbr> + +!!! info "`@decorator` Додаткова інформація" + Синтаксис `@something` у Python називається "декоратором". + + Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін). + + "Декоратор" приймає функцію нижче і виконує з нею якусь дію. + + У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`. + + Це і є "декоратор операції шляху (path operation decorator)". + +Можна також використовувати операції: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +І більш екзотичні: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +!!! tip "Порада" + Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. + + **FastAPI** не нав'язує жодного певного значення для кожного методу. + + Наведена тут інформація є рекомендацією, а не обов'язковою вимогою. + + Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій. + + +### Крок 4: визначте **функцію операції шляху (path operation function)** + +Ось "**функція операції шляху**": + +* **шлях**: це `/`. +* **операція**: це `get`. +* **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Це звичайна функція Python. + +FastAPI викликатиме її щоразу, коли отримає запит до URL із шляхом "/", використовуючи операцію `GET`. + +У даному випадку це асинхронна функція. + +--- + +Ви також можете визначити її як звичайну функцію замість `async def`: + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial003.py!} +``` + +!!! note "Примітка" + Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +### Крок 5: поверніть результат + +```Python hl_lines="8" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. + +Також можна повернути моделі Pydantic (про це ви дізнаєтесь пізніше). + +Існує багато інших об'єктів і моделей, які будуть автоматично конвертовані в JSON (зокрема ORM тощо). Спробуйте використати свої улюблені, велика ймовірність, що вони вже підтримуються. + +## Підіб'ємо підсумки + +* Імпортуємо `FastAPI`. +* Створюємо екземпляр `app`. +* Пишемо **декоратор операції шляху** як `@app.get("/")`. +* Пишемо **функцію операції шляху**; наприклад, `def root(): ...`. +* Запускаємо сервер у режимі розробки `fastapi dev`. From 846e8bc8869d6c2ca20b75d8602563a14e2650eb Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 9 Jul 2024 15:46:09 +0000 Subject: [PATCH 572/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9554afeb8..6a7410f92 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/first-steps.md`. PR [#11809](https://github.com/tiangolo/fastapi/pull/11809) by [@vkhoroshchak](https://github.com/vkhoroshchak). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md`. PR [#11804](https://github.com/tiangolo/fastapi/pull/11804) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#11786](https://github.com/tiangolo/fastapi/pull/11786) by [@logan2d5](https://github.com/logan2d5). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-webhooks.md`. PR [#11791](https://github.com/tiangolo/fastapi/pull/11791) by [@ceb10n](https://github.com/ceb10n). From 09b0a5d1534ed60148be5616b7c983315b758a54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph09@gmail.com> Date: Tue, 9 Jul 2024 14:58:59 -0300 Subject: [PATCH 573/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/dependencies/sub-dependen?= =?UTF-8?q?cies.md`=20(#11792)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/dependencies/sub-dependencies.md | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 docs/pt/docs/tutorial/dependencies/sub-dependencies.md diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..189f196ab --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,194 @@ +# Subdependências + +Você pode criar dependências que possuem **subdependências**. + +Elas podem ter o nível de **profundidade** que você achar necessário. + +O **FastAPI** se encarrega de resolver essas dependências. + +## Primeira dependência "injetável" + +Você pode criar uma primeira dependência (injetável) dessa forma: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro. + +Isso é bastante simples (e não muito útil), mas irá nos ajudar a focar em como as subdependências funcionam. + +## Segunda dependência, "injetável" e "dependente" + +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): + +=== "Python 3.10+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +Vamos focar nos parâmetros declarados: + +* Mesmo que essa função seja uma dependência ("injetável") por si mesma, ela também declara uma outra dependência (ela "depende" de outra coisa). + * Ela depende do `query_extractor`, e atribui o valor retornado pela função ao parâmetro `q`. +* Ela também declara um cookie opcional `last_query`, do tipo `str`. + * Se o usuário não passou nenhuma consulta `q`, a última consulta é utilizada, que foi salva em um cookie anteriormente. + +## Utilizando a dependência + +Então podemos utilizar a dependência com: + +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "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!} + ``` + +=== "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!} + ``` + +!!! info "Informação" + Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`. + + Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função. + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Utilizando a mesma dependência múltiplas vezes + +Se uma de suas dependências é declarada várias vezes para a mesma *operação de rota*, por exemplo, múltiplas dependências com uma mesma subdependência, o **FastAPI** irá chamar essa subdependência uma única vez para cada requisição. + +E o valor retornado é salvo em um <abbr title="Um utilitário/sistema para armazenar valores calculados/gerados para serem reutilizados em vez de computá-los novamente.">"cache"</abbr> e repassado para todos os "dependentes" que precisam dele em uma requisição específica, em vez de chamar a dependência múltiplas vezes para uma mesma requisição. + +Em um cenário avançado onde você precise que a dependência seja calculada em cada passo (possivelmente várias vezes) de uma requisição em vez de utilizar o valor em "cache", você pode definir o parâmetro `use_cache=False` em `Depends`: + +=== "Python 3.8+" + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} + ``` + +## Recapitulando + +Com exceção de todas as palavras complicadas usadas aqui, o sistema de **Injeção de Dependência** é bastante simples. + +Consiste apenas de funções que parecem idênticas a *funções de operação de rota*. + +Mas ainda assim, é bastante poderoso, e permite que você declare grafos (árvores) de dependências com uma profundidade arbitrária. + +!!! tip "Dica" + Tudo isso pode não parecer muito útil com esses exemplos. + + Mas você verá o quão útil isso é nos capítulos sobre **segurança**. + + E você também verá a quantidade de código que você não precisara escrever. From 912524233b535a1d45b54863b2c4e0bd2464b193 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 9 Jul 2024 17:59:20 +0000 Subject: [PATCH 574/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6a7410f92..b47f44277 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev). * 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018). * 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda). From 2d916a9c951a17d0414926eacc8bf4b70a90f8c5 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Thu, 11 Jul 2024 00:37:20 -0300 Subject: [PATCH 575/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/async-tests.md`=20(#11808?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/async-tests.md | 95 ++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 docs/pt/docs/advanced/async-tests.md diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md new file mode 100644 index 000000000..4ccc0c452 --- /dev/null +++ b/docs/pt/docs/advanced/async-tests.md @@ -0,0 +1,95 @@ +# Testes Assíncronos + +Você já viu como testar as suas aplicações **FastAPI** utilizando o `TestClient` que é fornecido. Até agora, você viu apenas como escrever testes síncronos, sem utilizar funções `async`. + +Ser capaz de utilizar funções assíncronas em seus testes pode ser útil, por exemplo, quando você está realizando uma consulta em seu banco de dados de maneira assíncrona. Imagine que você deseja testar realizando requisições para a sua aplicação FastAPI e depois verificar que a sua aplicação inseriu corretamente as informações no banco de dados, ao utilizar uma biblioteca assíncrona para banco de dados. + +Vamos ver como nós podemos fazer isso funcionar. + +## pytest.mark.anyio + +Se quisermos chamar funções assíncronas em nossos testes, as nossas funções de teste precisam ser assíncronas. O AnyIO oferece um plugin bem legal para isso, que nos permite especificar que algumas das nossas funções de teste precisam ser chamadas de forma assíncrona. + +## HTTPX + +Mesmo que a sua aplicação **FastAPI** utilize funções normais com `def` no lugar de `async def`, ela ainda é uma aplicação `async` por baixo dos panos. + +O `TestClient` faz algumas mágicas para invocar a aplicação FastAPI assíncrona em suas funções `def` normais, utilizando o pytest padrão. Porém a mágica não acontece mais quando nós estamos utilizando dentro de funções assíncronas. Ao executar os nossos testes de forma assíncrona, nós não podemos mais utilizar o `TestClient` dentro das nossas funções de teste. + +O `TestClient` é baseado no <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a>, e felizmente nós podemos utilizá-lo diretamente para testar a API. + +## Exemplo + +Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante ao descrito em [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} e [Testing](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +│ └── test_main.py +``` + +O arquivo `main.py` teria: + +```Python +{!../../../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!} +``` + +## Executá-lo + +Você pode executar os seus testes normalmente via: + +<div class="termy"> + +```console +$ pytest + +---> 100% +``` + +</div> + +## Em Detalhes + +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!} +``` + +!!! tip "Dica" + Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. + +Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. + +```Python hl_lines="9-10" +{!../../../docs_src/async_tests/test_main.py!} +``` + +Isso é equivalente a: + +```Python +response = client.get('/') +``` + +...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`. + +!!! tip "Dica" + Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. + +!!! 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 <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. + +## Outras Chamadas de Funções Assíncronas + +Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código. + +!!! tip "Dica" + Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MotorClient do MongoDB</a>) 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")`. From d3cdd3bbd14109f3b268df7ca496e24bb64593aa Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 11 Jul 2024 03:37:40 +0000 Subject: [PATCH 576/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b47f44277..7c56ad1b2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/async-tests.md`. PR [#11808](https://github.com/tiangolo/fastapi/pull/11808) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/first-steps.md`. PR [#11809](https://github.com/tiangolo/fastapi/pull/11809) by [@vkhoroshchak](https://github.com/vkhoroshchak). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md`. PR [#11804](https://github.com/tiangolo/fastapi/pull/11804) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#11786](https://github.com/tiangolo/fastapi/pull/11786) by [@logan2d5](https://github.com/logan2d5). From c8414b986ff07b1908dc1aa85395f1da558080ea Mon Sep 17 00:00:00 2001 From: Lucas Balieiro <37416577+lucasbalieiro@users.noreply.github.com> Date: Thu, 11 Jul 2024 22:41:15 -0400 Subject: [PATCH 577/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/general.md`=20(#11825)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/general.md | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/pt/docs/how-to/general.md diff --git a/docs/pt/docs/how-to/general.md b/docs/pt/docs/how-to/general.md new file mode 100644 index 000000000..4f21463b2 --- /dev/null +++ b/docs/pt/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Geral - Como Fazer - Receitas + +Aqui estão vários links para outros locais na documentação, para perguntas gerais ou frequentes + +## Filtro de dados- Segurança + +Para assegurar que você não vai retornar mais dados do que deveria, leia a seção [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank}. + +## Tags de Documentação - OpenAPI +Para adicionar tags às suas *rotas* e agrupá-las na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Resumo e Descrição da documentação - OpenAPI + +Para adicionar um resumo e uma descrição às suas *rotas* e exibi-los na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}. + +## Documentação das Descrições de Resposta - OpenAPI + +Para definir a descrição de uma resposta exibida na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}. + +## Documentação para Depreciar uma *Operação de Rota* - OpenAPI + +Para depreciar uma *operação de rota* e exibi-la na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}. + +## Converter qualquer dado para JSON + + +Para converter qualquer dado para um formato compatível com JSON, leia a seção [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +## OpenAPI Metadata - Docs + +Para adicionar metadados ao seu esquema OpenAPI, incluindo licensa, versão, contato, etc, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank}. + +## OpenAPI com URL customizada + +Para customizar a URL do OpenAPI (ou removê-la), leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## URLs de documentação do OpenAPI + +Para alterar as URLs usadas para as interfaces de usuário da documentação gerada automaticamente, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. From 18d28d4370656425fe780c8a8a46b713351584a2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 12 Jul 2024 02:41:39 +0000 Subject: [PATCH 578/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7c56ad1b2..0c5c9716e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/general.md`. PR [#11825](https://github.com/tiangolo/fastapi/pull/11825) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/async-tests.md`. PR [#11808](https://github.com/tiangolo/fastapi/pull/11808) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/first-steps.md`. PR [#11809](https://github.com/tiangolo/fastapi/pull/11809) by [@vkhoroshchak](https://github.com/vkhoroshchak). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md`. PR [#11804](https://github.com/tiangolo/fastapi/pull/11804) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 7782dd677b73e1f9b802ec1df9f6f7a284914451 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph09@gmail.com> Date: Thu, 11 Jul 2024 23:42:04 -0300 Subject: [PATCH 579/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/dependencies/global-depen?= =?UTF-8?q?dencies.md`=20(#11826)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/global-dependencies.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/pt/docs/tutorial/dependencies/global-dependencies.md diff --git a/docs/pt/docs/tutorial/dependencies/global-dependencies.md b/docs/pt/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..3eb5faa34 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,34 @@ +# Dependências Globais + +Para alguns tipos de aplicação específicos você pode querer adicionar dependências para toda a aplicação. + +De forma semelhante a [adicionar dependências (`dependencies`) em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, você pode adicioná-las à aplicação `FastAPI`. + +Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicação: + +=== "Python 3.9+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial012_an.py!} + ``` + +=== "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!} + ``` + +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. + +## Dependências para conjuntos de *operações de rota* + +Mais para a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você irá aprender a declarar um único parâmetro `dependencies` para um conjunto de *operações de rota*. From 2606671a0a83b1dc788ba4d2269a9d402f38e9ab Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 12 Jul 2024 02:43:47 +0000 Subject: [PATCH 580/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0c5c9716e..0805e3233 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/global-dependencies.md`. PR [#11826](https://github.com/tiangolo/fastapi/pull/11826) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/general.md`. PR [#11825](https://github.com/tiangolo/fastapi/pull/11825) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/async-tests.md`. PR [#11808](https://github.com/tiangolo/fastapi/pull/11808) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/first-steps.md`. PR [#11809](https://github.com/tiangolo/fastapi/pull/11809) by [@vkhoroshchak](https://github.com/vkhoroshchak). From 435c11a406b54288b95980809dcec0a52f2257ed Mon Sep 17 00:00:00 2001 From: Lucas Balieiro <37416577+lucasbalieiro@users.noreply.github.com> Date: Sat, 13 Jul 2024 21:24:05 -0400 Subject: [PATCH 581/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/reference/exceptions.md`=20(#11834?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/reference/exceptions.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 docs/pt/docs/reference/exceptions.md diff --git a/docs/pt/docs/reference/exceptions.md b/docs/pt/docs/reference/exceptions.md new file mode 100644 index 000000000..d6b5d2613 --- /dev/null +++ b/docs/pt/docs/reference/exceptions.md @@ -0,0 +1,20 @@ +# Exceções - `HTTPException` e `WebSocketException` + +Essas são as exceções que você pode lançar para mostrar erros ao cliente. + +Quando você lança uma exceção, como aconteceria com o Python normal, o restante da execução é abortado. Dessa forma, você pode lançar essas exceções de qualquer lugar do código para abortar uma solicitação e mostrar o erro ao cliente. + +Você pode usar: + +* `HTTPException` +* `WebSocketException` + +Essas exceções podem ser importadas diretamente do `fastapi`: + +```python +from fastapi import HTTPException, WebSocketException +``` + +::: fastapi.HTTPException + +::: fastapi.WebSocketException From 13712e2720212a4a19fd90c9f775e98af51efbc9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 01:24:27 +0000 Subject: [PATCH 582/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0805e3233..327ca6a69 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/reference/exceptions.md`. PR [#11834](https://github.com/tiangolo/fastapi/pull/11834) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/global-dependencies.md`. PR [#11826](https://github.com/tiangolo/fastapi/pull/11826) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/general.md`. PR [#11825](https://github.com/tiangolo/fastapi/pull/11825) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/async-tests.md`. PR [#11808](https://github.com/tiangolo/fastapi/pull/11808) by [@ceb10n](https://github.com/ceb10n). From f9ac185bf019a8e71b75d34752bb5bed9004cb02 Mon Sep 17 00:00:00 2001 From: Augustus D'Souza <augiwan@users.noreply.github.com> Date: Sun, 14 Jul 2024 07:16:19 +0530 Subject: [PATCH 583/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20links=20to?= =?UTF-8?q?=20alembic=20example=20repo=20in=20docs=20(#11628)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/tutorial/sql-databases.md | 2 +- docs/en/docs/tutorial/sql-databases.md | 2 +- docs/zh/docs/tutorial/sql-databases.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 4c8740984..5a5227352 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -501,7 +501,7 @@ current_user.items "🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>. +👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>. ### ✍ 🔗 diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 0b4d06b99..1f0ebc08b 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -513,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job). A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc. -You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic" class="external-link" target="_blank">the `alembic` directory in the source code</a>. +You can find an example of Alembic in a FastAPI project in the [Full Stack FastAPI Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic" class="external-link" target="_blank">the `alembic` directory in the source code</a>. ### Create a dependency diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index bd7c10571..8629b23fa 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -506,7 +506,7 @@ current_user.items “迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。 -您可以在[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/)。 +您可以在[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)。 ### 创建依赖项 From 475f0d015856f1ce39ccc0a7da2dc51cc8aee368 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 01:46:44 +0000 Subject: [PATCH 584/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 327ca6a69..6b4b36580 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev). * 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018). From 3960b45223e4f90428d379ffbab58db2bcfb5b8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B3=20Lino?= <nico.lino1991@gmail.com> Date: Sun, 14 Jul 2024 03:48:42 +0200 Subject: [PATCH 585/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20fastapi=20instr?= =?UTF-8?q?umentation=20external=20link=20(#11317)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index e3d475d2f..15f6169ee 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -27,7 +27,7 @@ Articles: - author: Nicoló Lino author_link: https://www.nlino.com link: https://github.com/softwarebloat/python-tracing-demo - title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo + title: Instrument FastAPI with OpenTelemetry tracing and visualize traces in Grafana Tempo. - author: Mikhail Rozhkov, Elena Samuylova author_link: https://www.linkedin.com/in/mnrozhkov/ link: https://www.evidentlyai.com/blog/fastapi-tutorial From 41e87c0ded0e6de9fb05e957725bc2a89eca1484 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 01:49:49 +0000 Subject: [PATCH 586/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6b4b36580..3477950c9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat). * ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev). From a3a6c61164522ffa3439f3ba3e022156107b934a Mon Sep 17 00:00:00 2001 From: DamianCzajkowski <43958031+DamianCzajkowski@users.noreply.github.com> Date: Sun, 14 Jul 2024 03:57:52 +0200 Subject: [PATCH 587/846] =?UTF-8?q?=F0=9F=93=9D=20=20Update=20docs=20with?= =?UTF-8?q?=20Ariadne=20reference=20from=20Starlette=20to=20FastAPI=20(#11?= =?UTF-8?q?797)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/graphql.md | 2 +- docs/em/docs/how-to/graphql.md | 2 +- docs/en/docs/how-to/graphql.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md index 9b03e8e05..b8e0bdddd 100644 --- a/docs/de/docs/how-to/graphql.md +++ b/docs/de/docs/how-to/graphql.md @@ -18,7 +18,7 @@ Hier sind einige der **GraphQL**-Bibliotheken, welche **ASGI** unterstützen. Di * <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> 🍓 * Mit <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">Dokumentation für FastAPI</a> * <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">Ariadne</a> - * Mit <a href="https://ariadnegraphql.org/docs/starlette-integration" class="external-link" target="_blank">Dokumentation für Starlette</a> (welche auch für FastAPI gilt) + * Mit <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">Dokumentation für FastAPI</a> * <a href="https://tartiflette.io/" class="external-link" target="_blank">Tartiflette</a> * Mit <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">Tartiflette ASGI</a>, für ASGI-Integration * <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a> diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 8509643ce..686a77949 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -18,7 +18,7 @@ * <a href="https://strawberry.rocks/" class="external-link" target="_blank">🍓</a> 👶 * ⏮️ <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">🩺 FastAPI</a> * <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">👸</a> - * ⏮️ <a href="https://ariadnegraphql.org/docs/starlette-integration" class="external-link" target="_blank">🩺 💃</a> (👈 ✔ FastAPI) + * ⏮️ <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">🩺 FastAPI</a> * <a href="https://tartiflette.io/" class="external-link" target="_blank">🍟</a> * ⏮️ <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">🍟 🔫</a> 🚚 🔫 🛠️ * <a href="https://graphene-python.org/" class="external-link" target="_blank">⚗</a> diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index 154606406..d5a5826f1 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -18,7 +18,7 @@ Here are some of the **GraphQL** libraries that have **ASGI** support. You could * <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> 🍓 * With <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">docs for FastAPI</a> * <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">Ariadne</a> - * With <a href="https://ariadnegraphql.org/docs/starlette-integration" class="external-link" target="_blank">docs for Starlette</a> (that also apply to FastAPI) + * With <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">docs for FastAPI</a> * <a href="https://tartiflette.io/" class="external-link" target="_blank">Tartiflette</a> * With <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">Tartiflette ASGI</a> to provide ASGI integration * <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a> From 9f49708fd89b7cbd89f83a2066b3bd8e965b12ac Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 01:58:15 +0000 Subject: [PATCH 588/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3477950c9..19d8d2981 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski). * 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat). * ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 511199014f55d769b600f0f816798b05ff4c7ccf Mon Sep 17 00:00:00 2001 From: Anita Hammer <166057949+anitahammer@users.noreply.github.com> Date: Sun, 14 Jul 2024 03:04:00 +0100 Subject: [PATCH 589/846] =?UTF-8?q?=F0=9F=8C=90=20Fix=20link=20in=20German?= =?UTF-8?q?=20translation=20(#11836)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Broken link on main page --- docs/de/docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index 9b8a73003..831d96e42 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -460,7 +460,7 @@ Wird von Starlette verwendet: * <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - erforderlich, wenn Sie den `TestClient` verwenden möchten. * <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - erforderlich, wenn Sie die Standardkonfiguration für Templates verwenden möchten. -* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - erforderlich, wenn Sie Formulare mittels `request.form()` <abbr title="Konvertieren des Strings, der aus einer HTTP-Anfrage stammt, nach Python-Daten">„parsen“</abbr> möchten. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - erforderlich, wenn Sie Formulare mittels `request.form()` <abbr title="Konvertieren des Strings, der aus einer HTTP-Anfrage stammt, nach Python-Daten">„parsen“</abbr> möchten. * <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - erforderlich für `SessionMiddleware` Unterstützung. * <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - erforderlich für Starlette's `SchemaGenerator` Unterstützung (Sie brauchen das wahrscheinlich nicht mit FastAPI). * <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - erforderlich, wenn Sie `UJSONResponse` verwenden möchten. From 36264cffb8039090050335626f3806a8fc1d9892 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 02:04:19 +0000 Subject: [PATCH 590/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 19d8d2981..e00a2d75b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer). * 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski). * 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat). * ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan). From 9edba691e7dff9985ec63cd802dc65bce04c9daa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 13 Jul 2024 21:14:00 -0500 Subject: [PATCH 591/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e00a2d75b..8589d35c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,19 +7,15 @@ hide: ## Latest Changes -* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan). - ### Upgrades -* 📝 Restored Swagger-UI links to use the latest version possible.. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster). +* 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster). ### Docs -* 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer). * 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski). * 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat). * ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan). -* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev). * 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018). * 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda). @@ -37,6 +33,9 @@ hide: ### Translations +* 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/exceptions.md`. PR [#11834](https://github.com/tiangolo/fastapi/pull/11834) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/global-dependencies.md`. PR [#11826](https://github.com/tiangolo/fastapi/pull/11826) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/general.md`. PR [#11825](https://github.com/tiangolo/fastapi/pull/11825) by [@lucasbalieiro](https://github.com/lucasbalieiro). From dfcc0322e4cd39bdcfd35d33a9e3dc3aef953b2d Mon Sep 17 00:00:00 2001 From: Lucas Balieiro <37416577+lucasbalieiro@users.noreply.github.com> Date: Sun, 14 Jul 2024 12:00:35 -0400 Subject: [PATCH 592/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/reference/index.md`=20(#11840)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/reference/index.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 docs/pt/docs/reference/index.md diff --git a/docs/pt/docs/reference/index.md b/docs/pt/docs/reference/index.md new file mode 100644 index 000000000..533a6a996 --- /dev/null +++ b/docs/pt/docs/reference/index.md @@ -0,0 +1,6 @@ +# Referência - API de Código + +Aqui está a referência ou API de código, as classes, funções, parâmetros, atributos e todas as partes do FastAPI que você pode usar em suas aplicações. + +Se você quer **aprender FastAPI**, é muito melhor ler o +[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/). From e23916d2f9b32eab9a5d658211a9bbe69de934be Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 16:00:56 +0000 Subject: [PATCH 593/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8589d35c4..22b5d2797 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/reference/index.md`. PR [#11840](https://github.com/tiangolo/fastapi/pull/11840) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan). From ebc6a0653ae6f9e1c023cca2fdb98c2086b4efb1 Mon Sep 17 00:00:00 2001 From: Maria Camila Gomez R <camigomez@experimentality.co> Date: Sun, 14 Jul 2024 11:22:03 -0500 Subject: [PATCH 594/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20`docs/es/docs/how-to/graphql.md`=20(#11697)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/how-to/graphql.md | 56 ++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 docs/es/docs/how-to/graphql.md diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md new file mode 100644 index 000000000..1138af76a --- /dev/null +++ b/docs/es/docs/how-to/graphql.md @@ -0,0 +1,56 @@ +# GraphQL + +Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar cualquier library **GraphQL** que sea compatible con ASGI. + +Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. + +!!! tip + **GraphQL** resuelve algunos casos de uso específicos. + + Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes. + + Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓 + +## Librerías GraphQL + +Aquí hay algunas de las libraries de **GraphQL** que tienen soporte con **ASGI** las cuales podrías usar con **FastAPI**: + +* <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> 🍓 + * Con <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">documentación para FastAPI</a> +* <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">Ariadne</a> + * Con <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">documentación para FastAPI</a> +* <a href="https://tartiflette.io/" class="external-link" target="_blank">Tartiflette</a> + * Con <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">Tartiflette ASGI</a> para proveer integración con ASGI +* <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a> + * Con <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a> + +## GraphQL con Strawberry + +Si necesitas o quieres trabajar con **GraphQL**, <a href="https://strawberry.rocks/" class="external-link" target="_blank">**Strawberry**</a> es la library **recomendada** por el diseño más cercano a **FastAPI**, el cual es completamente basado en **anotaciones de tipo**. + +Dependiendo de tus casos de uso, podrías preferir usar una library diferente, pero si me preguntas, probablemente te recomendaría **Strawberry**. + +Aquí hay una pequeña muestra de cómo podrías integrar Strawberry con FastAPI: + +```Python hl_lines="3 22 25-26" +{!../../../docs_src/graphql/tutorial001.py!} +``` + +Puedes aprender más sobre Strawberry en la <a href="https://strawberry.rocks/" class="external-link" target="_blank">documentación de Strawberry</a>. + +Y también en la documentación sobre <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">Strawberry con FastAPI</a>. + +## Clase obsoleta `GraphQLApp` en Starlette + +Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo con <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a>. + +Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** + +!!! tip + Si necesitas GraphQL, te recomendaría revisar <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. + +## Aprende más + +Puedes aprender más acerca de **GraphQL** en la <a href="https://graphql.org/" class="external-link" target="_blank">documentación oficial de GraphQL</a>. + +También puedes leer más acerca de cada library descrita anteriormente en sus enlaces. From ce5ecaa2a2f5e4717f4dbc93d976a13b59d7d157 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 16:22:25 +0000 Subject: [PATCH 595/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 22b5d2797..4bc454190 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add Spanish translation for `docs/es/docs/how-to/graphql.md`. PR [#11697](https://github.com/tiangolo/fastapi/pull/11697) by [@camigomezdev](https://github.com/camigomezdev). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/index.md`. PR [#11840](https://github.com/tiangolo/fastapi/pull/11840) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 60f7fe400618bdbd7660212d86ffe04504bf2096 Mon Sep 17 00:00:00 2001 From: kittydoor <me@kitty.sh> Date: Sun, 14 Jul 2024 19:06:59 +0200 Subject: [PATCH 596/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20Hypercorn=20lin?= =?UTF-8?q?ks=20in=20all=20the=20docs=20(#11744)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/bn/docs/index.md | 2 +- docs/de/docs/deployment/manually.md | 4 ++-- docs/de/docs/index.md | 2 +- docs/em/docs/deployment/manually.md | 4 ++-- docs/en/docs/deployment/manually.md | 4 ++-- docs/es/docs/index.md | 2 +- docs/fa/docs/index.md | 2 +- docs/fr/docs/deployment/manually.md | 4 ++-- docs/he/docs/index.md | 2 +- docs/it/docs/index.md | 2 +- docs/ja/docs/deployment/manually.md | 2 +- docs/ja/docs/index.md | 2 +- docs/ko/docs/index.md | 2 +- docs/pl/docs/index.md | 2 +- docs/pt/docs/deployment.md | 2 +- docs/pt/docs/index.md | 2 +- docs/ru/docs/deployment/manually.md | 4 ++-- docs/ru/docs/index.md | 2 +- docs/tr/docs/index.md | 2 +- docs/uk/docs/index.md | 2 +- docs/zh/docs/deployment/manually.md | 4 ++-- docs/zh/docs/index.md | 2 +- 22 files changed, 28 insertions(+), 28 deletions(-) diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index bbc3e9a3a..3105e69c8 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -126,7 +126,7 @@ $ pip install fastapi </div> -আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> অথবা <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> অথবা <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index c8e348aa1..ddc31dc5b 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -5,7 +5,7 @@ Das Wichtigste, was Sie zum Ausführen einer **FastAPI**-Anwendung auf einer ent Es gibt 3 Hauptalternativen: * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: ein hochperformanter ASGI-Server. -* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. +* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. * <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: Der für Django Channels entwickelte ASGI-Server. ## Servermaschine und Serverprogramm @@ -43,7 +43,7 @@ Sie können einen ASGI-kompatiblen Server installieren mit: === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. <div class="termy"> diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index 831d96e42..ccc50fd62 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -142,7 +142,7 @@ $ pip install fastapi </div> -Sie benötigen außerdem einen <abbr title="Asynchronous Server Gateway Interface – Asynchrone Server-Verbindungsschnittstelle">ASGI</abbr>-Server. Für die Produktumgebung beispielsweise <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oder <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +Sie benötigen außerdem einen <abbr title="Asynchronous Server Gateway Interface – Asynchrone Server-Verbindungsschnittstelle">ASGI</abbr>-Server. Für die Produktumgebung beispielsweise <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oder <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/em/docs/deployment/manually.md b/docs/em/docs/deployment/manually.md index f27b423e2..43cbc9409 100644 --- a/docs/em/docs/deployment/manually.md +++ b/docs/em/docs/deployment/manually.md @@ -5,7 +5,7 @@ 📤 3️⃣ 👑 🎛: * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: ↕ 🎭 🔫 💽. -* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣ & 🎻 👪 🎏 ⚒. +* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣ & 🎻 👪 🎏 ⚒. * <a href="https://github.com/django/daphne" class="external-link" target="_blank">👸</a>: 🔫 💽 🏗 ✳ 📻. ## 💽 🎰 & 💽 📋 @@ -43,7 +43,7 @@ === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. <div class="termy"> diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index 3baaa8253..51989d819 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -65,7 +65,7 @@ The main thing you need to run a **FastAPI** application (or any other ASGI appl There are several alternatives, including: * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: a high performance ASGI server. -* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: an ASGI server compatible with HTTP/2 and Trio among other features. +* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: an ASGI server compatible with HTTP/2 and Trio among other features. * <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: the ASGI server built for Django Channels. ## Server Machine and Server Program @@ -107,7 +107,7 @@ But you can also install an ASGI server manually: === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2. + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2. <div class="termy"> diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 631be7463..5153367dd 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -132,7 +132,7 @@ $ pip install fastapi </div> -También vas a necesitar un servidor ASGI para producción cómo <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> o <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +También vas a necesitar un servidor ASGI para producción cómo <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> o <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index 623bc0f75..dfbb8e647 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -134,7 +134,7 @@ $ pip install fastapi </div> -نصب یک سرور پروداکشن نظیر <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> یا <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a> نیز جزء نیازمندیهاست. +نصب یک سرور پروداکشن نظیر <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> یا <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a> نیز جزء نیازمندیهاست. <div class="termy"> diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index c53e2db67..eb1253cf8 100644 --- a/docs/fr/docs/deployment/manually.md +++ b/docs/fr/docs/deployment/manually.md @@ -5,7 +5,7 @@ La principale chose dont vous avez besoin pour exécuter une application **FastA Il existe 3 principales alternatives : * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> : un serveur ASGI haute performance. -* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a> : un serveur +* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a> : un serveur ASGI compatible avec HTTP/2 et Trio entre autres fonctionnalités. * <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a> : le serveur ASGI conçu pour Django Channels. @@ -46,7 +46,7 @@ Vous pouvez installer un serveur compatible ASGI avec : === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2. + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2. <div class="termy"> diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 621126128..626578e40 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -138,7 +138,7 @@ $ pip install fastapi </div> -תצטרכו גם שרת ASGI כגון <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> או <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +תצטרכו גם שרת ASGI כגון <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> או <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div dir="ltr" class="termy"> diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index c06d3a174..016316a64 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -129,7 +129,7 @@ $ pip install fastapi </div> -Per il rilascio in produzione, sarà necessario un server ASGI come <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oppure <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +Per il rilascio in produzione, sarà necessario un server ASGI come <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oppure <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index 67010a66f..449aea31e 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -25,7 +25,7 @@ === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。 + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。 <div class="termy"> diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index f95ac060f..2d4daac75 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -133,7 +133,7 @@ $ pip install fastapi </div> -本番環境では、<a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> または、 <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>のような、 ASGI サーバーが必要になります。 +本番環境では、<a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> または、 <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>のような、 ASGI サーバーが必要になります。 <div class="termy"> diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 4bc92c36c..21dd16f59 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -133,7 +133,7 @@ $ pip install fastapi </div> -프로덕션을 위해 <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 또는 <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>과 같은 ASGI 서버도 필요할 겁니다. +프로덕션을 위해 <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 또는 <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>과 같은 ASGI 서버도 필요할 겁니다. <div class="termy"> diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 4bd100f13..83bbe19cf 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -132,7 +132,7 @@ $ pip install fastapi </div> -Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> lub <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> lub <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md index 2272467fd..d25ea79fd 100644 --- a/docs/pt/docs/deployment.md +++ b/docs/pt/docs/deployment.md @@ -345,7 +345,7 @@ Você apenas precisa instalar um servidor ASGI compatível como: === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2. + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2. <div class="termy"> diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 223aeee46..6e7aa21f7 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -126,7 +126,7 @@ $ pip install fastapi </div> -Você também precisará de um servidor ASGI para produção, tal como <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> ou <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +Você também precisará de um servidor ASGI para produção, tal como <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> ou <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index a24580489..0b24c0695 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -5,7 +5,7 @@ Существует три наиболее распространённые альтернативы: * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: высокопроизводительный ASGI сервер. -* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. +* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. * <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: ASGI сервер, созданный для Django Channels. ## Сервер как машина и сервер как программа @@ -46,7 +46,7 @@ === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ASGI сервер, поддерживающий протокол HTTP/2. + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ASGI сервер, поддерживающий протокол HTTP/2. <div class="termy"> diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 03087448c..d59f45031 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -135,7 +135,7 @@ $ pip install fastapi </div> -Вам также понадобится сервер ASGI для производства, такой как <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> или <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +Вам также понадобится сервер ASGI для производства, такой как <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> или <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 4b9c0705d..f7a8cf2a5 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -141,7 +141,7 @@ $ pip install fastapi </div> -Uygulamamızı kullanılabilir hale getirmek için <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> ya da <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a> gibi bir ASGI sunucusuna ihtiyacımız olacak. +Uygulamamızı kullanılabilir hale getirmek için <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> ya da <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a> gibi bir ASGI sunucusuna ihtiyacımız olacak. <div class="termy"> diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index e32389772..29e19025a 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -127,7 +127,7 @@ $ pip install fastapi </div> -Вам також знадобиться сервер ASGI для продакшину, наприклад <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> або <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. +Вам також знадобиться сервер ASGI для продакшину, наприклад <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> або <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. <div class="termy"> diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md index 15588043f..ca7142613 100644 --- a/docs/zh/docs/deployment/manually.md +++ b/docs/zh/docs/deployment/manually.md @@ -5,7 +5,7 @@ 有 3 个主要可选方案: * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>:高性能 ASGI 服务器。 -* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 +* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 * <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>:为 Django Channels 构建的 ASGI 服务器。 ## 服务器主机和服务器程序 @@ -44,7 +44,7 @@ === "Hypercorn" - * <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>,一个也与 HTTP/2 兼容的 ASGI 服务器。 + * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>,一个也与 HTTP/2 兼容的 ASGI 服务器。 <div class="termy"> diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index aef3b3a50..f03a0dd13 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -138,7 +138,7 @@ $ pip install fastapi </div> -你还会需要一个 ASGI 服务器,生产环境可以使用 <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 或者 <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>。 +你还会需要一个 ASGI 服务器,生产环境可以使用 <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 或者 <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>。 <div class="termy"> From 3a8f6cd1a2fc5a30c853c10b6bb411b62c84e3ee Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 17:07:22 +0000 Subject: [PATCH 597/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4bc454190..b445e11d6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Update Hypercorn links in all the docs. PR [#11744](https://github.com/tiangolo/fastapi/pull/11744) by [@kittydoor](https://github.com/kittydoor). * 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski). * 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat). * ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan). From 9d74b23670ae7b7fa4ccb5d6cbfea7373ff12dd7 Mon Sep 17 00:00:00 2001 From: gitworkflows <118260833+gitworkflows@users.noreply.github.com> Date: Sun, 14 Jul 2024 23:10:43 +0600 Subject: [PATCH 598/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Simplify=20interna?= =?UTF-8?q?l=20docs=20script=20(#11777)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/mkdocs_hooks.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 8335a13f6..24ffecf46 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -39,7 +39,7 @@ def on_config(config: MkDocsConfig, **kwargs: Any) -> MkDocsConfig: lang = dir_path.parent.name if lang in available_langs: config.theme["language"] = lang - if not (config.site_url or "").endswith(f"{lang}/") and not lang == "en": + if not (config.site_url or "").endswith(f"{lang}/") and lang != "en": config.site_url = f"{config.site_url}{lang}/" return config From fb15c48556a44b8bb8cf9dd55000b95813f20bc7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 17:11:03 +0000 Subject: [PATCH 599/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b445e11d6..3dac89d7b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -81,6 +81,7 @@ hide: ### Internal +* ♻️ Simplify internal docs script. PR [#11777](https://github.com/tiangolo/fastapi/pull/11777) by [@gitworkflows](https://github.com/gitworkflows). * 🔧 Update sponsors: add Fine. PR [#11784](https://github.com/tiangolo/fastapi/pull/11784) by [@tiangolo](https://github.com/tiangolo). * 🔧 Tweak sponsors: Kong URL. PR [#11765](https://github.com/tiangolo/fastapi/pull/11765) by [@tiangolo](https://github.com/tiangolo). * 🔧 Tweak sponsors: Kong URL. PR [#11764](https://github.com/tiangolo/fastapi/pull/11764) by [@tiangolo](https://github.com/tiangolo). From 0b1e2ec2a6109fc6db8f8fd216d4843930d4d62a Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 14 Jul 2024 12:27:40 -0500 Subject: [PATCH 600/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Rewording=20in=20`?= =?UTF-8?q?docs/en/docs/fastapi-cli.md`=20(#11716)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Andres Pineda <1900897+ajpinedam@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/en/docs/fastapi-cli.md | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md index f5b0a6448..a6facde3a 100644 --- a/docs/en/docs/fastapi-cli.md +++ b/docs/en/docs/fastapi-cli.md @@ -54,9 +54,9 @@ $ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:singl </div> -That command line program called `fastapi` is **FastAPI CLI**. +The command line program called `fastapi` is **FastAPI CLI**. -FastAPI CLI takes the path to your Python program and automatically detects the variable with the FastAPI (commonly named `app`) and how to import it, and then serves it. +FastAPI CLI takes the path to your Python program (e.g. `main.py`) and automatically detects the `FastAPI` instance (commonly named `app`), determines the correct import process, and then serves it. For production you would use `fastapi run` instead. 🚀 @@ -64,19 +64,15 @@ Internally, **FastAPI CLI** uses <a href="https://www.uvicorn.org" class="extern ## `fastapi dev` -When you run `fastapi dev`, it will run on development mode. +Running `fastapi dev` initiates development mode. -By default, it will have **auto-reload** enabled, so it will automatically reload the server when you make changes to your code. This is resource intensive and could be less stable than without it, you should only use it for development. - -By default it will listen on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`). +By default, **auto-reload** is enabled, automatically reloading the server when you make changes to your code. This is resource-intensive and could be less stable than when it's disabled. You should only use it for development. It also listens on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`). ## `fastapi run` -When you run `fastapi run`, it will run on production mode by default. - -It will have **auto-reload disabled** by default. +Executing `fastapi run` starts FastAPI in production mode by default. -It will listen on the IP address `0.0.0.0`, which means all the available IP addresses, this way it will be publicly accessible to anyone that can communicate with the machine. This is how you would normally run it in production, for example, in a container. +By default, **auto-reload** is disabled. It also listens on the IP address `0.0.0.0`, which means all the available IP addresses, this way it will be publicly accessible to anyone that can communicate with the machine. This is how you would normally run it in production, for example, in a container. In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. From 7a9396c839bae676d32a97b46c39abef5b7c0ca5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 17:28:03 +0000 Subject: [PATCH 601/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3dac89d7b..192596210 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* ✏️ Rewording in `docs/en/docs/fastapi-cli.md`. PR [#11716](https://github.com/tiangolo/fastapi/pull/11716) by [@alejsdev](https://github.com/alejsdev). * 📝 Update Hypercorn links in all the docs. PR [#11744](https://github.com/tiangolo/fastapi/pull/11744) by [@kittydoor](https://github.com/kittydoor). * 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski). * 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat). From 4d3ef06029fec473b2b185da55f6d355d052e1ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 14 Jul 2024 12:46:40 -0500 Subject: [PATCH 602/846] =?UTF-8?q?=E2=9E=96=20Remove=20orjson=20and=20ujs?= =?UTF-8?q?on=20from=20default=20dependencies=20(#11842)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++++-- docs/en/docs/advanced/custom-response.md | 8 +++++++- docs/en/docs/index.md | 7 +++++-- pyproject.toml | 4 ---- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index ea722d57a..e344f97ad 100644 --- a/README.md +++ b/README.md @@ -468,12 +468,15 @@ Used by Starlette: Used by FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. -* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. * `fastapi-cli` - to provide the `fastapi` command. When you install `fastapi` it comes these standard dependencies. +Additional optional dependencies: + +* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. + ## `fastapi-slim` If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 45c7c7bd5..1d12173a1 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -39,7 +39,7 @@ But if you are certain that the content that you are returning is **serializable And it will be documented as such in OpenAPI. !!! tip - The `ORJSONResponse` is currently only available in FastAPI, not in Starlette. + The `ORJSONResponse` is only available in FastAPI, not in Starlette. ## HTML Response @@ -149,10 +149,16 @@ This is the default response used in **FastAPI**, as you read above. A fast alternative JSON response using <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>, as you read above. +!!! info + This requires installing `orjson` for example with `pip install orjson`. + ### `UJSONResponse` An alternative JSON response using <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>. +!!! info + This requires installing `ujson` for example with `pip install ujson`. + !!! warning `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 434c70893..8b54f175f 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -466,12 +466,15 @@ Used by Starlette: Used by FastAPI / Starlette: * <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. -* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. * `fastapi-cli` - to provide the `fastapi` command. When you install `fastapi` it comes these standard dependencies. +Additional optional dependencies: + +* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. + ## `fastapi-slim` If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. diff --git a/pyproject.toml b/pyproject.toml index a79845646..dbaa42149 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,10 +61,6 @@ standard = [ "jinja2 >=2.11.2", # For forms and file uploads "python-multipart >=0.0.7", - # For UJSONResponse - "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", - # For ORJSONResponse - "orjson >=3.2.1", # To validate email fields "email_validator >=2.0.0", # Uvicorn with uvloop From 0f22c76d7d27790803c036ef66124c68e1b44dd3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 14 Jul 2024 17:47:04 +0000 Subject: [PATCH 603/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 192596210..6a08a1e5d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Upgrades +* ➖ Remove orjson and ujson from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo). * 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster). ### Docs From 38db0a585870e14b7561c8ac420f2ede3564e995 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 14 Jul 2024 12:53:37 -0500 Subject: [PATCH 604/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6a08a1e5d..f9dc1d71d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,7 +9,8 @@ hide: ### Upgrades -* ➖ Remove orjson and ujson from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo). +* ➖ Remove `orjson` and `ujson` from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo). + * These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they not included in `pip install fastapi`. * 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster). ### Docs From b1993642461031bac9d21dd87e7faf59f19049f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 14 Jul 2024 12:54:20 -0500 Subject: [PATCH 605/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?1.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f9dc1d71d..3734f3482 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.111.1 + ### Upgrades * ➖ Remove `orjson` and `ujson` from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 04305ad8b..4d60bc7de 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.111.0" +__version__ = "0.111.1" from starlette import status as status From 4c0c05c9446d23b67fc22cc715bc62908173bd43 Mon Sep 17 00:00:00 2001 From: Lucas Balieiro <37416577+lucasbalieiro@users.noreply.github.com> Date: Mon, 15 Jul 2024 14:46:51 -0400 Subject: [PATCH 606/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/reference/apirouter.md`=20(#11843)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/reference/apirouter.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 docs/pt/docs/reference/apirouter.md diff --git a/docs/pt/docs/reference/apirouter.md b/docs/pt/docs/reference/apirouter.md new file mode 100644 index 000000000..7568601c9 --- /dev/null +++ b/docs/pt/docs/reference/apirouter.md @@ -0,0 +1,24 @@ +# Classe `APIRouter` + +Aqui está a informação de referência para a classe `APIRouter`, com todos os seus parâmetros, atributos e métodos. + +Você pode importar a classe `APIRouter` diretamente do `fastapi`: + +```python +from fastapi import APIRouter +``` + +::: fastapi.APIRouter + options: + members: + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event From 67ed86cb7f788516c2dc1e0b7d800e4ae8a531d6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 15 Jul 2024 18:47:15 +0000 Subject: [PATCH 607/846] =?UTF-8?q?=F0=9F=93=9D=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 3734f3482..83c7ad188 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/reference/apirouter.md`. PR [#11843](https://github.com/tiangolo/fastapi/pull/11843) by [@lucasbalieiro](https://github.com/lucasbalieiro). + ## 0.111.1 ### Upgrades From 7bbddf012c2f5dc3781d9331ee9fec9f718efa94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 16 Jul 2024 21:12:29 -0500 Subject: [PATCH 608/846] =?UTF-8?q?=F0=9F=94=A8=20Update=20docs=20Termynal?= =?UTF-8?q?=20scripts=20to=20not=20include=20line=20nums=20for=20local=20d?= =?UTF-8?q?ev=20(#11854)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/css/custom.css | 4 ++++ docs/en/docs/js/custom.js | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/css/custom.css b/docs/en/docs/css/custom.css index 386aa9d7e..b192f6123 100644 --- a/docs/en/docs/css/custom.css +++ b/docs/en/docs/css/custom.css @@ -13,6 +13,10 @@ white-space: pre-wrap; } +.termy .linenos { + display: none; +} + a.external-link { /* For right to left languages */ direction: ltr; diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js index 8e3be4c13..0008db49e 100644 --- a/docs/en/docs/js/custom.js +++ b/docs/en/docs/js/custom.js @@ -35,7 +35,7 @@ function setupTermynal() { function createTermynals() { document - .querySelectorAll(`.${termynalActivateClass} .highlight`) + .querySelectorAll(`.${termynalActivateClass} .highlight code`) .forEach(node => { const text = node.textContent; const lines = text.split("\n"); From 84f04cc8a048bd7cead9c1acff53d4479889c9c1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 17 Jul 2024 02:13:04 +0000 Subject: [PATCH 609/846] =?UTF-8?q?=F0=9F=93=9D=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 83c7ad188..405a7922c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/reference/apirouter.md`. PR [#11843](https://github.com/tiangolo/fastapi/pull/11843) by [@lucasbalieiro](https://github.com/lucasbalieiro). +### Internal + +* 🔨 Update docs Termynal scripts to not include line nums for local dev. PR [#11854](https://github.com/tiangolo/fastapi/pull/11854) by [@tiangolo](https://github.com/tiangolo). + ## 0.111.1 ### Upgrades From 9230978aae7513a31b9e6e772bf4397f519c81b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 17 Jul 2024 17:36:02 -0500 Subject: [PATCH 610/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20rem?= =?UTF-8?q?ove=20TalkPython=20(#11861)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- 2 files changed, 4 deletions(-) diff --git a/README.md b/README.md index e344f97ad..48ab9d1a5 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,6 @@ The key features are: <a href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> <a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a> <a href="https://fine.dev?ref=fastapibadge" target="_blank" title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"><img src="https://fastapi.tiangolo.com/img/sponsors/fine.png"></a> -<a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> <a href="https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship" target="_blank" title="SDKs for your API | Speakeasy"><img src="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index d6dfd5d0e..9b6539adf 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -36,9 +36,6 @@ gold: title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" img: https://fastapi.tiangolo.com/img/sponsors/fine.png silver: - - url: https://training.talkpython.fm/fastapi-courses - title: FastAPI video courses on demand from people you trust - img: https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks img: https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg From 15130a3eb5080d8d457752a502167ddd44d79156 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 17 Jul 2024 22:37:18 +0000 Subject: [PATCH 611/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 405a7922c..9ec295be5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* 🔧 Update sponsors: remove TalkPython. PR [#11861](https://github.com/tiangolo/fastapi/pull/11861) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs Termynal scripts to not include line nums for local dev. PR [#11854](https://github.com/tiangolo/fastapi/pull/11854) by [@tiangolo](https://github.com/tiangolo). ## 0.111.1 From a5fbbeeb61d8b197a7a52f4d3536d2ef508d231c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph09@gmail.com> Date: Thu, 18 Jul 2024 17:13:18 -0300 Subject: [PATCH 612/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/dependencies/dependencies?= =?UTF-8?q?-with-yield.md`=20(#11848)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-with-yield.md | 349 ++++++++++++++++++ 1 file changed, 349 insertions(+) create mode 100644 docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..8b4175fc5 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,349 @@ +# Dependências com yield + +O FastAPI possui suporte para dependências que realizam <abbr title='também chamados de "código de saída", "código de cleanup", "código de teardown", "código de finalização", "código de saída para gerenciador de contextos", etc.'>alguns passos extras ao finalizar</abbr>. + +Para fazer isso, utilize `yield` em vez de `return`, e escreva os passos extras (código) depois. + +!!! tip "Dica" + Garanta que `yield` é utilizado apenas uma vez. + +!!! note "Detalhes Técnicos" + Qualquer função que possa ser utilizada com: + + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + + pode ser utilizada como uma dependência do **FastAPI**. + + Na realidade, o FastAPI utiliza esses dois decoradores internamente. + +## Uma dependência de banco de dados com `yield` + +Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dados, e fechá-la após terminar sua operação. + +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!} +``` + +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!} +``` + +O código após o `yield` é executado após a resposta ser entregue: + +```Python hl_lines="5-6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! tip "Dica" + Você pode usar funções assíncronas (`async`) ou funções comuns. + + O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns. + +## Uma dependência com `yield` e `try` + +Se você utilizar um bloco `try` em uma dependência com `yield`, você irá capturar qualquer exceção que for lançada enquanto a dependência é utilizada. + +Por exemplo, se algum código em um certo momento no meio da operação, em outra dependência ou em uma *operação de rota*, fizer um "rollback" de uma transação de banco de dados ou causar qualquer outro erro, você irá capturar a exceção em sua dependência. + +Então, você pode procurar por essa exceção específica dentro da dependência com `except AlgumaExcecao`. + +Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções. + +```python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +## Subdependências com `yield` + +Você pode ter subdependências e "árvores" de subdependências de qualquer tamanho e forma, e qualquer uma ou todas elas podem utilizar `yield`. + +O **FastAPI** garantirá que o "código de saída" em cada dependência com `yield` é executado na ordem correta. + +Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` depender de `dependency_a`: + +=== "python 3.9+" + + ```python hl_lines="6 14 22" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "python 3.8+" + + ```python hl_lines="5 13 21" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "python 3.8+ non-annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```python hl_lines="4 12 20" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +E todas elas podem utilizar `yield`. + +Neste caso, `dependency_c` precisa que o valor de `dependency_b` (nomeada de `dep_b` aqui) continue disponível para executar seu código de saída. + +E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada de `dep_a`) continue disponível para executar seu código de saída. + +=== "python 3.9+" + + ```python hl_lines="18-19 26-27" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "python 3.8+" + + ```python hl_lines="17-18 25-26" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "python 3.8+ non-annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```python hl_lines="16-17 24-25" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +Da mesma forma, você pode ter algumas dependências com `yield` e outras com `return` e ter uma relação de dependência entre algumas dos dois tipos. + +E você poderia ter uma única dependência que precisa de diversas outras dependências com `yield`, etc. + +Você pode ter qualquer combinação de dependências que você quiser. + +O **FastAPI** se encarrega de executá-las na ordem certa. + +!!! note "Detalhes Técnicos" + Tudo isso funciona graças aos <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">gerenciadores de contexto</a> do Python. + + O **FastAPI** utiliza eles internamente para alcançar isso. + +## Dependências com `yield` e `httpexception` + +Você viu que dependências podem ser utilizadas com `yield` e podem incluir blocos `try` para capturar exceções. + +Da mesma forma, você pode lançar uma `httpexception` ou algo parecido no código de saída, após o `yield` + +!!! tip "Dica" + + Essa é uma técnica relativamente avançada, e na maioria dos casos você não precisa dela totalmente, já que você pode lançar exceções (incluindo `httpexception`) dentro do resto do código da sua aplicação, por exemplo, em uma *função de operação de rota*. + + Mas ela existe para ser utilizada caso você precise. 🤓 + +=== "python 3.9+" + + ```python hl_lines="18-22 31" + {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} + ``` + +=== "python 3.8+" + + ```python hl_lines="17-21 30" + {!> ../../../docs_src/dependencies/tutorial008b_an.py!} + ``` + +=== "python 3.8+ non-annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```python hl_lines="16-20 29" + {!> ../../../docs_src/dependencies/tutorial008b.py!} + ``` + +Uma alternativa que você pode utilizar para capturar exceções (e possivelmente lançar outra HTTPException) é criar um [Manipulador de Exceções Customizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. + +## Dependências com `yield` e `except` + +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: + +=== "Python 3.9+" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14-15" + {!> ../../../docs_src/dependencies/tutorial008c_an.py!} + ``` + +=== "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!} + ``` + +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. 😱 + +### Sempre levante (`raise`) exceções em Dependências com `yield` e `except` + +Se você capturar uma exceção em uma dependência com `yield`, a menos que você esteja levantando outra `HTTPException` ou coisa parecida, você deveria relançar a exceção original. + +Você pode relançar a mesma exceção utilizando `raise`: + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial008d_an.py!} + ``` + +=== "python 3.8+ non-annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial008d.py!} + ``` + +Agora o cliente irá receber a mesma resposta *HTTP 500 Internal Server Error*, mas o servidor terá nosso `InternalError` personalizado nos logs. 😎 + +## Execução de dependências com `yield` + +A sequência de execução é mais ou menos como esse diagrama. O tempo passa do topo para baixo. E cada coluna é uma das partes interagindo ou executando código. + +```mermaid +sequenceDiagram + +participant client as Cliente +participant handler as Manipulador de exceções +participant dep as Dep com yield +participant operation as Operação de Rota +participant tasks as Tarefas de Background + + Note over client,operation: pode lançar exceções, incluindo HTTPException + client ->> dep: Iniciar requisição + Note over dep: Executar código até o yield + opt lançar Exceção + dep -->> handler: lançar Exceção + handler -->> client: resposta de erro HTTP + end + dep ->> operation: Executar dependência, e.g. sessão de BD + opt raise + operation -->> dep: Lançar exceção (e.g. HTTPException) + opt handle + dep -->> dep: Pode capturar exceções, lançar uma nova HTTPException, lançar outras exceções + end + handler -->> client: resposta de erro HTTP + end + + operation ->> client: Retornar resposta ao cliente + Note over client,operation: Resposta já foi enviada, e não pode ser modificada + opt Tarefas + operation -->> tasks: Enviar tarefas de background + end + opt Lançar outra exceção + tasks -->> tasks: Manipula exceções no código da tarefa de background + end +``` + +!!! info "Informação" + Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*. + + Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada + +!!! tip "Dica" + Esse diagrama mostra `HttpException`, mas você pode levantar qualquer outra exceção que você capture em uma dependência com `yield` ou um [Manipulador de exceções personalizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. + + Se você lançar qualquer exceção, ela será passada para as dependências com yield, inlcuindo a `HTTPException`. Na maioria dos casos você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente. + +## Dependências com `yield`, `HTTPException`, `except` e Tarefas de Background + +!!! warning "Aviso" + Você provavelmente não precisa desses detalhes técnicos, você pode pular essa seção e continuar na próxima seção abaixo. + + Esses detalhes são úteis principalmente se você estiver usando uma versão do FastAPI anterior à 0.106.0 e utilizando recursos de dependências com `yield` em tarefas de background. + +### Dependências com `yield` e `except`, Detalhes Técnicos + +Antes do FastAPI 0.110.0, se você utilizasse uma dependência com `yield`, e então capturasse uma dependência com `except` nessa dependência, caso a exceção não fosse relançada, ela era automaticamente lançada para qualquer manipulador de exceções ou o manipulador de erros interno do servidor. + +Isso foi modificado na versão 0.110.0 para consertar o consumo de memória não controlado das exceções relançadas automaticamente sem um manipulador (erros internos do servidor), e para manter o comportamento consistente com o código Python tradicional. + +### Tarefas de Background e Dependências com `yield`, Detalhes Técnicos + +Antes do FastAPI 0.106.0, levantar exceções após um `yield` não era possível, o código de saída nas dependências com `yield` era executado *após* a resposta ser enviada, então os [Manipuladores de Exceções](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank} já teriam executado. + +Isso foi implementado dessa forma principalmente para permitir que os mesmos objetos fornecidos ("yielded") pelas dependências dentro de tarefas de background fossem reutilizados, por que o código de saída era executado antes das tarefas de background serem finalizadas. + +Ainda assim, como isso exigiria esperar que a resposta navegasse pela rede enquanto mantia ativo um recurso desnecessário na dependência com yield (por exemplo, uma conexão com banco de dados), isso mudou na versão 0.106.0 do FastAPI. + +!!! tip "Dica" + + Adicionalmente, uma tarefa de background é, normalmente, um conjunto de lógicas independentes que devem ser manipuladas separadamente, com seus próprios recursos (e.g. sua própria conexão com banco de dados). + + Então, dessa forma você provavelmente terá um código mais limpo. + +Se você costumava depender desse comportamento, agora você precisa criar os recursos para uma tarefa de background dentro dela mesma, e usar internamente apenas dados que não dependam de recursos de dependências com `yield`. + +Por exemplo, em vez de utilizar a mesma sessão do banco de dados, você criaria uma nova sessão dentro da tarefa de background, e você obteria os objetos do banco de dados utilizando essa nova sessão. E então, em vez de passar o objeto obtido do banco de dados como um parâmetro para a função da tarefa de background, você passaria o ID desse objeto e buscaria ele novamente dentro da função da tarefa de background. + +## Gerenciadores de contexto + +### O que são gerenciadores de contexto + +"Gerenciadores de Contexto" são qualquer um dos objetos Python que podem ser utilizados com a declaração `with`. + +Por exemplo, <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" class="external-link" target="_blank">você pode utilizar `with` para ler um arquivo</a>: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Por baixo dos panos, o código `open("./somefile.txt")` cria um objeto que é chamado de "Gerenciador de Contexto". + +Quando o bloco `with` finaliza, ele se certifica de fechar o arquivo, mesmo que tenha ocorrido alguma exceção. + +Quando você cria uma dependência com `yield`, o **FastAPI** irá criar um gerenciador de contexto internamente para ela, e combiná-lo com algumas outras ferramentas relacionadas. + +### Utilizando gerenciadores de contexto em dependências com `yield` + +!!! warning "Aviso" + Isso é uma ideia mais ou menos "avançada". + + Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto. + +Em python, você pode criar Gerenciadores de Contexto ao <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank"> criar uma classe com dois métodos: `__enter__()` e `__exit__()`</a>. + +Você também pode usá-los dentro de dependências com `yield` do **FastAPI** ao utilizar `with` ou `async with` dentro da função da dependência: + +```Python hl_lines="1-9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip "Dica" + Outra forma de criar um gerenciador de contexto é utilizando: + + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou + + * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + + Para decorar uma função com um único `yield`. + + Isso é o que o **FastAPI** usa internamente para dependências com `yield`. + + Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria). + + O FastAPI irá fazer isso para você internamente. From 4592223c869f0d092b7270593ff3d32113539b14 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Jul 2024 20:13:42 +0000 Subject: [PATCH 613/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9ec295be5..31654d0ba 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/dependencies/dependencies-with-yield.md`. PR [#11848](https://github.com/tiangolo/fastapi/pull/11848) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/apirouter.md`. PR [#11843](https://github.com/tiangolo/fastapi/pull/11843) by [@lucasbalieiro](https://github.com/lucasbalieiro). ### Internal From 3898fa88f29a52a57889cf6134fb3d955ee6c1b2 Mon Sep 17 00:00:00 2001 From: Lucas Balieiro <37416577+lucasbalieiro@users.noreply.github.com> Date: Thu, 18 Jul 2024 16:15:21 -0400 Subject: [PATCH 614/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/reference/background.md`=20(#11849?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/reference/background.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 docs/pt/docs/reference/background.md diff --git a/docs/pt/docs/reference/background.md b/docs/pt/docs/reference/background.md new file mode 100644 index 000000000..bfc15aa76 --- /dev/null +++ b/docs/pt/docs/reference/background.md @@ -0,0 +1,11 @@ +# Tarefas em Segundo Plano - `BackgroundTasks` + +Você pode declarar um parâmetro em uma *função de operação de rota* ou em uma função de dependência com o tipo `BackgroundTasks`, e então utilizá-lo para agendar a execução de tarefas em segundo plano após o envio da resposta. + +Você pode importá-lo diretamente do `fastapi`: + +```python +from fastapi import BackgroundTasks +``` + +::: fastapi.BackgroundTasks From cd6e9db0653eabbf0fb14908c73939a11a131058 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 18 Jul 2024 20:18:17 +0000 Subject: [PATCH 615/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 31654d0ba..f32bff241 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/reference/background.md`. PR [#11849](https://github.com/tiangolo/fastapi/pull/11849) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#11848](https://github.com/tiangolo/fastapi/pull/11848) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/apirouter.md`. PR [#11843](https://github.com/tiangolo/fastapi/pull/11843) by [@lucasbalieiro](https://github.com/lucasbalieiro). From b80a2590f807a9261a1863bf194e3d94a4e583ce Mon Sep 17 00:00:00 2001 From: Nolan Di Mare Sullivan <nolan.dm.sullivan@gmail.com> Date: Mon, 22 Jul 2024 21:37:30 +0100 Subject: [PATCH 616/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20Speakeasy=20URL?= =?UTF-8?q?=20(#11871)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- README.md | 2 +- docs/de/docs/advanced/generate-clients.md | 2 +- docs/en/data/sponsors.yml | 2 +- docs/en/docs/advanced/generate-clients.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 48ab9d1a5..2bcccbe3b 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ The key features are: <a href="https://fine.dev?ref=fastapibadge" target="_blank" title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"><img src="https://fastapi.tiangolo.com/img/sponsors/fine.png"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> -<a href="https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship" target="_blank" title="SDKs for your API | Speakeasy"><img src="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a> +<a href="https://speakeasy.com?utm_source=fastapi+repo&utm_medium=github+sponsorship" target="_blank" title="SDKs for your API | Speakeasy"><img src="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a> <a href="https://www.svix.com/" target="_blank" title="Svix - Webhooks as a service"><img src="https://fastapi.tiangolo.com/img/sponsors/svix.svg"></a> <a href="https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers" target="_blank" title="Take code reviews from hours to minutes"><img src="https://fastapi.tiangolo.com/img/sponsors/codacy.png"></a> <a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" target="_blank" title="Stainless | Generate best-in-class SDKs"><img src="https://fastapi.tiangolo.com/img/sponsors/stainless.png"></a> diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index 7d1d69353..d69437954 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -20,7 +20,7 @@ Einige von diesen ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponse Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 -Beispielsweise könnten Sie <a href="https://speakeasyapi.dev/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> ausprobieren. +Beispielsweise könnten Sie <a href="https://speakeasy.com/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> ausprobieren. Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und die Sie online suchen und finden können. 🤓 diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 9b6539adf..7fad270da 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -42,7 +42,7 @@ silver: - url: https://databento.com/ title: Pay as you go for market data img: https://fastapi.tiangolo.com/img/sponsors/databento.svg - - url: https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship + - url: https://speakeasy.com?utm_source=fastapi+repo&utm_medium=github+sponsorship title: SDKs for your API | Speakeasy img: https://fastapi.tiangolo.com/img/sponsors/speakeasy.png - url: https://www.svix.com/ diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 09d00913f..136ddb064 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -20,7 +20,7 @@ Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-autho And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 -For example, you might want to try <a href="https://speakeasyapi.dev/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> and <a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" class="external-link" target="_blank">Stainless</a>. +For example, you might want to try <a href="https://speakeasy.com/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> and <a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" class="external-link" target="_blank">Stainless</a>. There are also several other companies offering similar services that you can search and find online. 🤓 From 360f4966a6ca96c95f2e504f5841e0b895f2a9d6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 22 Jul 2024 20:37:50 +0000 Subject: [PATCH 617/846] =?UTF-8?q?=F0=9F=93=9D=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 f32bff241..7872e2fbe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update Speakeasy URL. PR [#11871](https://github.com/tiangolo/fastapi/pull/11871) by [@ndimares](https://github.com/ndimares). + ### Translations * 🌐 Add Portuguese translation for `docs/pt/docs/reference/background.md`. PR [#11849](https://github.com/tiangolo/fastapi/pull/11849) by [@lucasbalieiro](https://github.com/lucasbalieiro). From 480f9285997bca3e65793a4a8af178393420c3d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 23 Jul 2024 14:36:22 -0500 Subject: [PATCH 618/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20rem?= =?UTF-8?q?ove=20Reflex=20(#11875)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- docs/en/overrides/main.html | 6 ------ 3 files changed, 10 deletions(-) diff --git a/README.md b/README.md index 2bcccbe3b..c0422ead8 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,6 @@ The key features are: <a href="https://platform.sh/try-it-now/?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" target="_blank" title="Build, run and scale your apps on a modern, reliable, and secure PaaS."><img src="https://fastapi.tiangolo.com/img/sponsors/platform-sh.png"></a> <a href="https://www.porter.run" target="_blank" title="Deploy FastAPI on AWS with a few clicks"><img src="https://fastapi.tiangolo.com/img/sponsors/porter.png"></a> <a href="https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor" target="_blank" title="Automate FastAPI documentation generation with Bump.sh"><img src="https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg"></a> -<a href="https://reflex.dev" target="_blank" title="Reflex"><img src="https://fastapi.tiangolo.com/img/sponsors/reflex.png"></a> <a href="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge" target="_blank" title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files"><img src="https://fastapi.tiangolo.com/img/sponsors/scalar.svg"></a> <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> <a href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 7fad270da..39654a361 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -11,9 +11,6 @@ gold: - url: https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor title: Automate FastAPI documentation generation with Bump.sh img: https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg - - url: https://reflex.dev - title: Reflex - img: https://fastapi.tiangolo.com/img/sponsors/reflex.png - url: https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge title: "Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files" img: https://fastapi.tiangolo.com/img/sponsors/scalar.svg diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index ae8ea5667..d647a8df4 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -46,12 +46,6 @@ <img class="sponsor-image" src="/img/sponsors/bump-sh-banner.svg" /> </a> </div> - <div class="item"> - <a title="Reflex" style="display: block; position: relative;" href="https://reflex.dev" target="_blank"> - <span class="sponsor-badge">sponsor</span> - <img class="sponsor-image" src="/img/sponsors/reflex-banner.png" /> - </a> - </div> <div class="item"> <a title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files" style="display: block; position: relative;" href="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=top-banner" target="_blank"> <span class="sponsor-badge">sponsor</span> From cd86c72ed6087943e362040c4fcbf056e57cb89d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 23 Jul 2024 19:36:46 +0000 Subject: [PATCH 619/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7872e2fbe..962db1395 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🔧 Update sponsors, remove Reflex. PR [#11875](https://github.com/tiangolo/fastapi/pull/11875) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors: remove TalkPython. PR [#11861](https://github.com/tiangolo/fastapi/pull/11861) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs Termynal scripts to not include line nums for local dev. PR [#11854](https://github.com/tiangolo/fastapi/pull/11854) by [@tiangolo](https://github.com/tiangolo). From 4b4c48ecff0eb8feff2f3086d1615c84882ad463 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Wed, 24 Jul 2024 17:39:07 -0300 Subject: [PATCH 620/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/response-change-status-co?= =?UTF-8?q?de.md`=20(#11863)?= 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/pt/docs/advanced/response-change-status-code.md diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..99695c831 --- /dev/null +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -0,0 +1,33 @@ +# Retorno - Altere o Código de Status + +Você provavelmente leu anteriormente que você pode definir um [Código de Status do Retorno](../tutorial/response-status-code.md){.internal-link target=_blank} padrão. + +Porém em alguns casos você precisa retornar um código de status diferente do padrão. + +## Caso de uso + +Por exemplo, imagine que você deseja retornar um código de status HTTP de "OK" `200` por padrão. + +Mas se o dado não existir, você quer criá-lo e retornar um código de status HTTP de "CREATED" `201`. + +Mas você ainda quer ser capaz de filtrar e converter o dado que você retornará com um `response_model`. + +Para estes casos, você pode utilizar um parâmetro `Response`. + +## Use um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` em sua *função de operação de rota* (assim como você pode fazer para cookies e headers). + +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!} +``` + +E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). + +E se você declarar um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou. + +O **FastAPI** utilizará este retorno *temporal* para extrair o código de status (e também cookies e headers), e irá colocá-los no retorno final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` nas dependências, e definir o código de status nelas. Mas lembre-se que o último que for definido é o que prevalecerá. From 386a6796abb445d04e65c729dbb7fcc4a4775b96 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 24 Jul 2024 20:39:30 +0000 Subject: [PATCH 621/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 962db1395..5a9b1c06c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-change-status-code.md`. PR [#11863](https://github.com/tiangolo/fastapi/pull/11863) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/background.md`. PR [#11849](https://github.com/tiangolo/fastapi/pull/11849) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#11848](https://github.com/tiangolo/fastapi/pull/11848) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/apirouter.md`. PR [#11843](https://github.com/tiangolo/fastapi/pull/11843) by [@lucasbalieiro](https://github.com/lucasbalieiro). From c96afadbd74cc25f8cb73f0a456b217f17bf5368 Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov <drammtv@gmail.com> Date: Sun, 28 Jul 2024 02:59:11 +0300 Subject: [PATCH 622/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/dependencies/sub-dependencie?= =?UTF-8?q?s.md`=20(#10515)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/dependencies/sub-dependencies.md | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 docs/ru/docs/tutorial/dependencies/sub-dependencies.md diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..31f9f43c6 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,194 @@ +# Подзависимости + +Вы можете создавать зависимости, которые имеют **подзависимости**. + +Их **вложенность** может быть любой глубины. + +**FastAPI** сам займётся их управлением. + +## Провайдер зависимости + +Можно создать первую зависимость следующим образом: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.6 без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. + +Это довольно просто (хотя и не очень полезно), но поможет нам сосредоточиться на том, как работают подзависимости. + +## Вторая зависимость + +Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): + +=== "Python 3.10+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="14" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.6 без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +Остановимся на объявленных параметрах: + +* Несмотря на то, что эта функция сама является зависимостью, она также является зависимой от чего-то другого. + * Она зависит от `query_extractor` и присваивает возвращаемое ей значение параметру `q`. +* Она также объявляет необязательный куки-параметр `last_query` в виде строки. + * Если пользователь не указал параметр `q` в запросе, то мы используем последний использованный запрос, который мы ранее сохранили в куки-параметре `last_query`. + +## Использование зависимости + +Затем мы можем использовать зависимость вместе с: + +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="24" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.6 без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="22" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +!!! info "Дополнительная информация" + Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. + + Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове. + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Использование одной и той же зависимости несколько раз + +Если одна из ваших зависимостей объявлена несколько раз для одной и той же *функции операции пути*, например, несколько зависимостей имеют общую подзависимость, **FastAPI** будет знать, что вызывать эту подзависимость нужно только один раз за запрос. + +При этом возвращаемое значение будет сохранено в <abbr title="Система для хранения значений, сгенерированных компьютером, для их повторного использования вместо повторного вычисления.">"кэш"</abbr> и будет передано всем "зависимым" функциям, которые нуждаются в нем внутри этого конкретного запроса, вместо того, чтобы вызывать зависимость несколько раз для одного и того же запроса. + +В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`: + +=== "Python 3.6+" + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="1" + async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} + ``` + +## Резюме + +Помимо всех этих умных слов, используемых здесь, система внедрения зависимостей довольно проста. + +Это просто функции, которые выглядят так же, как *функции операций путей*. + +Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко. + +!!! tip "Подсказка" + Все это может показаться не столь полезным на этих простых примерах. + + Но вы увидите как это пригодится в главах посвященных безопасности. + + И вы также увидите, сколько кода это вам сэкономит. From a4fd3fd4835a3905e5c7823f142b06bdcf9ebd2c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 27 Jul 2024 23:59:30 +0000 Subject: [PATCH 623/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5a9b1c06c..b61857fb5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10515](https://github.com/tiangolo/fastapi/pull/10515) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-change-status-code.md`. PR [#11863](https://github.com/tiangolo/fastapi/pull/11863) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/background.md`. PR [#11849](https://github.com/tiangolo/fastapi/pull/11849) by [@lucasbalieiro](https://github.com/lucasbalieiro). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#11848](https://github.com/tiangolo/fastapi/pull/11848) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 81234084cd4691a844ae75489f9c58705588a828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 27 Jul 2024 19:03:57 -0500 Subject: [PATCH 624/846] =?UTF-8?q?=F0=9F=93=9D=20Re-structure=20docs=20ma?= =?UTF-8?q?in=20menu=20(#11904)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/features.md | 5 ----- docs/de/docs/help/index.md | 3 --- docs/de/docs/index.md | 5 +---- docs/em/docs/features.md | 5 ----- docs/em/docs/index.md | 5 +---- docs/en/docs/features.md | 5 ----- docs/en/docs/help/index.md | 3 --- docs/en/docs/index.md | 5 +---- docs/en/docs/reference/index.md | 2 +- docs/en/mkdocs.yml | 12 ++++++------ docs/es/docs/features.md | 5 ----- docs/es/docs/help/index.md | 3 --- docs/es/docs/index.md | 5 +---- docs/fa/docs/index.md | 5 +---- docs/fr/docs/features.md | 5 ----- docs/fr/docs/index.md | 5 +---- docs/he/docs/index.md | 5 +---- docs/ja/docs/features.md | 5 ----- docs/ja/docs/index.md | 5 +---- docs/ko/docs/features.md | 5 ----- docs/ko/docs/help/index.md | 3 --- docs/ko/docs/index.md | 5 +---- docs/pl/docs/features.md | 5 ----- docs/pl/docs/index.md | 5 +---- docs/pt/docs/features.md | 5 ----- docs/pt/docs/help/index.md | 3 --- docs/pt/docs/index.md | 5 +---- docs/ru/docs/features.md | 5 ----- docs/ru/docs/index.md | 5 +---- docs/tr/docs/features.md | 5 ----- docs/tr/docs/help/index.md | 3 --- docs/tr/docs/index.md | 5 +---- docs/vi/docs/features.md | 5 ----- docs/vi/docs/index.md | 5 +---- docs/yo/docs/index.md | 5 +---- docs/zh/docs/features.md | 5 ----- docs/zh/docs/index.md | 5 +---- 37 files changed, 23 insertions(+), 154 deletions(-) delete mode 100644 docs/de/docs/help/index.md delete mode 100644 docs/en/docs/help/index.md delete mode 100644 docs/es/docs/help/index.md delete mode 100644 docs/ko/docs/help/index.md delete mode 100644 docs/pt/docs/help/index.md delete mode 100644 docs/tr/docs/help/index.md diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index 76aad9f16..1e68aff88 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Merkmale ## FastAPI Merkmale diff --git a/docs/de/docs/help/index.md b/docs/de/docs/help/index.md deleted file mode 100644 index 8fdc4a049..000000000 --- a/docs/de/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Hilfe - -Helfen und Hilfe erhalten, beitragen, mitmachen. 🤝 diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index ccc50fd62..e3c5be321 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index 6ef7c5ccc..3693f4c54 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # ⚒ ## FastAPI ⚒ diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index c4e41ce17..0b5cca86f 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 8afa13a98..f8954c0fc 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Features ## FastAPI features diff --git a/docs/en/docs/help/index.md b/docs/en/docs/help/index.md deleted file mode 100644 index 5ee7df2fe..000000000 --- a/docs/en/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Help - -Help and get help, contribute, get involved. 🤝 diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 8b54f175f..75f27d04f 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/en/docs/reference/index.md b/docs/en/docs/reference/index.md index 512d5c25c..b6dfdd063 100644 --- a/docs/en/docs/reference/index.md +++ b/docs/en/docs/reference/index.md @@ -1,4 +1,4 @@ -# Reference - Code API +# Reference Here's the reference or code API, the classes, functions, parameters, attributes, and all the FastAPI parts you can use in your applications. diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 05dffb706..31ec6ebc7 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -81,8 +81,9 @@ plugins: show_symbol_type_heading: true show_symbol_type_toc: true nav: -- FastAPI: index.md -- features.md +- FastAPI: + - index.md + - features.md - Learn: - learn/index.md - python-types.md @@ -218,6 +219,8 @@ nav: - fastapi-people.md - Resources: - resources/index.md + - help-fastapi.md + - contributing.md - project-generation.md - external-links.md - newsletter.md @@ -226,10 +229,7 @@ nav: - alternatives.md - history-design-future.md - benchmarks.md -- Help: - - help/index.md - - help-fastapi.md - - contributing.md + - release-notes.md markdown_extensions: toc: diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index 7623d8eb1..d957b10b7 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Características ## Características de FastAPI diff --git a/docs/es/docs/help/index.md b/docs/es/docs/help/index.md deleted file mode 100644 index f6ce35e9c..000000000 --- a/docs/es/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Ayuda - -Ayuda y recibe ayuda, contribuye, involúcrate. 🤝 diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 5153367dd..733e4664e 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index dfbb8e647..ea8063129 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index da1c70df9..1457df2a5 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Fonctionnalités ## Fonctionnalités de FastAPI diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index e31f416ce..5b0ba142e 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 626578e40..6af8e3217 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 64d8758a5..98c59e7c4 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # 機能 ## FastAPIの機能 diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 2d4daac75..6f85d2013 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index f7b35557c..ca1940a21 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # 기능 ## FastAPI의 기능 diff --git a/docs/ko/docs/help/index.md b/docs/ko/docs/help/index.md deleted file mode 100644 index fc023071a..000000000 --- a/docs/ko/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# 도움 - -도움을 주고 받고, 기여하고, 참여합니다. 🤝 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 21dd16f59..66ecd7dff 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index 7c2013799..a6435977c 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Cechy ## Cechy FastAPI diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 83bbe19cf..a69d7dc14 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index c514fc8e3..64efeeae1 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Recursos ## Recursos do FastAPI diff --git a/docs/pt/docs/help/index.md b/docs/pt/docs/help/index.md deleted file mode 100644 index e254e10df..000000000 --- a/docs/pt/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Ajude - -Ajude e obtenha ajuda, contribua, participe. 🤝 diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 6e7aa21f7..3f8dd18a9 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index 59860e12b..baa4ec778 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Основные свойства ## Основные свойства FastAPI diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index d59f45031..7148131dc 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index b964aba4d..1cda8c7fb 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Özelikler ## FastAPI özellikleri diff --git a/docs/tr/docs/help/index.md b/docs/tr/docs/help/index.md deleted file mode 100644 index cef0914ce..000000000 --- a/docs/tr/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Yardım - -Yardım alın, yardım edin, katkıda bulunun, dahil olun. 🤝 diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index f7a8cf2a5..3dc624a68 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md index fe75591dc..9edb1c8fa 100644 --- a/docs/vi/docs/features.md +++ b/docs/vi/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Tính năng ## Tính năng của FastAPI diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index b13f91fb7..c75af9fa8 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 9bd21c4b9..c2780a086 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index b613aaf72..d8190032f 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # 特性 ## FastAPI 特性 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index f03a0dd13..0933a0291 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI <style> .md-content .md-typeset h1 { display: none; } From dddf07904ab1ddac8d9879d02565c345546d3ff8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 28 Jul 2024 00:04:20 +0000 Subject: [PATCH 625/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b61857fb5..cfdd704b2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Re-structure docs main menu. PR [#11904](https://github.com/tiangolo/fastapi/pull/11904) by [@tiangolo](https://github.com/tiangolo). * 📝 Update Speakeasy URL. PR [#11871](https://github.com/tiangolo/fastapi/pull/11871) by [@ndimares](https://github.com/ndimares). ### Translations From d6dfb9397b9c8b68bfc5a8ca3ccbcef9f9ad089d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 28 Jul 2024 13:49:12 -0500 Subject: [PATCH 626/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20GitHub=20Action?= =?UTF-8?q?=20to=20notify=20translations=20with=20label=20`approved-1`=20(?= =?UTF-8?q?#11907)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 👷 Update GitHub Action to notify translations with label approved-1 --- .github/actions/notify-translations/app/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py index 8ac1f233d..9ded86da9 100644 --- a/.github/actions/notify-translations/app/main.py +++ b/.github/actions/notify-translations/app/main.py @@ -11,7 +11,7 @@ from pydantic import BaseModel, BaseSettings, SecretStr awaiting_label = "awaiting-review" lang_all_label = "lang-all" -approved_label = "approved-2" +approved_label = "approved-1" translations_path = Path(__file__).parent / "translations.yml" github_graphql_url = "https://api.github.com/graphql" From c944f9c40c30cee570d15ffc6fe313537d8ca475 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 28 Jul 2024 18:49:31 +0000 Subject: [PATCH 627/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cfdd704b2..24d8d0ed5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Internal +* 👷 Update GitHub Action to notify translations with label `approved-1`. PR [#11907](https://github.com/tiangolo/fastapi/pull/11907) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Reflex. PR [#11875](https://github.com/tiangolo/fastapi/pull/11875) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors: remove TalkPython. PR [#11861](https://github.com/tiangolo/fastapi/pull/11861) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs Termynal scripts to not include line nums for local dev. PR [#11854](https://github.com/tiangolo/fastapi/pull/11854) by [@tiangolo](https://github.com/tiangolo). From baf1efc8b8e650e182550f9702f31fa8f1b2e925 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 28 Jul 2024 15:26:24 -0500 Subject: [PATCH 628/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20docs=20about=20Fas?= =?UTF-8?q?tAPI=20team=20and=20project=20management=20(#11908)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/members.yml | 19 +++ docs/en/docs/fastapi-people.md | 19 +++ docs/en/docs/management-tasks.md | 256 +++++++++++++++++++++++++++++++ docs/en/docs/management.md | 41 +++++ docs/en/mkdocs.yml | 4 +- 5 files changed, 338 insertions(+), 1 deletion(-) create mode 100644 docs/en/data/members.yml create mode 100644 docs/en/docs/management-tasks.md create mode 100644 docs/en/docs/management.md diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml new file mode 100644 index 000000000..0b9e7b94c --- /dev/null +++ b/docs/en/data/members.yml @@ -0,0 +1,19 @@ +members: +- login: tiangolo + avatar_url: https://github.com/tiangolo.png + url: https://github.com/tiangolo +- login: Kludex + avatar_url: https://github.com/Kludex.png + url: https://github.com/Kludex +- login: alejsdev + avatar_url: https://github.com/alejsdev.png + url: https://github.com/alejsdev +- login: svlandeg + avatar_url: https://github.com/svlandeg.png + url: https://github.com/svlandeg +- login: estebanx64 + avatar_url: https://github.com/estebanx64.png + url: https://github.com/estebanx64 +- login: patrick91 + avatar_url: https://github.com/patrick91.png + url: https://github.com/patrick91 diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index 2bd01ba43..80eee8cb0 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -36,9 +36,28 @@ These are the people that: * [Help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. * [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. * Review Pull Requests, [especially important for translations](contributing.md#translations){.internal-link target=_blank}. +* Help [manage the repository](management-tasks.md){.internal-link target=_blank} (team members). + +All these tasks help maintain the repository. A round of applause to them. 👏 🙇 +## Team + +This is the current list of team members. 😎 + +They have different levels of involvement and permissions, they can perform [repository management tasks](./management-tasks.md){.internal-link target=_blank} and together we [manage the FastAPI repository](./management.md){.internal-link target=_blank}. + +<div class="user-list user-list-center"> +{% for user in members["members"] %} + +<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatar_url }}"/></div><div class="title">@{{ user.login }}</div></a></div> +{% endfor %} + +</div> + +Although the team members have the permissions to perform privileged tasks, all the [help from others maintaining FastAPI](./help-fastapi.md#help-maintain-fastapi){.internal-link target=_blank} is very much appreciated! 🙇♂️ + ## FastAPI Experts These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🙇 diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md new file mode 100644 index 000000000..231dbe24d --- /dev/null +++ b/docs/en/docs/management-tasks.md @@ -0,0 +1,256 @@ +# Repository Management Tasks + +These are the tasks that can be performed to manage the FastAPI repository by [team members](./fastapi-people.md#team){.internal-link target=_blank}. + +!!! tip + This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉 + +...so, you are a [team member of FastAPI](./fastapi-people.md#team){.internal-link target=_blank}? Wow, you are so cool! 😎 + +You can help with everything on [Help FastAPI - Get Help](./help-fastapi.md){.internal-link target=_blank} the same ways as external contributors. But additionally, there are some tasks that only you (as part of the team) can perform. + +Here are the general instructions for the tasks you can perform. + +Thanks a lot for your help. 🙇 + +## Be Nice + +First of all, be nice. 😊 + +You probably are super nice if you were added to the team, but it's worth mentioning it. 🤓 + +### When Things are Difficult + +When things are great, everything is easier, so that doesn't need much instructions. But when things are difficult, here are some guidelines. + +Try to find the good side. In general, if people are not being unfriendly, try to thank their effort and interest, even if you disagree with the main subject (discussion, PR), just thank them for being interested in the project, or for having dedicated some time to try to do something. + +It's difficult to convey emotion in text, use emojis to help. 😅 + +In discussions and PRs, in many cases, people bring their frustration and show it without filter, in many cases exaggerating, complaining, being entitled, etc. That's really not nice, and when it happens, it lowers our priority to solve their problems. But still, try to breath, and be gentle with your answers. + +Try to avoid using bitter sarcasm or potentially passive-aggressive comments. If something is wrong, it's better to be direct (try to be gentle) than sarcastic. + +Try to be as specific and objective as possible, avoid generalizations. + +For conversations that are more difficult, for example to reject a PR, you can ask me (@tiangolo) to handle it directly. + +## Edit PR Titles + +* Edit the PR title to start with an emoji from <a href="https://gitmoji.dev/" class="external-link" target="_blank">gitmoji</a>. + * Use the emoji character, not the GitHub code. So, use `🐛` instead of `:bug:`. This is so that it shows up correctly outside of GitHub, for example in the release notes. + * For translations use the `🌐` emoji ("globe with meridians"). +* Start the title with a verb. For example `Add`, `Refactor`, `Fix`, etc. This way the title will say the action that the PR does. Like `Add support for teleporting`, instead of `Teleporting wasn't working, so this PR fixes it`. +* Edit the text of the PR title to start in "imperative", like giving an order. So, instead of `Adding support for teleporting` use `Add support for teleporting`. +* Try to make the title descriptive about what it achieves. If it's a feature, try to describe it, for example `Add support for teleporting` instead of `Create TeleportAdapter class`. +* Do not finish the title with a period (`.`). +* When the PR is for a translation, start with the `🌐` and then `Add {language} translation for` and then the translated file path. For example: + +```Markdown +🌐 Add Spanish translation for `docs/es/docs/teleporting.md` +``` + +Once the PR is merged, a GitHub Action (<a href="https://github.com/tiangolo/latest-changes" class="external-link" target="_blank">latest-changes</a>) will use the PR title to update the latest changes automatically. + +So, having a nice PR title will not only look nice in GitHub, but also in the release notes. 📝 + +## Add Labels to PRs + +The same GitHub Action <a href="https://github.com/tiangolo/latest-changes" class="external-link" target="_blank">latest-changes</a> uses one label in the PR to decide the section in the release notes to put this PR in. + +Make sure you use a supported label from the <a href="https://github.com/tiangolo/latest-changes#using-labels" class="external-link" target="_blank">latest-changes list of labels</a>: + +* `breaking`: Breaking Changes + * Existing code will break if they update the version without changing their code. This rarely happens, so this label is not frequently used. +* `security`: Security Fixes + * This is for security fixes, like vulnerabilities. It would almost never be used. +* `feature`: Features + * New features, adding support for things that didn't exist before. +* `bug`: Fixes + * Something that was supported didn't work, and this fixes it. There are many PRs that claim to be bug fixes because the user is doing something in an unexpected way that is not supported, but they considered it what should be supported by default. Many of these are actually features or refactors. But in some cases there's an actual bug. +* `refactor`: Refactors + * This is normally for changes to the internal code that don't change the behavior. Normally it improves maintainability, or enables future features, etc. +* `upgrade`: Upgrades + * This is for upgrades to direct dependencies from the project, or extra optional dependencies, normally in `pyproject.toml`. So, things that would affect final users, they would end up receiving the upgrade in their code base once they update. But this is not for upgrades to internal dependencies used for development, testing, docs, etc. Those internal dependencies, normally in `requirements.txt` files or GitHub Action versions should be marked as `internal`, not `upgrade`. +* `docs`: Docs + * Changes in docs. This includes updating the docs, fixing typos. But it doesn't include changes to translations. + * You can normally quickly detect it by going to the "Files changed" tab in the PR and checking if the updated file(s) starts with `docs/en/docs`. The original version of the docs is always in English, so in `docs/en/docs`. +* `lang-all`: Translations + * Use this for translations. You can normally quickly detect it by going to the "Files changed" tab in the PR and checking if the updated file(s) starts with `docs/{some lang}/docs` but not `docs/en/docs`. For example, `docs/es/docs`. +* `internal`: Internal + * Use this for changes that only affect how the repo is managed. For example upgrades to internal dependencies, changes in GitHub Actions or scripts, etc. + +!!! tip + Some tools like Dependabot, will add some labels, like `dependencies`, but have in mind that this label is not used by the `latest-changes` GitHub Action, so it won't be used in the release notes. Please make sure one of the labels above is added. + +## Add Labels to Translation PRs + +When there's a PR for a translation, apart from adding the `lang-all` label, also add a label for the language. + +There will be a label for each language using the language code, like `lang-{lang code}`, for example, `lang-es` for Spanish, `lang-fr` for French, etc. + +* Add the specific language label. +* Add the label `awaiting-review`. + +The label `awaiting-review` is special, only used for translations. A GitHub Action will detect it, then it will read the language label, and it will update the GitHub Discussions managing the translations for that language to notify people that there's a new translation to review. + +Once a native speaker comes, reviews the PR, and approves it, the GitHub Action will come and remove the `awaiting-review` label, and add the `approved-1` label. + +This way, we can notice when there are new translations ready, because they have the `approved-1` label. + +## Merge Translation PRs + +For Spanish, as I'm a native speaker and it's a language close to me, I will give it a final review myself and in most cases tweak the PR a bit before merging it. + +For the other languages, confirm that: + +* The title is correct following the instructions above. +* It has the labels `lang-all` and `lang-{lang code}`. +* The PR changes only one Markdown file adding a translation. + * Or in some cases, at most two files, if they are small and people reviewed them. + * If it's the first translation for that language, it will have additional `mkdocs.yml` files, for those cases follow the instructions below. +* The PR doesn't add any additional or extraneous files. +* The translation seems to have a similar structure as the original English file. +* The translation doesn't seem to change the original content, for example with obvious additional documentation sections. +* The translation doesn't use different Markdown structures, for example adding HTML tags when the original didn't have them. +* The "admonition" sections, like `tip`, `info`, etc. are not changed or translated. For example: + +``` +!!! tip + This is a tip. +``` + +looks like this: + +!!! tip + This is a tip. + +...it could be translated as: + +``` +!!! tip + Esto es un consejo. +``` + +...but needs to keep the exact `tip` keyword. If it was translated to `consejo`, like: + +``` +!!! consejo + Esto es un consejo. +``` + +it would change the style to the default one, it would look like: + +!!! consejo + Esto es un consejo. + +Those don't have to be translated, but if they are, they need to be written as: + +``` +!!! tip "consejo" + Esto es un consejo. +``` + +Which looks like: + +!!! tip "consejo" + Esto es un consejo. + +## First Translation PR + +When there's a first translation for a language, it will have a `docs/{lang code}/docs/index.md` translated file and a `docs/{lang code}/mkdocs.yml`. + +For example, for Bosnian, it would be: + +* `docs/bs/docs/index.md` +* `docs/bs/mkdocs.yml` + +The `mkdocs.yml` file will have only the following content: + +```YAML +INHERIT: ../en/mkdocs.yml +``` + +The language code would normally be in the <a href="https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes" class="external-link" target="_blank">ISO 639-1 list of language codes</a>. + +In any case, the language code should be in the file <a href="https://github.com/tiangolo/fastapi/blob/master/docs/language_names.yml" class="external-link" target="_blank">docs/language_names.yml</a>. + +There won't be yet a label for the language code, for example, if it was Bosnian, there wouldn't be a `lang-bs`. Before creating the label and adding it to the PR, create the GitHub Discussion: + +* Go to the <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">Translations GitHub Discussions</a> +* Create a new discussion with the title `Bosnian Translations` (or the language name in English) +* A description of: + +```Markdown +## Bosnian translations + +This is the issue to track translations of the docs to Bosnian. 🚀 + +Here are the [PRs to review with the label `lang-bs`](https://github.com/tiangolo/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-bs+label%3A%22awaiting-review%22). 🤓 +``` + +Update "Bosnian" with the new language. + +And update the search link to point to the new language label that will be created, like `lang-bs`. + +Create and add the label to that new Discussion just created, like `lang-bs`. + +Then go back to the PR, and add the label, like `lang-bs`, and `lang-all` and `awaiting-review`. + +Now the GitHub action will automatically detect the label `lang-bs` and will post in that Discussion that this PR is waiting to be reviewed. + +## Review PRs + +If a PR doesn't explain what it does or why, ask for more information. + +A PR should have a specific use case that it is solving. + +* If the PR is for a feature, it should have docs. + * Unless it's a feature we want to discourage, like support for a corner case that we don't want users to use. +* The docs should include a source example file, not write Python directly in Markdown. +* If the source example(s) file can have different syntax for Python 3.8, 3.9, 3.10, there should be different versions of the file, and they should be shown in tabs in the docs. +* There should be tests testing the source example. +* Before the PR is applied, the new tests should fail. +* After applying the PR, the new tests should pass. +* Coverage should stay at 100%. +* If you see the PR makes sense, or we discussed it and considered it should be accepted, you can add commits on top of the PR to tweak it, to add docs, tests, format, refactor, remove extra files, etc. +* Feel free to comment in the PR to ask for more information, to suggest changes, etc. +* Once you think the PR is ready, move it in the internal GitHub project for me to review it. + +## FastAPI People PRs + +Every month, a GitHub Action updates the FastAPI People data. Those PRs look like this one: <a href="https://github.com/tiangolo/fastapi/pull/11669" class="external-link" target="_blank">👥 Update FastAPI People</a>. + +If the tests are passing, you can merge it right away. + +## External Links PRs + +When people add external links they edit this file <a href="https://github.com/tiangolo/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">external_links.yml</a>. + +* Make sure the new link is in the correct category (e.g. "Podcasts") and language (e.g. "Japanese"). +* A new link should be at the top of its list. +* The link URL should work (it should not return a 404). +* The content of the link should be about FastAPI. +* The new addition should have these fields: + * `author`: The name of the author. + * `link`: The URL with the content. + * `title`: The title of the link (the title of the article, podcast, etc). + +After checking all these things and ensuring the PR has the right labels, you can merge it. + +## Dependabot PRs + +Dependabot will create PRs to update dependencies for several things, and those PRs all look similar, but some are way more delicate than others. + +* If the PR is for a direct dependency, so, Dependabot is modifying `pyproject.toml`, **don't merge it**. 😱 Let me check it first. There's a good chance that some additional tweaks or updates are needed. +* If the PR updates one of the internal dependencies, for example it's modifying `requirements.txt` files, or GitHub Action versions, if the tests are passing, the release notes (shown in a summary in the PR) don't show any obvious potential breaking change, you can merge it. 😎 + +## Mark GitHub Discussions Answers + +When a question in GitHub Discussions has been answered, mark the answer by clicking "Mark as answer". + +Many of the current Discussion Questions were migrated from old issues. Many have the label `answered`, that means they were answered when they were issues, but now in GitHub Discussions, it's not known what is the actual response from the messages. + +You can filter discussions by [`Questions` that are `Unanswered` and have the label `answered`](https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aopen+label%3Aanswered+is%3Aunanswered). + +All of those discussions already have an answer in the conversation, you can find it and mark it with the "Mark as answer" button. diff --git a/docs/en/docs/management.md b/docs/en/docs/management.md new file mode 100644 index 000000000..27bf0bd1c --- /dev/null +++ b/docs/en/docs/management.md @@ -0,0 +1,41 @@ +# Repository Management + +Here's a short description of how the FastAPI repository is managed and maintained. + +## Owner + +I, <a href="https://github.com/tiangolo" target="_blank">@tiangolo</a>, am the creator and owner of the FastAPI repository. 🤓 + +I make the final decisions on the the project. I'm the <a href="https://en.wikipedia.org/wiki/Benevolent_dictator_for_life" class="external-link" target="_blank"><abbr title="Benevolent Dictator For Life">BDFL</abbr></a>. 😅 + +I normally give the final review to each PR, commonly with some tweaking commits on top, before merging them. + +## Team + +There's a team of people that help manage and maintain the project. 😎 + +They have different levels of permissions and [specific instructions](./management-tasks.md){.internal-link target=_blank}. + +Some of the tasks they can perform include: + +* Adding labels to PRs. +* Editing PR titles. +* Adding commits on top of PRs to tweak them. +* Mark answers in GitHub Discussions questions, etc. +* Merge some specific types of PRs. + +You can see the current team members in [FastAPI People - Team](./fastapi-people.md#team){.internal-link target=_blank}. + +Joining the team is by invitation only, and I could update or remove permissions, instructions, or membership. + +## FastAPI Experts + +The people that help others the most in GitHub Discussions can become [**FastAPI Experts**](./fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +This is normally the best way to contribute to the project. + +## External Contributions + +External contributions are very welcome and appreciated, including answering questions, submitting PRs, etc. 🙇♂️ + +There are many ways to [help maintain FastAPI](./help-fastapi.md#help-maintain-fastapi){.internal-link target=_blank}. diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 31ec6ebc7..81baa051a 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -46,6 +46,7 @@ plugins: - external_links: ../en/data/external_links.yml - github_sponsors: ../en/data/github_sponsors.yml - people: ../en/data/people.yml + - members: ../en/data/members.yml - sponsors_badge: ../en/data/sponsors_badge.yml - sponsors: ../en/data/sponsors.yml redirects: @@ -224,12 +225,13 @@ nav: - project-generation.md - external-links.md - newsletter.md + - management-tasks.md - About: - about/index.md - alternatives.md - history-design-future.md - benchmarks.md - + - management.md - release-notes.md markdown_extensions: toc: From dc8e194a20208a01bb05d71ac0404925dd44a7dd Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 28 Jul 2024 20:26:48 +0000 Subject: [PATCH 629/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 24d8d0ed5..adc8556f9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add docs about FastAPI team and project management. PR [#11908](https://github.com/tiangolo/fastapi/pull/11908) by [@tiangolo](https://github.com/tiangolo). * 📝 Re-structure docs main menu. PR [#11904](https://github.com/tiangolo/fastapi/pull/11904) by [@tiangolo](https://github.com/tiangolo). * 📝 Update Speakeasy URL. PR [#11871](https://github.com/tiangolo/fastapi/pull/11871) by [@ndimares](https://github.com/ndimares). From 84b4ac595e81d5cd625016d93c12b525cfc44aca Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Mon, 29 Jul 2024 14:09:51 -0300 Subject: [PATCH 630/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/wsgi.md`=20(#11909)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/wsgi.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 docs/pt/docs/advanced/wsgi.md diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md new file mode 100644 index 000000000..2c7ac1ffe --- /dev/null +++ b/docs/pt/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# Adicionando WSGI - Flask, Django, entre outros + +Como você viu em [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank} e [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}, você pode **"montar"** aplicações WSGI. + +Para isso, você pode utilizar o `WSGIMiddleware` para encapsular a sua aplicação WSGI, como por exemplo Flask, Django, etc. + +## Usando o `WSGIMiddleware` + +Você precisa importar o `WSGIMiddleware`. + +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!} +``` + +## Conferindo + +Agora todas as requisições sob o caminho `/v1/` serão manipuladas pela aplicação utilizando Flask. + +E o resto será manipulado pelo **FastAPI**. + +Se você rodar a aplicação e ir até <a href="http://localhost:8000/v1/" class="external-link" target="_blank">http://localhost:8000/v1/</a>, você verá o retorno do Flask: + +```txt +Hello, World from Flask! +``` + +E se você for até <a href="http://localhost:8000/v2" class="external-link" target="_blank">http://localhost:8000/v2</a>, você verá o retorno do FastAPI: + +```JSON +{ + "message": "Hello World" +} +``` From 9e42833445beea11628fe9f7cdd2221aeed8ad55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Jul 2024 13:12:13 -0500 Subject: [PATCH 631/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20GitHub=20Action?= =?UTF-8?q?s=20token=20usage=20(#11914)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 4 ++-- .github/workflows/issue-manager.yml | 2 +- .github/workflows/label-approved.yml | 2 +- .github/workflows/notify-translations.yml | 2 +- .github/workflows/smokeshow.yml | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index dd54608d9..d8f18ff61 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -24,7 +24,7 @@ jobs: path: ./site/ pattern: docs-site-* merge-multiple: true - github-token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} + github-token: ${{ secrets.GITHUB_TOKEN }} run-id: ${{ github.event.workflow_run.id }} - name: Deploy to Cloudflare Pages # hashFiles returns an empty string if there are no files @@ -42,5 +42,5 @@ jobs: if: steps.deploy.outputs.url != '' uses: ./.github/actions/comment-docs-preview-in-pr with: - token: ${{ secrets.FASTAPI_PREVIEW_DOCS_COMMENT_DEPLOY }} + token: ${{ secrets.GITHUB_TOKEN }} deploy_url: "${{ steps.deploy.outputs.url }}" diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index 0f564d721..bd0113dc7 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -25,7 +25,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: tiangolo/issue-manager@0.5.0 with: - token: ${{ secrets.FASTAPI_ISSUE_MANAGER }} + token: ${{ secrets.GITHUB_TOKEN }} config: > { "answered": { diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 51be2413d..417e19dad 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -16,7 +16,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: docker://tiangolo/label-approved:0.0.4 with: - token: ${{ secrets.FASTAPI_LABEL_APPROVED }} + token: ${{ secrets.GITHUB_TOKEN }} config: > { "approved-1": diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index c0904ce48..b0ebb5a0a 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -32,4 +32,4 @@ jobs: limit-access-to-actor: true - uses: ./.github/actions/notify-translations with: - token: ${{ secrets.FASTAPI_NOTIFY_TRANSLATIONS }} + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index ffc9c5f8a..d3a975df5 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -28,7 +28,7 @@ jobs: with: name: coverage-html path: htmlcov - github-token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} + github-token: ${{ secrets.GITHUB_TOKEN }} run-id: ${{ github.event.workflow_run.id }} - run: smokeshow upload htmlcov @@ -36,6 +36,6 @@ jobs: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 100 SMOKESHOW_GITHUB_CONTEXT: coverage - SMOKESHOW_GITHUB_TOKEN: ${{ secrets.FASTAPI_SMOKESHOW_UPLOAD }} + SMOKESHOW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SMOKESHOW_GITHUB_PR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} SMOKESHOW_AUTH_KEY: ${{ secrets.SMOKESHOW_AUTH_KEY }} From 7eb37d08bc9d3b5529c5d541f22701f742d0abab Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 29 Jul 2024 18:12:37 +0000 Subject: [PATCH 632/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index adc8556f9..d460ff58b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update GitHub Actions token usage. PR [#11914](https://github.com/fastapi/fastapi/pull/11914) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action to notify translations with label `approved-1`. PR [#11907](https://github.com/tiangolo/fastapi/pull/11907) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Reflex. PR [#11875](https://github.com/tiangolo/fastapi/pull/11875) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors: remove TalkPython. PR [#11861](https://github.com/tiangolo/fastapi/pull/11861) by [@tiangolo](https://github.com/tiangolo). From 8bd07a4342a6660ce9c3793c3715e542190096fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Jul 2024 17:51:29 -0500 Subject: [PATCH 633/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20token=20permiss?= =?UTF-8?q?ions=20for=20GitHub=20Actions=20(#11915)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 2 ++ .github/workflows/notify-translations.yml | 3 +++ 2 files changed, 5 insertions(+) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index d8f18ff61..6de36e408 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -5,6 +5,8 @@ on: - Build Docs types: - completed +permissions: + deployments: write jobs: deploy-docs: diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index b0ebb5a0a..4787f3ddd 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -15,6 +15,9 @@ on: required: false default: 'false' +permissions: + discussions: write + jobs: notify-translations: runs-on: ubuntu-latest From 2c57673e078a2e133c3b37e192a65c654cd8ddf8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 29 Jul 2024 22:51:53 +0000 Subject: [PATCH 634/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d460ff58b..43cafafaf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update token permissions for GitHub Actions. PR [#11915](https://github.com/fastapi/fastapi/pull/11915) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Actions token usage. PR [#11914](https://github.com/fastapi/fastapi/pull/11914) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action to notify translations with label `approved-1`. PR [#11907](https://github.com/tiangolo/fastapi/pull/11907) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Reflex. PR [#11875](https://github.com/tiangolo/fastapi/pull/11875) by [@tiangolo](https://github.com/tiangolo). From de70702b7c05a95a6a915d2fd72d21ba96adb2d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Jul 2024 18:09:18 -0500 Subject: [PATCH 635/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20token=20permiss?= =?UTF-8?q?ions=20to=20comment=20deployment=20URL=20in=20docs=20(#11917)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 6de36e408..0f2fb4a5a 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -7,6 +7,7 @@ on: - completed permissions: deployments: write + issues: write jobs: deploy-docs: From 12fffbc7ea452b63e433a034cfe99419efed0035 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 29 Jul 2024 23:09:37 +0000 Subject: [PATCH 636/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 43cafafaf..a14d627c6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update token permissions to comment deployment URL in docs. PR [#11917](https://github.com/fastapi/fastapi/pull/11917) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token permissions for GitHub Actions. PR [#11915](https://github.com/fastapi/fastapi/pull/11915) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Actions token usage. PR [#11914](https://github.com/fastapi/fastapi/pull/11914) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action to notify translations with label `approved-1`. PR [#11907](https://github.com/tiangolo/fastapi/pull/11907) by [@tiangolo](https://github.com/tiangolo). From 221e59b0d16e81d75261574e39209ffebf249618 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Jul 2024 18:35:07 -0500 Subject: [PATCH 637/846] =?UTF-8?q?=F0=9F=9A=9A=20Rename=20GitHub=20links?= =?UTF-8?q?=20from=20tiangolo/fastapi=20to=20fastapi/fastapi=20(#11913)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/ISSUE_TEMPLATE/config.yml | 8 +++--- .github/ISSUE_TEMPLATE/privileged.yml | 2 +- .../actions/notify-translations/app/main.py | 4 +-- .github/actions/people/app/main.py | 6 ++-- .github/workflows/issue-manager.yml | 2 +- .github/workflows/label-approved.yml | 2 +- .github/workflows/people.yml | 2 +- CITATION.cff | 2 +- README.md | 12 ++++---- docs/az/docs/fastapi-people.md | 4 +-- docs/az/docs/index.md | 12 ++++---- docs/bn/docs/index.md | 12 ++++---- docs/de/docs/contributing.md | 6 ++-- docs/de/docs/external-links.md | 4 +-- docs/de/docs/fastapi-people.md | 4 +-- docs/de/docs/help-fastapi.md | 18 ++++++------ docs/de/docs/history-design-future.md | 2 +- docs/de/docs/index.md | 12 ++++---- docs/de/docs/project-generation.md | 2 +- docs/em/docs/contributing.md | 4 +-- docs/em/docs/external-links.md | 2 +- docs/em/docs/fastapi-people.md | 4 +-- docs/em/docs/help-fastapi.md | 18 ++++++------ docs/em/docs/history-design-future.md | 2 +- docs/em/docs/index.md | 12 ++++---- docs/em/docs/project-generation.md | 2 +- docs/en/docs/contributing.md | 6 ++-- docs/en/docs/external-links.md | 2 +- docs/en/docs/fastapi-people.md | 4 +-- docs/en/docs/help-fastapi.md | 18 ++++++------ docs/en/docs/history-design-future.md | 2 +- docs/en/docs/index.md | 12 ++++---- docs/en/docs/js/custom.js | 2 +- docs/en/docs/management-tasks.md | 12 ++++---- docs/en/mkdocs.yml | 6 ++-- docs/es/docs/external-links.md | 2 +- docs/es/docs/index.md | 12 ++++---- docs/fa/docs/index.md | 12 ++++---- docs/fr/docs/contributing.md | 4 +-- docs/fr/docs/external-links.md | 2 +- docs/fr/docs/fastapi-people.md | 4 +-- docs/fr/docs/help-fastapi.md | 14 +++++----- docs/fr/docs/history-design-future.md | 2 +- docs/fr/docs/index.md | 12 ++++---- docs/fr/docs/project-generation.md | 2 +- docs/he/docs/index.md | 12 ++++---- docs/hu/docs/index.md | 12 ++++---- docs/it/docs/index.md | 12 ++++---- docs/ja/docs/contributing.md | 4 +-- docs/ja/docs/external-links.md | 2 +- docs/ja/docs/fastapi-people.md | 4 +-- docs/ja/docs/help-fastapi.md | 14 +++++----- docs/ja/docs/history-design-future.md | 2 +- docs/ja/docs/index.md | 12 ++++---- docs/ja/docs/project-generation.md | 2 +- docs/ko/docs/help-fastapi.md | 28 +++++++++---------- docs/ko/docs/index.md | 12 ++++---- docs/pl/docs/fastapi-people.md | 4 +-- docs/pl/docs/help-fastapi.md | 18 ++++++------ docs/pl/docs/index.md | 12 ++++---- docs/pt/docs/contributing.md | 4 +-- docs/pt/docs/external-links.md | 2 +- docs/pt/docs/fastapi-people.md | 4 +-- docs/pt/docs/help-fastapi.md | 16 +++++------ docs/pt/docs/history-design-future.md | 2 +- docs/pt/docs/index.md | 12 ++++---- docs/pt/docs/project-generation.md | 2 +- docs/ru/docs/contributing.md | 4 +-- docs/ru/docs/external-links.md | 2 +- docs/ru/docs/fastapi-people.md | 4 +-- docs/ru/docs/help-fastapi.md | 16 +++++------ docs/ru/docs/history-design-future.md | 2 +- docs/ru/docs/index.md | 12 ++++---- docs/ru/docs/project-generation.md | 2 +- docs/tr/docs/external-links.md | 2 +- docs/tr/docs/fastapi-people.md | 4 +-- docs/tr/docs/history-design-future.md | 2 +- docs/tr/docs/index.md | 12 ++++---- docs/tr/docs/project-generation.md | 2 +- docs/uk/docs/fastapi-people.md | 4 +-- docs/uk/docs/index.md | 12 ++++---- docs/vi/docs/index.md | 12 ++++---- docs/yo/docs/index.md | 12 ++++---- docs/zh-hant/docs/fastapi-people.md | 4 +-- docs/zh-hant/docs/index.md | 12 ++++---- docs/zh/docs/contributing.md | 8 +++--- docs/zh/docs/fastapi-people.md | 4 +-- docs/zh/docs/help-fastapi.md | 16 +++++------ docs/zh/docs/history-design-future.md | 2 +- docs/zh/docs/index.md | 12 ++++---- docs/zh/docs/project-generation.md | 2 +- pyproject.toml | 4 +-- 92 files changed, 325 insertions(+), 325 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index a8f4c4de2..fd9f3b11c 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -4,13 +4,13 @@ contact_links: about: Please report security vulnerabilities to security@tiangolo.com - name: Question or Problem about: Ask a question or ask about a problem in GitHub Discussions. - url: https://github.com/tiangolo/fastapi/discussions/categories/questions + url: https://github.com/fastapi/fastapi/discussions/categories/questions - name: Feature Request about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already. - url: https://github.com/tiangolo/fastapi/discussions/categories/questions + url: https://github.com/fastapi/fastapi/discussions/categories/questions - name: Show and tell about: Show what you built with FastAPI or to be used with FastAPI. - url: https://github.com/tiangolo/fastapi/discussions/categories/show-and-tell + url: https://github.com/fastapi/fastapi/discussions/categories/show-and-tell - name: Translations about: Coordinate translations in GitHub Discussions. - url: https://github.com/tiangolo/fastapi/discussions/categories/translations + url: https://github.com/fastapi/fastapi/discussions/categories/translations diff --git a/.github/ISSUE_TEMPLATE/privileged.yml b/.github/ISSUE_TEMPLATE/privileged.yml index c01e34b6d..2b85eb310 100644 --- a/.github/ISSUE_TEMPLATE/privileged.yml +++ b/.github/ISSUE_TEMPLATE/privileged.yml @@ -6,7 +6,7 @@ body: value: | Thanks for your interest in FastAPI! 🚀 - If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/fastapi/discussions/categories/questions) instead. + If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions) instead. - type: checkboxes id: privileged attributes: diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py index 9ded86da9..716232d49 100644 --- a/.github/actions/notify-translations/app/main.py +++ b/.github/actions/notify-translations/app/main.py @@ -19,7 +19,7 @@ questions_translations_category_id = "DIC_kwDOCZduT84CT5P9" all_discussions_query = """ query Q($category_id: ID) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { discussions(categoryId: $category_id, first: 100) { nodes { title @@ -41,7 +41,7 @@ query Q($category_id: ID) { translation_discussion_query = """ query Q($after: String, $discussion_number: Int!) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { discussion(number: $discussion_number) { comments(first: 100, after: $after) { edges { diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index 9f2b9369d..33156f1ca 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -17,7 +17,7 @@ questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0" discussions_query = """ query Q($after: String, $category_id: ID) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { discussions(first: 100, after: $after, categoryId: $category_id) { edges { cursor @@ -61,7 +61,7 @@ query Q($after: String, $category_id: ID) { prs_query = """ query Q($after: String) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { pullRequests(first: 100, after: $after) { edges { cursor @@ -109,7 +109,7 @@ query Q($after: String) { sponsors_query = """ query Q($after: String) { - user(login: "tiangolo") { + user(login: "fastapi") { sponsorshipsAsMaintainer(first: 100, after: $after) { edges { cursor diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index bd0113dc7..260902e12 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -16,7 +16,7 @@ on: jobs: issue-manager: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 417e19dad..63fb7ff23 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -7,7 +7,7 @@ on: jobs: label-approved: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml index b0868771d..c60c63d1b 100644 --- a/.github/workflows/people.yml +++ b/.github/workflows/people.yml @@ -12,7 +12,7 @@ on: jobs: fastapi-people: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context diff --git a/CITATION.cff b/CITATION.cff index 9028248b1..f14700349 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -12,7 +12,7 @@ authors: family-names: Ramírez email: tiangolo@gmail.com identifiers: -repository-code: 'https://github.com/tiangolo/fastapi' +repository-code: 'https://github.com/fastapi/fastapi' url: 'https://fastapi.tiangolo.com' abstract: >- FastAPI framework, high performance, easy to learn, fast to code, diff --git a/README.md b/README.md index c0422ead8..43cc7198c 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ <em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -23,7 +23,7 @@ **Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Source Code**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -72,7 +72,7 @@ The key features are: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md index 60494f191..9bb7ad6ea 100644 --- a/docs/az/docs/fastapi-people.md +++ b/docs/az/docs/fastapi-people.md @@ -91,7 +91,7 @@ Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstə </div> {% endif %} -Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Əməkdaşlar səhifəsində</a> görə bilərsiniz. 👷 +Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Əməkdaşlar səhifəsində</a> görə bilərsiniz. 👷 ## Ən çox rəy verənlər @@ -178,7 +178,7 @@ Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün g Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək. -Bu səhifənin məlumatları hər ay hesablanır və siz <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">buradan mənbə kodunu</a> oxuya bilərsiniz. +Bu səhifənin məlumatları hər ay hesablanır və siz <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">buradan mənbə kodunu</a> oxuya bilərsiniz. Burada sponsorların əməyini də vurğulamaq istəyirəm. diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index 430295d91..90864a98e 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -5,11 +5,11 @@ <em>FastAPI framework, yüksək məshuldarlı, öyrənməsi asan, çevik kodlama, istifadəyə hazırdır</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Əhatə"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Əhatə"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Paket versiyası"> @@ -23,7 +23,7 @@ **Sənədlər**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Qaynaq Kodu**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Qaynaq Kodu**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -63,7 +63,7 @@ FastAPI Python ilə API yaratmaq üçün standart Python <abbr title="Tip Məsl "_[...] Son günlərdə **FastAPI**-ı çox istifadə edirəm. [...] Əslində onu komandamın bütün **Microsoftda ML sevislərində** istifadə etməyi planlayıram. Onların bəziləri **windows**-un əsas məhsuluna və bəzi **Office** məhsullarına inteqrasiya olunurlar._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 3105e69c8..042cf9399 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -5,11 +5,11 @@ <em>FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক।</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -20,7 +20,7 @@ **নির্দেশিকা নথি**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**সোর্স কোড**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**সোর্স কোড**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -61,7 +61,7 @@ FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ "_আমি আজকাল **FastAPI** ব্যবহার করছি। [...] আমরা ভাবছি মাইক্রোসফ্টে **ML সার্ভিস** এ সকল দলের জন্য এটি ব্যবহার করব। যার মধ্যে কিছু পণ্য **Windows** এ সংযোযন হয় এবং কিছু **Office** এর সাথে সংযোযন হচ্ছে।_" -<div style="text-align: right; margin-right: 10%;">কবির খান - <strong>মাইক্রোসফ্টে</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">কবির খান - <strong>মাইক্রোসফ্টে</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md index 07a3c9a78..b1bd62496 100644 --- a/docs/de/docs/contributing.md +++ b/docs/de/docs/contributing.md @@ -4,7 +4,7 @@ Vielleicht möchten Sie sich zuerst die grundlegenden Möglichkeiten anschauen, ## Entwicklung -Wenn Sie das <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">fastapi Repository</a> bereits geklont haben und tief in den Code eintauchen möchten, hier einen Leitfaden zum Einrichten Ihrer Umgebung. +Wenn Sie das <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">fastapi Repository</a> bereits geklont haben und tief in den Code eintauchen möchten, hier einen Leitfaden zum Einrichten Ihrer Umgebung. ### Virtuelle Umgebung mit `venv` @@ -257,7 +257,7 @@ Hier sind die Schritte, die Ihnen bei Übersetzungen helfen. #### Tipps und Richtlinien -* Schauen Sie nach <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">aktuellen Pull Requests</a> 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 <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3Aawaiting-review" class="external-link" target="_blank">`lang-es`</a>. +* Schauen Sie nach <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">aktuellen Pull Requests</a> 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 <a href="https://github.com/fastapi/fastapi/pulls?q=is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3Aawaiting-review" class="external-link" target="_blank">`lang-es`</a>. * 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. @@ -266,7 +266,7 @@ Hier sind die Schritte, die Ihnen bei Übersetzungen helfen. Schauen Sie sich die Dokumentation an, <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">wie man ein Review zu einem Pull Request hinzufügt</a>, welches den PR absegnet oder Änderungen vorschlägt. -* Überprüfen Sie, ob es eine <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub-Diskussion</a> 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. +* Überprüfen Sie, ob es eine <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub-Diskussion</a> 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. diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md index d97f4d39c..1dfa70767 100644 --- a/docs/de/docs/external-links.md +++ b/docs/de/docs/external-links.md @@ -7,10 +7,10 @@ Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. Hier ist eine unvollständige Liste einiger davon. !!! tip "Tipp" - Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>. + Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>. !!! note "Hinweis Deutsche Übersetzung" - Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/tiangolo/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt. + Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt. {% for section_name, section_content in external_links.items() %} diff --git a/docs/de/docs/fastapi-people.md b/docs/de/docs/fastapi-people.md index 522a4bce5..deaecf214 100644 --- a/docs/de/docs/fastapi-people.md +++ b/docs/de/docs/fastapi-people.md @@ -89,7 +89,7 @@ Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦 </div> {% endif %} -Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors-Seite</a> sehen. 👷 +Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors-Seite</a> sehen. 👷 ## Top-Rezensenten @@ -169,7 +169,7 @@ Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen. -Diese Daten werden jeden Monat berechnet, Sie können den <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">Quellcode hier lesen</a>. +Diese Daten werden jeden Monat berechnet, Sie können den <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">Quellcode hier lesen</a>. Hier weise ich auch auf Beiträge von Sponsoren hin. diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md index bdc07e55f..d7d7b3359 100644 --- a/docs/de/docs/help-fastapi.md +++ b/docs/de/docs/help-fastapi.md @@ -25,13 +25,13 @@ Sie können den (unregelmäßig erscheinenden) [**FastAPI and Friends**-Newslett ## **FastAPI** auf GitHub einen Stern geben -Sie können FastAPI auf GitHub „starren“ (durch Klicken auf den Stern-Button oben rechts): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ +Sie können FastAPI auf GitHub „starren“ (durch Klicken auf den Stern-Button oben rechts): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. ⭐️ Durch das Hinzufügen eines Sterns können andere Benutzer es leichter finden und sehen, dass es für andere bereits nützlich war. ## Das GitHub-Repository auf Releases beobachten -Sie können FastAPI in GitHub beobachten (Klicken Sie oben rechts auf den Button „watch“): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Sie können FastAPI in GitHub beobachten (Klicken Sie oben rechts auf den Button „watch“): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Dort können Sie „Releases only“ auswählen. @@ -58,7 +58,7 @@ Insbesondere: ## Über **FastAPI** tweeten -<a href="https://twitter.com/compose/tweet?text=Ich liebe @fastapi, weil ... https://github.com/tiangolo/fastapi" class="external-link" target= "_blank">Tweeten Sie über **FastAPI**</a> und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉 +<a href="https://twitter.com/compose/tweet?text=Ich liebe @fastapi, weil ... https://github.com/fastapi/fastapi" class="external-link" target= "_blank">Tweeten Sie über **FastAPI**</a> und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉 Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, in welchem Projekt/Unternehmen Sie es verwenden, usw. @@ -72,8 +72,8 @@ Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, i Sie können versuchen, anderen bei ihren Fragen zu helfen: -* <a href="https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub-Diskussionen</a> -* <a href="https://github.com/tiangolo/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub-Issues</a> +* <a href="https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub-Diskussionen</a> +* <a href="https://github.com/fastapi/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub-Issues</a> In vielen Fällen kennen Sie möglicherweise bereits die Antwort auf diese Fragen. 🤓 @@ -124,7 +124,7 @@ Wenn die Person antwortet, besteht eine hohe Chance, dass Sie ihr Problem gelös ## Das GitHub-Repository beobachten -Sie können FastAPI auf GitHub „beobachten“ (Klicken Sie oben rechts auf die Schaltfläche „watch“): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank" >https://github.com/tiangolo/fastapi</a>. 👀 +Sie können FastAPI auf GitHub „beobachten“ (Klicken Sie oben rechts auf die Schaltfläche „watch“): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank" >https://github.com/fastapi/fastapi</a>. 👀 Wenn Sie dann „Watching“ statt „Releases only“ auswählen, erhalten Sie Benachrichtigungen, wenn jemand ein neues Issue eröffnet oder eine neue Frage stellt. Sie können auch spezifizieren, dass Sie nur über neue Issues, Diskussionen, PRs, usw. benachrichtigt werden möchten. @@ -132,7 +132,7 @@ Dann können Sie versuchen, bei der Lösung solcher Fragen zu helfen. ## Fragen stellen -Sie können im GitHub-Repository <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">eine neue Frage erstellen</a>, zum Beispiel: +Sie können im GitHub-Repository <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">eine neue Frage erstellen</a>, zum Beispiel: * Stellen Sie eine **Frage** oder bitten Sie um Hilfe mit einem **Problem**. * Schlagen Sie eine neue **Funktionalität** vor. @@ -195,7 +195,7 @@ Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich dir Sie können zum Quellcode mit Pull Requests [beitragen](contributing.md){.internal-link target=_blank}, zum Beispiel: * Um einen Tippfehler zu beheben, den Sie in der Dokumentation gefunden haben. -* Um einen Artikel, ein Video oder einen Podcast über FastAPI zu teilen, den Sie erstellt oder gefunden haben, indem Sie <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">diese Datei bearbeiten</a>. +* Um einen Artikel, ein Video oder einen Podcast über FastAPI zu teilen, den Sie erstellt oder gefunden haben, indem Sie <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">diese Datei bearbeiten</a>. * Stellen Sie sicher, dass Sie Ihren Link am Anfang des entsprechenden Abschnitts einfügen. * Um zu helfen, [die Dokumentation in Ihre Sprache zu übersetzen](contributing.md#ubersetzungen){.internal-link target=_blank}. * Sie können auch dabei helfen, die von anderen erstellten Übersetzungen zu überprüfen (Review). @@ -226,7 +226,7 @@ Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalt Treten Sie dem 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord-Chatserver</a> 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. !!! tip "Tipp" - Wenn Sie Fragen haben, stellen Sie sie bei <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Diskussionen</a>, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. + Wenn Sie Fragen haben, stellen Sie sie bei <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Diskussionen</a>, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. Nutzen Sie den Chat nur für andere allgemeine Gespräche. diff --git a/docs/de/docs/history-design-future.md b/docs/de/docs/history-design-future.md index 22597b1f5..ee917608e 100644 --- a/docs/de/docs/history-design-future.md +++ b/docs/de/docs/history-design-future.md @@ -1,6 +1,6 @@ # Geschichte, Design und Zukunft -Vor einiger Zeit fragte <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">ein **FastAPI**-Benutzer</a>: +Vor einiger Zeit fragte <a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">ein **FastAPI**-Benutzer</a>: > Was ist die Geschichte dieses Projekts? Es scheint, als wäre es in ein paar Wochen aus dem Nichts zu etwas Großartigem geworden [...] diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index e3c5be321..3789c5998 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI Framework, hochperformant, leicht zu erlernen, schnell zu programmieren, einsatzbereit</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package-Version"> @@ -29,7 +29,7 @@ **Dokumentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Quellcode**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Quellcode**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -70,7 +70,7 @@ Seine Schlüssel-Merkmale sind: „_[...] Ich verwende **FastAPI** heutzutage sehr oft. [...] Ich habe tatsächlich vor, es für alle **ML-Dienste meines Teams bei Microsoft** zu verwenden. Einige davon werden in das Kernprodukt **Windows** und einige **Office**-Produkte integriert._“ -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(Ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(Ref)</small></a></div> --- diff --git a/docs/de/docs/project-generation.md b/docs/de/docs/project-generation.md index c1ae6512d..c47bcb6d3 100644 --- a/docs/de/docs/project-generation.md +++ b/docs/de/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" clas * Docker-Schwarmmodus-Deployment. * **Docker Compose**-Integration und Optimierung für die lokale Entwicklung. * **Produktionsbereit** Python-Webserver, verwendet Uvicorn und Gunicorn. -* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a>-Backend: +* Python <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a>-Backend: * **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (dank Starlette und Pydantic). * **Intuitiv**: Hervorragende Editor-Unterstützung. <abbr title="Auch bekannt als automatische Vervollständigung, IntelliSense">Codevervollständigung</abbr> überall. Weniger Zeitaufwand für das Debuggen. * **Einfach**: Einfach zu bedienen und zu erlernen. Weniger Zeit für das Lesen von Dokumentationen. diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md index 748928f88..08561d8f8 100644 --- a/docs/em/docs/contributing.md +++ b/docs/em/docs/contributing.md @@ -233,14 +233,14 @@ Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. #### 💁♂ & 📄 -* ✅ ⏳ <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">♻ 🚲 📨</a> 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫. +* ✅ ⏳ <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">♻ 🚲 📨</a> 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫. !!! tip 👆 💪 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">🚮 🏤 ⏮️ 🔀 🔑</a> ♻ 🚲 📨. ✅ 🩺 🔃 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">❎ 🚲 📨 📄</a> ✔ ⚫️ ⚖️ 📨 🔀. -* ✅ <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">❔</a> 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸. +* ✅ <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">❔</a> 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸. * 🚮 👁 🚲 📨 📍 📃 💬. 👈 🔜 ⚒ ⚫️ 🌅 ⏩ 🎏 📄 ⚫️. diff --git a/docs/em/docs/external-links.md b/docs/em/docs/external-links.md index 5ba668bfa..08db2d4c1 100644 --- a/docs/em/docs/external-links.md +++ b/docs/em/docs/external-links.md @@ -7,7 +7,7 @@ 📥 ❌ 📇 👫. !!! tip - 🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>. + 🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>. ## 📄 diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md index d3c7d2038..75880e216 100644 --- a/docs/em/docs/fastapi-people.md +++ b/docs/em/docs/fastapi-people.md @@ -89,7 +89,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. </div> {% endif %} -📤 📚 🎏 👨🔬 (🌅 🌘 💯), 👆 💪 👀 👫 🌐 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI 📂 👨🔬 📃</a>. 👶 +📤 📚 🎏 👨🔬 (🌅 🌘 💯), 👆 💪 👀 👫 🌐 <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI 📂 👨🔬 📃</a>. 👶 ## 🔝 👨🔬 @@ -176,7 +176,7 @@ FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. ✴️ ✅ 🎯 👈 🛎 🌘 ⭐, & 📚 💼 🌅 😩, 💖 🤝 🎏 ⏮️ ❔ & ⚖ 🚲 📨 ⏮️ ✍. -💽 ⚖ 🔠 🗓️, 👆 💪 ✍ <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">ℹ 📟 📥</a>. +💽 ⚖ 🔠 🗓️, 👆 💪 ✍ <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">ℹ 📟 📥</a>. 📥 👤 🎦 💰 ⚪️➡️ 💰. diff --git a/docs/em/docs/help-fastapi.md b/docs/em/docs/help-fastapi.md index fbb9ca9a9..4a285062d 100644 --- a/docs/em/docs/help-fastapi.md +++ b/docs/em/docs/help-fastapi.md @@ -26,13 +26,13 @@ ## ✴ **FastAPI** 📂 -👆 💪 "✴" FastAPI 📂 (🖊 ✴ 🔼 🔝 ▶️️): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👶 👶 +👆 💪 "✴" FastAPI 📂 (🖊 ✴ 🔼 🔝 ▶️️): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👶 👶 ❎ ✴, 🎏 👩💻 🔜 💪 🔎 ⚫️ 🌅 💪 & 👀 👈 ⚫️ ✔️ ⏪ ⚠ 🎏. ## ⌚ 📂 🗃 🚀 -👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👶 +👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👶 📤 👆 💪 🖊 "🚀 🕴". @@ -59,7 +59,7 @@ ## 👱📔 🔃 **FastAPI** -<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">👱📔 🔃 **FastAPI**</a> & ➡️ 👤 & 🎏 💭 ⚫️❔ 👆 💖 ⚫️. 👶 +<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi" class="external-link" target="_blank">👱📔 🔃 **FastAPI**</a> & ➡️ 👤 & 🎏 💭 ⚫️❔ 👆 💖 ⚫️. 👶 👤 💌 👂 🔃 ❔ **FastAPI** 💆♂ ⚙️, ⚫️❔ 👆 ✔️ 💖 ⚫️, ❔ 🏗/🏢 👆 ⚙️ ⚫️, ♒️. @@ -73,8 +73,8 @@ 👆 💪 🔄 & ℹ 🎏 ⏮️ 👫 ❔: -* <a href="https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">📂 💬</a> -* <a href="https://github.com/tiangolo/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">📂 ❔</a> +* <a href="https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">📂 💬</a> +* <a href="https://github.com/fastapi/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">📂 ❔</a> 📚 💼 👆 5️⃣📆 ⏪ 💭 ❔ 📚 ❔. 👶 @@ -125,7 +125,7 @@ ## ⌚ 📂 🗃 -👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👶 +👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👶 🚥 👆 🖊 "👀" ↩️ "🚀 🕴" 👆 🔜 📨 📨 🕐❔ 👱 ✍ 🆕 ❔ ⚖️ ❔. 👆 💪 ✔ 👈 👆 🕴 💚 🚨 🔃 🆕 ❔, ⚖️ 💬, ⚖️ 🎸, ♒️. @@ -133,7 +133,7 @@ ## 💭 ❔ -👆 💪 <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">✍ 🆕 ❔</a> 📂 🗃, 🖼: +👆 💪 <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">✍ 🆕 ❔</a> 📂 🗃, 🖼: * 💭 **❔** ⚖️ 💭 🔃 **⚠**. * 🤔 🆕 **⚒**. @@ -196,7 +196,7 @@ 👆 💪 [📉](contributing.md){.internal-link target=_blank} ℹ 📟 ⏮️ 🚲 📨, 🖼: * 🔧 🤭 👆 🔎 🔛 🧾. -* 💰 📄, 📹, ⚖️ 📻 👆 ✍ ⚖️ 🔎 🔃 FastAPI <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">✍ 👉 📁</a>. +* 💰 📄, 📹, ⚖️ 📻 👆 ✍ ⚖️ 🔎 🔃 FastAPI <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">✍ 👉 📁</a>. * ⚒ 💭 👆 🚮 👆 🔗 ▶️ 🔗 📄. * ℹ [💬 🧾](contributing.md#_9){.internal-link target=_blank} 👆 🇪🇸. * 👆 💪 ℹ 📄 ✍ ✍ 🎏. @@ -227,7 +227,7 @@ 🛑 👶 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">😧 💬 💽</a> 👶 & 🤙 👅 ⏮️ 🎏 FastAPI 👪. !!! tip - ❔, 💭 👫 <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. + ❔, 💭 👫 <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. ⚙️ 💬 🕴 🎏 🏢 💬. diff --git a/docs/em/docs/history-design-future.md b/docs/em/docs/history-design-future.md index 7a45fe14b..2238bec2b 100644 --- a/docs/em/docs/history-design-future.md +++ b/docs/em/docs/history-design-future.md @@ -1,6 +1,6 @@ # 📖, 🔧 & 🔮 -🕰 🏁, <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank"> **FastAPI** 👩💻 💭</a>: +🕰 🏁, <a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank"> **FastAPI** 👩💻 💭</a>: > ⚫️❔ 📖 👉 🏗 ❓ ⚫️ 😑 ✔️ 👟 ⚪️➡️ 🕳 👌 👩❤👨 🗓️ [...] diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index 0b5cca86f..a7d1d06f9 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI 🛠️, ↕ 🎭, ⏩ 💡, ⏩ 📟, 🔜 🏭</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **🧾**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**ℹ 📟**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**ℹ 📟**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -69,7 +69,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ "_[...] 👤 ⚙️ **FastAPI** 📚 👫 📆. [...] 👤 🤙 📆 ⚙️ ⚫️ 🌐 👇 🏉 **⚗ 🐕🦺 🤸♂**. 👫 💆♂ 🛠️ 🔘 🐚 **🖥** 🏬 & **📠** 🏬._" -<div style="text-align: right; margin-right: 10%;">🧿 🇵🇰 - <strong>🤸♂</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(🇦🇪)</small></a></div> +<div style="text-align: right; margin-right: 10%;">🧿 🇵🇰 - <strong>🤸♂</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(🇦🇪)</small></a></div> --- diff --git a/docs/em/docs/project-generation.md b/docs/em/docs/project-generation.md index ae959e1d5..ef6a21821 100644 --- a/docs/em/docs/project-generation.md +++ b/docs/em/docs/project-generation.md @@ -14,7 +14,7 @@ * ☁ 🐝 📳 🛠️. * **☁ ✍** 🛠️ & 🛠️ 🇧🇿 🛠️. * **🏭 🔜** 🐍 🕸 💽 ⚙️ Uvicorn & 🐁. -* 🐍 <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> 👩💻: +* 🐍 <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a> 👩💻: * **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). * **🏋️**: 👑 👨🎨 🐕🦺. <abbr title="also known as auto-complete, autocompletion, IntelliSense">🛠️</abbr> 🌐. 🌘 🕰 🛠️. * **⏩**: 🔧 ⏩ ⚙️ & 💡. 🌘 🕰 👂 🩺. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 2d308a9db..d7ec25dea 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -4,7 +4,7 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- ## Developing -If you already cloned the <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">fastapi repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment. +If you already cloned the <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">fastapi repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment. ### Virtual environment with `venv` @@ -257,7 +257,7 @@ Here are the steps to help with translations. #### Tips and guidelines -* Check the currently <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">existing pull requests</a> for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3Aawaiting-review" class="external-link" target="_blank">`lang-es`</a>. +* Check the currently <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">existing pull requests</a> for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is <a href="https://github.com/fastapi/fastapi/pulls?q=is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3Aawaiting-review" class="external-link" target="_blank">`lang-es`</a>. * Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. @@ -266,7 +266,7 @@ Here are the steps to help with translations. Check the docs about <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adding a pull request review</a> to approve it or request changes. -* Check if there's a <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. +* Check if there's a <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. * If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it. diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index b89021ee2..1a36390f5 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -7,7 +7,7 @@ There are many posts, articles, tools, and projects, related to **FastAPI**. Here's an incomplete list of some of them. !!! tip - If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request adding it</a>. + If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request adding it</a>. {% for section_name, section_content in external_links.items() %} diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index 80eee8cb0..c9fcc3866 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -167,7 +167,7 @@ They have contributed source code, documentation, translations, etc. 📦 </div> {% endif %} -There are many other contributors (more than a hundred), you can see them all in the <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors page</a>. 👷 +There are many other contributors (more than a hundred), you can see them all in the <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors page</a>. 👷 ## Top Translation Reviewers @@ -248,7 +248,7 @@ The main intention of this page is to highlight the effort of the community to h Especially including efforts that are normally less visible, and in many cases more arduous, like helping others with questions and reviewing Pull Requests with translations. -The data is calculated each month, you can read the <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">source code here</a>. +The data is calculated each month, you can read the <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">source code here</a>. Here I'm also highlighting contributions from sponsors. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 121447739..ab2dff39b 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -26,13 +26,13 @@ You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](newsl ## Star **FastAPI** in GitHub -You can "star" FastAPI in GitHub (clicking the star button at the top right): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ +You can "star" FastAPI in GitHub (clicking the star button at the top right): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. ⭐️ By adding a star, other users will be able to find it more easily and see that it has been already useful for others. ## Watch the GitHub repository for releases -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 There you can select "Releases only". @@ -59,7 +59,7 @@ You can: ## Tweet about **FastAPI** -<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">Tweet about **FastAPI**</a> and let me and others know why you like it. 🎉 +<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi" class="external-link" target="_blank">Tweet about **FastAPI**</a> and let me and others know why you like it. 🎉 I love to hear about how **FastAPI** is being used, what you have liked in it, in which project/company are you using it, etc. @@ -73,8 +73,8 @@ I love to hear about how **FastAPI** is being used, what you have liked in it, i You can try and help others with their questions in: -* <a href="https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub Discussions</a> -* <a href="https://github.com/tiangolo/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub Issues</a> +* <a href="https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub Discussions</a> +* <a href="https://github.com/fastapi/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub Issues</a> In many cases you might already know the answer for those questions. 🤓 @@ -125,7 +125,7 @@ If they reply, there's a high chance you would have solved their problem, congra ## Watch the GitHub repository -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue or question. You can also specify that you only want to be notified about new issues, or discussions, or PRs, etc. @@ -133,7 +133,7 @@ Then you can try and help them solve those questions. ## Ask Questions -You can <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">create a new question</a> in the GitHub repository, for example to: +You can <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">create a new question</a> in the GitHub repository, for example to: * Ask a **question** or ask about a **problem**. * Suggest a new **feature**. @@ -196,7 +196,7 @@ And if there's any other style or consistency need, I'll ask directly for that, You can [contribute](contributing.md){.internal-link target=_blank} to the source code with Pull Requests, for example: * To fix a typo you found on the documentation. -* To share an article, video, or podcast you created or found about FastAPI by <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">editing this file</a>. +* To share an article, video, or podcast you created or found about FastAPI by <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">editing this file</a>. * Make sure you add your link to the start of the corresponding section. * To help [translate the documentation](contributing.md#translations){.internal-link target=_blank} to your language. * You can also help to review the translations created by others. @@ -227,7 +227,7 @@ If you can help me with that, **you are helping me maintain FastAPI** and making Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord chat server</a> 👥 and hang out with others in the FastAPI community. !!! tip - For questions, ask them in <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + For questions, ask them in <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. Use the chat only for other general conversations. diff --git a/docs/en/docs/history-design-future.md b/docs/en/docs/history-design-future.md index 7824fb080..b4a744d64 100644 --- a/docs/en/docs/history-design-future.md +++ b/docs/en/docs/history-design-future.md @@ -1,6 +1,6 @@ # History, Design and Future -Some time ago, <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">a **FastAPI** user asked</a>: +Some time ago, <a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">a **FastAPI** user asked</a>: > What’s the history of this project? It seems to have come from nowhere to awesome in a few weeks [...] diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 75f27d04f..73357542f 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Source Code**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -69,7 +69,7 @@ The key features are: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js index 0008db49e..b7e5236f3 100644 --- a/docs/en/docs/js/custom.js +++ b/docs/en/docs/js/custom.js @@ -163,7 +163,7 @@ async function main() { div.innerHTML = '<ul></ul>' const ul = document.querySelector('.github-topic-projects ul') data.forEach(v => { - if (v.full_name === 'tiangolo/fastapi') { + if (v.full_name === 'fastapi/fastapi') { return } const li = document.createElement('li') diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index 231dbe24d..efda1a703 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -173,11 +173,11 @@ INHERIT: ../en/mkdocs.yml The language code would normally be in the <a href="https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes" class="external-link" target="_blank">ISO 639-1 list of language codes</a>. -In any case, the language code should be in the file <a href="https://github.com/tiangolo/fastapi/blob/master/docs/language_names.yml" class="external-link" target="_blank">docs/language_names.yml</a>. +In any case, the language code should be in the file <a href="https://github.com/fastapi/fastapi/blob/master/docs/language_names.yml" class="external-link" target="_blank">docs/language_names.yml</a>. There won't be yet a label for the language code, for example, if it was Bosnian, there wouldn't be a `lang-bs`. Before creating the label and adding it to the PR, create the GitHub Discussion: -* Go to the <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">Translations GitHub Discussions</a> +* Go to the <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">Translations GitHub Discussions</a> * Create a new discussion with the title `Bosnian Translations` (or the language name in English) * A description of: @@ -186,7 +186,7 @@ There won't be yet a label for the language code, for example, if it was Bosnian This is the issue to track translations of the docs to Bosnian. 🚀 -Here are the [PRs to review with the label `lang-bs`](https://github.com/tiangolo/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-bs+label%3A%22awaiting-review%22). 🤓 +Here are the [PRs to review with the label `lang-bs`](https://github.com/fastapi/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-bs+label%3A%22awaiting-review%22). 🤓 ``` Update "Bosnian" with the new language. @@ -219,13 +219,13 @@ A PR should have a specific use case that it is solving. ## FastAPI People PRs -Every month, a GitHub Action updates the FastAPI People data. Those PRs look like this one: <a href="https://github.com/tiangolo/fastapi/pull/11669" class="external-link" target="_blank">👥 Update FastAPI People</a>. +Every month, a GitHub Action updates the FastAPI People data. Those PRs look like this one: <a href="https://github.com/fastapi/fastapi/pull/11669" class="external-link" target="_blank">👥 Update FastAPI People</a>. If the tests are passing, you can merge it right away. ## External Links PRs -When people add external links they edit this file <a href="https://github.com/tiangolo/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">external_links.yml</a>. +When people add external links they edit this file <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">external_links.yml</a>. * Make sure the new link is in the correct category (e.g. "Podcasts") and language (e.g. "Japanese"). * A new link should be at the top of its list. @@ -251,6 +251,6 @@ When a question in GitHub Discussions has been answered, mark the answer by clic Many of the current Discussion Questions were migrated from old issues. Many have the label `answered`, that means they were answered when they were issues, but now in GitHub Discussions, it's not known what is the actual response from the messages. -You can filter discussions by [`Questions` that are `Unanswered` and have the label `answered`](https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aopen+label%3Aanswered+is%3Aunanswered). +You can filter discussions by [`Questions` that are `Unanswered` and have the label `answered`](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aopen+label%3Aanswered+is%3Aunanswered). All of those discussions already have an answer in the conversation, you can find it and mark it with the "Mark as answer" button. diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 81baa051a..c13e36798 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -36,8 +36,8 @@ theme: logo: img/icon-white.svg favicon: img/favicon.png language: en -repo_name: tiangolo/fastapi -repo_url: https://github.com/tiangolo/fastapi +repo_name: fastapi/fastapi +repo_url: https://github.com/fastapi/fastapi edit_uri: '' plugins: search: null @@ -259,7 +259,7 @@ extra: property: G-YNEVN69SC3 social: - icon: fontawesome/brands/github-alt - link: https://github.com/tiangolo/fastapi + link: https://github.com/fastapi/fastapi - icon: fontawesome/brands/discord link: https://discord.gg/VQjSZaeJmf - icon: fontawesome/brands/twitter diff --git a/docs/es/docs/external-links.md b/docs/es/docs/external-links.md index cfbdd68a6..481f72e9e 100644 --- a/docs/es/docs/external-links.md +++ b/docs/es/docs/external-links.md @@ -7,7 +7,7 @@ Hay muchas publicaciones, artículos, herramientas y proyectos relacionados con Aquí hay una lista incompleta de algunos de ellos. !!! tip "Consejo" - Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request agregándolo</a>. + Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request agregándolo</a>. {% for section_name, section_content in external_links.items() %} diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 733e4664e..2b6a2f0be 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -26,7 +26,7 @@ **Documentación**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Código Fuente**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Código Fuente**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python basado en las anotaciones de tipos estándar de Python. @@ -66,7 +66,7 @@ Sus características principales son: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index ea8063129..bc8b77941 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -11,11 +11,11 @@ <em>فریمورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **مستندات**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**کد منبع**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**کد منبع**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- FastAPI یک وب فریمورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وبسوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریمورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است. @@ -66,7 +66,7 @@ FastAPI یک وب فریمورک مدرن و سریع (با کارایی با <div style="text-align: left; direction: ltr;"><em> [...] I'm using <strong>FastAPI</strong> a ton these days. [...] I'm actually planning to use it for all of my team's <strong>ML services at Microsoft</strong>. Some of them are getting integrated into the core <strong>Windows</strong> product and some <strong>Office</strong> products."</em></div> -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md index 8292f14bb..ed4d32f5a 100644 --- a/docs/fr/docs/contributing.md +++ b/docs/fr/docs/contributing.md @@ -269,14 +269,14 @@ Voici les étapes à suivre pour aider à la traduction. #### Conseils et lignes directrices -* Vérifiez les <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">pull requests existantes</a> pour votre langue et ajouter des reviews demandant des changements ou les approuvant. +* Vérifiez les <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">pull requests existantes</a> pour votre langue et ajouter des reviews demandant des changements ou les approuvant. !!! tip Vous pouvez <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">ajouter des commentaires avec des suggestions de changement</a> aux pull requests existantes. Consultez les documents concernant <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">l'ajout d'un review de pull request</a> pour l'approuver ou demander des modifications. -* Vérifiez dans <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">issues</a> pour voir s'il y a une personne qui coordonne les traductions pour votre langue. +* Vérifiez dans <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">issues</a> 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. diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md index 37b8c5b13..2f928f523 100644 --- a/docs/fr/docs/external-links.md +++ b/docs/fr/docs/external-links.md @@ -7,7 +7,7 @@ Il existe de nombreux articles, outils et projets liés à **FastAPI**. Voici une liste incomplète de certains d'entre eux. !!! tip "Astuce" - Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>. + Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>. {% for section_name, section_content in external_links.items() %} diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md index d99dcd9c2..52a79032a 100644 --- a/docs/fr/docs/fastapi-people.md +++ b/docs/fr/docs/fastapi-people.md @@ -89,7 +89,7 @@ Ils ont contribué au code source, à la documentation, aux traductions, etc. </div> {% endif %} -Il existe de nombreux autres contributeurs (plus d'une centaine), vous pouvez les voir tous dans la <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">Page des contributeurs de FastAPI GitHub</a>. 👷 +Il existe de nombreux autres contributeurs (plus d'une centaine), vous pouvez les voir tous dans la <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">Page des contributeurs de FastAPI GitHub</a>. 👷 ## Principaux Reviewers @@ -175,6 +175,6 @@ L'intention de cette page est de souligner l'effort de la communauté pour aider Notamment en incluant des efforts qui sont normalement moins visibles, et, dans de nombreux cas, plus difficile, comme aider d'autres personnes à résoudre des problèmes et examiner les Pull Requests de traduction. -Les données sont calculées chaque mois, vous pouvez lire le <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">code source ici</a>. +Les données sont calculées chaque mois, vous pouvez lire le <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">code source ici</a>. Je me réserve également le droit de mettre à jour l'algorithme, les sections, les seuils, etc. (juste au cas où 🤷). diff --git a/docs/fr/docs/help-fastapi.md b/docs/fr/docs/help-fastapi.md index 525c699f5..a365a8d3a 100644 --- a/docs/fr/docs/help-fastapi.md +++ b/docs/fr/docs/help-fastapi.md @@ -12,13 +12,13 @@ Il existe également plusieurs façons d'obtenir de l'aide. ## Star **FastAPI** sur GitHub -Vous pouvez "star" FastAPI dans GitHub (en cliquant sur le bouton étoile en haut à droite) : <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ +Vous pouvez "star" FastAPI dans GitHub (en cliquant sur le bouton étoile en haut à droite) : <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. ⭐️ En ajoutant une étoile, les autres utilisateurs pourront la trouver plus facilement et constater qu'elle a déjà été utile à d'autres. ## Watch le dépôt GitHub pour les releases -Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Vous pouvez y sélectionner "Releases only". @@ -44,7 +44,7 @@ Vous pouvez : ## Tweeter sur **FastAPI** -<a href="https://twitter.com/compose/tweet?text=I'm loving FastAPI because... https://github.com/tiangolo/fastapi cc @tiangolo" class="external-link" target="_blank">Tweetez à propos de **FastAPI**</a> et faites-moi savoir, ainsi qu'aux autres, pourquoi vous aimez ça. 🎉 +<a href="https://twitter.com/compose/tweet?text=I'm loving FastAPI because... https://github.com/fastapi/fastapi cc @tiangolo" class="external-link" target="_blank">Tweetez à propos de **FastAPI**</a> et faites-moi savoir, ainsi qu'aux autres, pourquoi vous aimez ça. 🎉 J'aime entendre parler de l'utilisation du **FastAPI**, de ce que vous avez aimé dedans, dans quel projet/entreprise l'utilisez-vous, etc. @@ -56,11 +56,11 @@ J'aime entendre parler de l'utilisation du **FastAPI**, de ce que vous avez aim ## Aider les autres à résoudre les problèmes dans GitHub -Vous pouvez voir <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">les problèmes existants</a> et essayer d'aider les autres, la plupart du temps il s'agit de questions dont vous connaissez peut-être déjà la réponse. 🤓 +Vous pouvez voir <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">les problèmes existants</a> et essayer d'aider les autres, la plupart du temps il s'agit de questions dont vous connaissez peut-être déjà la réponse. 🤓 ## Watch le dépôt GitHub -Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Si vous sélectionnez "Watching" au lieu de "Releases only", vous recevrez des notifications lorsque quelqu'un crée une nouvelle Issue. @@ -68,7 +68,7 @@ Vous pouvez alors essayer de les aider à résoudre ces problèmes. ## Créer une Issue -Vous pouvez <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">créer une Issue</a> dans le dépôt GitHub, par exemple pour : +Vous pouvez <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">créer une Issue</a> dans le dépôt GitHub, par exemple pour : * Poser une question ou s'informer sur un problème. * Suggérer une nouvelle fonctionnalité. @@ -77,7 +77,7 @@ Vous pouvez <a href="https://github.com/tiangolo/fastapi/issues/new/choose" clas ## Créer une Pull Request -Vous pouvez <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">créer une Pull Request</a>, par exemple : +Vous pouvez <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">créer une Pull Request</a>, par exemple : * Pour corriger une faute de frappe que vous avez trouvée sur la documentation. * Proposer de nouvelles sections de documentation. diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md index beb649121..6b26dd079 100644 --- a/docs/fr/docs/history-design-future.md +++ b/docs/fr/docs/history-design-future.md @@ -1,6 +1,6 @@ # Histoire, conception et avenir -Il y a quelque temps, <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">un utilisateur de **FastAPI** a demandé</a> : +Il y a quelque temps, <a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">un utilisateur de **FastAPI** a demandé</a> : > Quelle est l'histoire de ce projet ? Il semble être sorti de nulle part et est devenu génial en quelques semaines [...]. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 5b0ba142e..927c0c643 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -11,11 +11,11 @@ <em>Framework FastAPI, haute performance, facile à apprendre, rapide à coder, prêt pour la production</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **Documentation** : <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Code Source** : <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Code Source** : <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -69,7 +69,7 @@ Les principales fonctionnalités sont : "_[...] J'utilise beaucoup **FastAPI** ces derniers temps. [...] Je prévois de l'utiliser dans mon équipe pour tous les **services de ML chez Microsoft**. Certains d'entre eux seront intégrés dans le coeur de **Windows** et dans certains produits **Office**._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/fr/docs/project-generation.md b/docs/fr/docs/project-generation.md index c58d2cd2b..4c04dc167 100644 --- a/docs/fr/docs/project-generation.md +++ b/docs/fr/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub : <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" cla * Déploiement Docker en mode <a href="https://docs.docker.com/engine/swarm/" class="external-link" target="_blank">Swarm</a> * Intégration **Docker Compose** et optimisation pour développement local. * Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn. -* Backend Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> : +* Backend Python <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a> : * **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic). * **Intuitif** : Excellent support des éditeurs. <abbr title="aussi appelée auto-complétion, autocomplétion, IntelliSense...">Complétion</abbr> partout. Moins de temps passé à déboguer. * **Facile** : Fait pour être facile à utiliser et apprendre. Moins de temps passé à lire de la documentation. diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 6af8e3217..3af166ab0 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -11,11 +11,11 @@ <em>תשתית FastAPI, ביצועים גבוהים, קלה ללמידה, מהירה לתכנות, מוכנה לסביבת ייצור</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **תיעוד**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**קוד**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**קוד**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -70,7 +70,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 671b0477f..b7231ad56 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -5,11 +5,11 @@ <em>FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -23,7 +23,7 @@ **Dokumentáció**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Forrás kód**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Forrás kód**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python -al, a Python szabványos típusjelöléseire építve. @@ -63,7 +63,7 @@ Kulcs funkciók: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 016316a64..38f611734 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -9,11 +9,11 @@ <em>FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione</em> </p> <p align="center"> -<a href="https://travis-ci.com/tiangolo/fastapi" target="_blank"> - <img src="https://travis-ci.com/tiangolo/fastapi.svg?branch=master" alt="Build Status"> +<a href="https://travis-ci.com/fastapi/fastapi" target="_blank"> + <img src="https://travis-ci.com/fastapi/fastapi.svg?branch=master" alt="Build Status"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://badge.fury.io/py/fastapi.svg" alt="Package version"> @@ -24,7 +24,7 @@ **Documentazione**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Codice Sorgente**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Codice Sorgente**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -64,7 +64,7 @@ Le sue caratteristiche principali sono: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md index 31db51c52..be8e9280e 100644 --- a/docs/ja/docs/contributing.md +++ b/docs/ja/docs/contributing.md @@ -236,14 +236,14 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 #### 豆知識とガイドライン -* あなたの言語の<a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">今あるプルリクエスト</a>を確認し、変更や承認をするレビューを追加します。 +* あなたの言語の<a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">今あるプルリクエスト</a>を確認し、変更や承認をするレビューを追加します。 !!! tip "豆知識" すでにあるプルリクエストに<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">修正提案つきのコメントを追加</a>できます。 修正提案の承認のために<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">プルリクエストのレビューの追加</a>のドキュメントを確認してください。 -* <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">issues</a>をチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 +* <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">issues</a>をチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 * 翻訳したページごとに1つのプルリクエストを追加します。これにより、他のユーザーがレビューしやすくなります。 diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md index aca5d5b34..4cd15c8aa 100644 --- a/docs/ja/docs/external-links.md +++ b/docs/ja/docs/external-links.md @@ -7,7 +7,7 @@ それらの不完全なリストを以下に示します。 !!! tip "豆知識" - ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">プルリクエストして下さい</a>。 + ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">プルリクエストして下さい</a>。 {% for section_name, section_content in external_links.items() %} diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md index d92a7bf46..aaf76ba21 100644 --- a/docs/ja/docs/fastapi-people.md +++ b/docs/ja/docs/fastapi-people.md @@ -90,7 +90,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 </div> {% endif %} -他にもたくさん (100人以上) の contributors がいます。<a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors ページ</a>ですべての contributors を確認できます。👷 +他にもたくさん (100人以上) の contributors がいます。<a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors ページ</a>ですべての contributors を確認できます。👷 ## Top Reviewers @@ -177,7 +177,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴 特に、他の人の issues を支援したり、翻訳のプルリクエストを確認したりするなど、通常は目立たず、多くの場合、より困難な作業を含みます。 -データは毎月集計されます。<a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">ソースコードはこちら</a>で確認できます。 +データは毎月集計されます。<a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">ソースコードはこちら</a>で確認できます。 ここでは、スポンサーの貢献も強調しています。 diff --git a/docs/ja/docs/help-fastapi.md b/docs/ja/docs/help-fastapi.md index e753b7ce3..d999fa127 100644 --- a/docs/ja/docs/help-fastapi.md +++ b/docs/ja/docs/help-fastapi.md @@ -12,13 +12,13 @@ FastAPIやユーザーや開発者を応援したいですか? ## GitHubで **FastAPI** にStar -GitHubでFastAPIに「Star」をつけることができます (右上部のStarボタンをクリック): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ +GitHubでFastAPIに「Star」をつけることができます (右上部のStarボタンをクリック): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. ⭐️ スターを増やすことで、他のユーザーの目につきやすくなり、多くの人にとって便利なものであることを示せます。 ## GitHubレポジトリのリリースをWatch -GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリック): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリック): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 そこで「Releases only」を選択できます。 @@ -42,7 +42,7 @@ GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリ ## **FastAPI** に関するツイート -<a href="https://twitter.com/compose/tweet?text=I'm loving FastAPI because... https://github.com/tiangolo/fastapi cc @tiangolo" class="external-link" target="_blank">**FastAPI** についてツイート</a>し、開発者や他の人にどこが気に入ったのか教えてください。🎉 +<a href="https://twitter.com/compose/tweet?text=I'm loving FastAPI because... https://github.com/fastapi/fastapi cc @tiangolo" class="external-link" target="_blank">**FastAPI** についてツイート</a>し、開発者や他の人にどこが気に入ったのか教えてください。🎉 **FastAPI** がどのように使われ、どこが気に入られ、どんなプロジェクト/会社で使われているかなどについて知りたいです。 @@ -54,11 +54,11 @@ GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリ ## GitHub issuesで他の人を助ける -<a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">既存のissues</a>を確認して、他の人を助けてみてください。皆さんが回答を知っているかもしれない質問がほとんどです。🤓 +<a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">既存のissues</a>を確認して、他の人を助けてみてください。皆さんが回答を知っているかもしれない質問がほとんどです。🤓 ## GitHubレポジトリをWatch -GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンをクリック): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンをクリック): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 「Releases only」ではなく「Watching」を選択すると、新たなissueが立てられた際に通知されます。 @@ -66,7 +66,7 @@ GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンを ## issuesを立てる -GitHubレポジトリで<a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">新たなissueを立てられます</a>。例えば: +GitHubレポジトリで<a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">新たなissueを立てられます</a>。例えば: * 質問、または、問題の報告 * 新機能の提案 @@ -75,7 +75,7 @@ GitHubレポジトリで<a href="https://github.com/tiangolo/fastapi/issues/new/ ## プルリクエストをする -以下の様な<a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">プルリクエストを作成</a>できます: +以下の様な<a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">プルリクエストを作成</a>できます: * ドキュメントのタイプミスを修正。 * 新たなドキュメントセクションを提案。 diff --git a/docs/ja/docs/history-design-future.md b/docs/ja/docs/history-design-future.md index 5d53cf77a..bc4a160ea 100644 --- a/docs/ja/docs/history-design-future.md +++ b/docs/ja/docs/history-design-future.md @@ -1,6 +1,6 @@ # 歴史、設計、そしてこれから -少し前に、<a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">**FastAPI** +少し前に、<a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">**FastAPI** のユーザーに以下の様に尋ねられました</a>: > このプロジェクトの歴史は?何もないところから、数週間ですごいものができているようです。 [...] diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 6f85d2013..c066c5070 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em> </p> <p align="center"> -<a href="https://travis-ci.com/tiangolo/fastapi" target="_blank"> - <img src="https://travis-ci.com/tiangolo/fastapi.svg?branch=master" alt="Build Status"> +<a href="https://travis-ci.com/fastapi/fastapi" target="_blank"> + <img src="https://travis-ci.com/fastapi/fastapi.svg?branch=master" alt="Build Status"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://badge.fury.io/py/fastapi.svg" alt="Package version"> @@ -26,7 +26,7 @@ **ドキュメント**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**ソースコード**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**ソースコード**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -67,7 +67,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降 "_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoft の機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな**Windows**製品と**Office**製品に統合されつつあります。_" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/ja/docs/project-generation.md b/docs/ja/docs/project-generation.md index 4b6f0f9fd..daef52efa 100644 --- a/docs/ja/docs/project-generation.md +++ b/docs/ja/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" clas * Docker Swarm モードデプロイ。 * ローカル開発環境向けの**Docker Compose**インテグレーションと最適化。 * UvicornとGunicornを使用した**リリース可能な** Python web サーバ。 -* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> バックエンド: +* Python <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a> バックエンド: * **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげ)。 * **直感的**: 素晴らしいエディタのサポートや <abbr title="自動補完、インテリセンスとも呼ばれる">補完。</abbr> デバッグ時間の短縮。 * **簡単**: 簡単に利用、習得できるようなデザイン。ドキュメントを読む時間を削減。 diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md index 4faf4c1f0..7c3b15d33 100644 --- a/docs/ko/docs/help-fastapi.md +++ b/docs/ko/docs/help-fastapi.md @@ -12,7 +12,7 @@ ## 뉴스레터 구독 - [**FastAPI와 친구** 뉴스레터](https://github.com/tiangolo/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}: + [**FastAPI와 친구** 뉴스레터](https://github.com/fastapi/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}: - FastAPI 와 그 친구들에 대한 뉴스 🚀 - 가이드 📝 @@ -26,13 +26,13 @@ ## Star **FastAPI** in GitHub - GitHub에서 FastAPI에 "star"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/tiangolo/fastapi. ⭐️ + GitHub에서 FastAPI에 "star"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️ 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. ## GitHub 저장소에서 릴리즈 확인 - GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/tiangolo/fastapi. 👀 + GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 여기서 "Releases only"을 선택할 수 있습니다. @@ -62,7 +62,7 @@ ## **FastAPI**에 대한 트윗 - [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 + [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. @@ -73,13 +73,13 @@ ## GitHub의 이슈로 다른사람 돕기 - [존재하는 이슈](https://github.com/tiangolo/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓 + [존재하는 이슈](https://github.com/fastapi/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓 - 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉 + 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉 ## GitHub 저장소 보기 - GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/tiangolo/fastapi. 👀 + GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 "Releases only" 대신 "Watching"을 선택하면 다른 사용자가 새로운 issue를 생성할 때 알림이 수신됩니다. @@ -87,7 +87,7 @@ ## 이슈 생성하기 - GitHub 저장소에 [새로운 이슈 생성](https://github.com/tiangolo/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다: + GitHub 저장소에 [새로운 이슈 생성](https://github.com/fastapi/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다: - **질문**을 하거나 **문제**에 대해 질문합니다. - 새로운 **기능**을 제안 합니다. @@ -96,15 +96,15 @@ ## Pull Request를 만드십시오 - Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: + Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: - 문서에서 찾은 오타를 수정할 때. - - FastAPI를 [편집하여](https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때. + - FastAPI를 [편집하여](https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때. - 해당 섹션의 시작 부분에 링크를 추가했는지 확인하십시오. - - 당신의 언어로 [문서 번역하는데](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때. + - 당신의 언어로 [문서 번역하는데](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때. - 또한 다른 사용자가 만든 번역을 검토하는데 도움을 줄 수도 있습니다. @@ -118,13 +118,13 @@ 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. - !!! tip 질문이 있는 경우, [GitHub 이슈 ](https://github.com/tiangolo/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . + !!! tip 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . ``` 다른 일반적인 대화에서만 채팅을 사용하십시오. ``` - 기존 [지터 채팅](https://gitter.im/tiangolo/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다. + 기존 [지터 채팅](https://gitter.im/fastapi/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다. ### 질문을 위해 채팅을 사용하지 마십시오 @@ -132,7 +132,7 @@ GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 - 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다. + 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다. 반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 66ecd7dff..620fcc881 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -26,7 +26,7 @@ **문서**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**소스 코드**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**소스 코드**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -67,7 +67,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 "_[...] 저는 요즘 **FastAPI**를 많이 사용하고 있습니다. [...] 사실 우리 팀의 **마이크로소프트 ML 서비스** 전부를 바꿀 계획입니다. 그중 일부는 핵심 **Windows**와 몇몇의 **Office** 제품들이 통합되고 있습니다._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>마이크로소프트</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>마이크로소프트</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/pl/docs/fastapi-people.md b/docs/pl/docs/fastapi-people.md index b244ab489..6c431b401 100644 --- a/docs/pl/docs/fastapi-people.md +++ b/docs/pl/docs/fastapi-people.md @@ -84,7 +84,7 @@ Współtworzyli kod źródłowy, dokumentację, tłumaczenia itp. 📦 </div> {% endif %} -Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">Kontrybutorzy FastAPI na GitHub</a>. 👷 +Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">Kontrybutorzy FastAPI na GitHub</a>. 👷 ## Najlepsi Oceniajacy @@ -171,7 +171,7 @@ Głównym celem tej strony jest podkreślenie wysiłku społeczności w pomagani Szczególnie włączając wysiłki, które są zwykle mniej widoczne, a w wielu przypadkach bardziej żmudne, tak jak pomaganie innym z pytaniami i ocenianie Pull Requestów z tłumaczeniami. -Dane są obliczane każdego miesiąca, możesz przeczytać <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kod źródłowy tutaj</a>. +Dane są obliczane każdego miesiąca, możesz przeczytać <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kod źródłowy tutaj</a>. Tutaj również podkreślam wkład od sponsorów. diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index fdc3b0bf9..00c99edfa 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -26,13 +26,13 @@ Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołac ## Dodaj gwiazdkę **FastAPI** na GitHubie -Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ +Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. ⭐️ Dodając gwiazdkę, inni użytkownicy będą mogli łatwiej znaleźć projekt i zobaczyć, że był już przydatny dla innych. ## Obserwuj repozytorium GitHub w poszukiwaniu nowych wydań -Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Wybierz opcję "Tylko wydania". @@ -59,7 +59,7 @@ Możesz: ## Napisz tweeta o **FastAPI** -<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">Napisz tweeta o **FastAPI**</a> i powiedz czemu Ci się podoba. 🎉 +<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi" class="external-link" target="_blank">Napisz tweeta o **FastAPI**</a> i powiedz czemu Ci się podoba. 🎉 Uwielbiam czytać w jaki sposób **FastAPI** jest używane, co Ci się w nim podobało, w jakim projekcie/firmie go używasz itp. @@ -73,8 +73,8 @@ Uwielbiam czytać w jaki sposób **FastAPI** jest używane, co Ci się w nim pod Możesz spróbować pomóc innym, odpowiadając w: -* <a href="https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">Dyskusjach na GitHubie</a> -* <a href="https://github.com/tiangolo/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">Problemach na GitHubie</a> +* <a href="https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">Dyskusjach na GitHubie</a> +* <a href="https://github.com/fastapi/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">Problemach na GitHubie</a> W wielu przypadkach możesz już znać odpowiedź na te pytania. 🤓 @@ -125,7 +125,7 @@ Jeśli odpowiedzą, jest duża szansa, że rozwiązałeś ich problem, gratulacj ## Obserwuj repozytorium na GitHubie -Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Jeśli wybierzesz "Obserwuj" zamiast "Tylko wydania", otrzymasz powiadomienia, gdy ktoś utworzy nowy problem lub pytanie. Możesz również określić, że chcesz być powiadamiany tylko o nowych problemach, dyskusjach, PR-ach itp. @@ -133,7 +133,7 @@ Następnie możesz spróbować pomóc rozwiązać te problemy. ## Zadawaj pytania -Możesz <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">utworzyć nowe pytanie</a> w repozytorium na GitHubie, na przykład aby: +Możesz <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">utworzyć nowe pytanie</a> w repozytorium na GitHubie, na przykład aby: * Zadać **pytanie** lub zapytać o **problem**. * Zaproponować nową **funkcję**. @@ -196,7 +196,7 @@ A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sa Możesz [wnieść wkład](contributing.md){.internal-link target=_blank} do kodu źródłowego za pomocą Pull Requestu, na przykład: * Naprawić literówkę, którą znalazłeś w dokumentacji. -* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">edytując ten plik</a>. +* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">edytując ten plik</a>. * Upewnij się, że dodajesz swój link na początku odpowiedniej sekcji. * Pomóc w [tłumaczeniu dokumentacji](contributing.md#translations){.internal-link target=_blank} na Twój język. * Możesz również pomóc w weryfikacji tłumaczeń stworzonych przez innych. @@ -227,7 +227,7 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz Dołącz do 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">serwera czatu na Discordzie</a> 👥 i spędzaj czas z innymi w społeczności FastAPI. !!! tip "Wskazówka" - Jeśli masz pytania, zadaj je w <a href="https://github.com/tiangolo/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + Jeśli masz pytania, zadaj je w <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. Używaj czatu tylko do innych ogólnych rozmów. diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index a69d7dc14..efa9abfc3 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -26,7 +26,7 @@ **Dokumentacja**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Kod żródłowy**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Kod żródłowy**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -66,7 +66,7 @@ Kluczowe cechy: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/pt/docs/contributing.md b/docs/pt/docs/contributing.md index 02895fcfc..7d8d1fd5e 100644 --- a/docs/pt/docs/contributing.md +++ b/docs/pt/docs/contributing.md @@ -237,14 +237,14 @@ Aqui estão os passos para ajudar com as traduções. #### Dicas e orientações -* Verifique sempre os <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">_pull requests_ existentes</a> para a sua linguagem e faça revisões das alterações e aprove elas. +* Verifique sempre os <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">_pull requests_ existentes</a> para a sua linguagem e faça revisões das alterações e aprove elas. !!! tip Você pode <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">adicionar comentários com sugestões de alterações</a> para _pull requests_ existentes. Verifique as documentações sobre <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adicionar revisão ao _pull request_</a> para aprovação ou solicitação de alterações. -* Verifique em <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">_issues_</a> para ver se existe alguém coordenando traduções para a sua linguagem. +* Verifique em <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">_issues_</a> 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. diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md index 77ec32351..a4832804d 100644 --- a/docs/pt/docs/external-links.md +++ b/docs/pt/docs/external-links.md @@ -7,7 +7,7 @@ Existem muitas postagens, artigos, ferramentas e projetos relacionados ao **Fast Aqui tem uma lista, incompleta, de algumas delas. !!! tip "Dica" - Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um <a href="https://github.com/tiangolo/fastapi/edit/master/docs/external-links.md" class="external-link" target="_blank">_Pull Request_ adicionando ele</a>. + Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um <a href="https://github.com/fastapi/fastapi/edit/master/docs/external-links.md" class="external-link" target="_blank">_Pull Request_ adicionando ele</a>. {% for section_name, section_content in external_links.items() %} diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md index 93c3479f2..d67ae0d33 100644 --- a/docs/pt/docs/fastapi-people.md +++ b/docs/pt/docs/fastapi-people.md @@ -90,7 +90,7 @@ Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 </div> {% endif %} -Existem muitos outros contribuidores (mais de uma centena), você pode ver todos eles em <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">Página de Contribuidores do FastAPI no GitHub</a>. 👷 +Existem muitos outros contribuidores (mais de uma centena), você pode ver todos eles em <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">Página de Contribuidores do FastAPI no GitHub</a>. 👷 ## Top Revisores @@ -176,7 +176,7 @@ A principal intenção desta página é destacar o esforço da comunidade para a Especialmente incluindo esforços que normalmente são menos visíveis, e em muitos casos mais árduo, como ajudar os outros com issues e revisando Pull Requests com traduções. -Os dados são calculados todo mês, você pode ler o <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">código fonte aqui</a>. +Os dados são calculados todo mês, você pode ler o <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">código fonte aqui</a>. Aqui também estou destacando contribuições de patrocinadores. diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index babb404f9..0deef15b5 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -26,13 +26,13 @@ Você pode se inscrever (pouco frequente) [**FastAPI e amigos** newsletter](news ## Favorite o **FastAPI** no GitHub -Você pode "favoritar" o FastAPI no GitHub (clicando na estrela no canto superior direito): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ +Você pode "favoritar" o FastAPI no GitHub (clicando na estrela no canto superior direito): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. ⭐️ Favoritando, outros usuários poderão encontrar mais facilmente e verão que já foi útil para muita gente. ## Acompanhe novos updates no repositorio do GitHub -Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no botão com um "olho" no canto superior direito): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no botão com um "olho" no canto superior direito): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Podendo selecionar apenas "Novos Updates". @@ -59,7 +59,7 @@ Você pode: ## Tweete sobre **FastAPI** -<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">Tweete sobre o **FastAPI**</a> e compartilhe comigo e com os outros o porque de gostar do FastAPI. 🎉 +<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi" class="external-link" target="_blank">Tweete sobre o **FastAPI**</a> e compartilhe comigo e com os outros o porque de gostar do FastAPI. 🎉 Adoro ouvir sobre como o **FastAPI** é usado, o que você gosta nele, em qual projeto/empresa está sendo usado, etc. @@ -70,13 +70,13 @@ Adoro ouvir sobre como o **FastAPI** é usado, o que você gosta nele, em qual p ## Responda perguntas no GitHub -Você pode acompanhar as <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">perguntas existentes</a> e tentar ajudar outros, . 🤓 +Você pode acompanhar as <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">perguntas existentes</a> e tentar ajudar outros, . 🤓 Ajudando a responder as questões de varias pessoas, você pode se tornar um [Expert em FastAPI](fastapi-people.md#especialistas){.internal-link target=_blank} oficial. 🎉 ## Acompanhe o repositório do GitHub -Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no "olho" no canto superior direito): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no "olho" no canto superior direito): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Se você selecionar "Acompanhando" (Watching) em vez de "Apenas Lançamentos" (Releases only) você receberá notificações quando alguém tiver uma nova pergunta. @@ -84,7 +84,7 @@ Assim podendo tentar ajudar a resolver essas questões. ## Faça perguntas -É possível <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">criar uma nova pergunta</a> no repositório do GitHub, por exemplo: +É possível <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">criar uma nova pergunta</a> no repositório do GitHub, por exemplo: * Faça uma **pergunta** ou pergunte sobre um **problema**. * Sugira novos **recursos**. @@ -96,7 +96,7 @@ Assim podendo tentar ajudar a resolver essas questões. É possível [contribuir](contributing.md){.internal-link target=_blank} no código fonte fazendo Pull Requests, por exemplo: * Para corrigir um erro de digitação que você encontrou na documentação. -* Para compartilhar um artigo, video, ou podcast criados por você sobre o FastAPI <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">editando este arquivo</a>. +* Para compartilhar um artigo, video, ou podcast criados por você sobre o FastAPI <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">editando este arquivo</a>. * Não se esqueça de adicionar o link no começo da seção correspondente. * Para ajudar [traduzir a documentação](contributing.md#traducoes){.internal-link target=_blank} para sua lingua. * Também é possivel revisar as traduções já existentes. @@ -110,7 +110,7 @@ Entre no 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" targ do FastAPI. !!! tip "Dica" - Para perguntas, pergunte nas <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. + Para perguntas, pergunte nas <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. Use o chat apenas para outro tipo de assunto. diff --git a/docs/pt/docs/history-design-future.md b/docs/pt/docs/history-design-future.md index a7a177660..4ec217405 100644 --- a/docs/pt/docs/history-design-future.md +++ b/docs/pt/docs/history-design-future.md @@ -1,6 +1,6 @@ # História, Design e Futuro -Há algum tempo, <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">um usuário **FastAPI** perguntou</a>: +Há algum tempo, <a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">um usuário **FastAPI** perguntou</a>: > Qual é a história desse projeto? Parece que surgiu do nada e se tornou incrível em poucas semanas [...] diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 3f8dd18a9..bdaafdefc 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -11,11 +11,11 @@ <em>Framework FastAPI, alta performance, fácil de aprender, fácil de codar, pronto para produção</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -26,7 +26,7 @@ **Documentação**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Código fonte**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Código fonte**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -66,7 +66,7 @@ Os recursos chave são: "*[...] Estou usando **FastAPI** muito esses dias. [...] Estou na verdade planejando utilizar ele em todos os times de **serviços _Machine Learning_ na Microsoft**. Alguns deles estão sendo integrados no _core_ do produto **Windows** e alguns produtos **Office**.*" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/pt/docs/project-generation.md b/docs/pt/docs/project-generation.md index c98bd069d..e5c935fd2 100644 --- a/docs/pt/docs/project-generation.md +++ b/docs/pt/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" clas * Modo de implantação Docker Swarm. * Integração e otimização **Docker Compose** para desenvolvimento local. * **Pronto para Produção** com servidor _web_ usando Uvicorn e Gunicorn. -* _Backend_ <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> Python: +* _Backend_ <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a> Python: * **Rápido**: Alta performance, no nível de **NodeJS** e **Go** (graças ao Starlette e Pydantic). * **Intuitivo**: Ótimo suporte de editor. <abbr title="também conhecido como auto-complete, auto completação, IntelliSense">_Auto-Complete_</abbr> em todo lugar. Menos tempo _debugando_. * **Fácil**: Projetado para ser fácil de usar e aprender. Menos tempo lendo documentações. diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md index f9b8912e5..c87916312 100644 --- a/docs/ru/docs/contributing.md +++ b/docs/ru/docs/contributing.md @@ -237,14 +237,14 @@ $ uvicorn tutorial001:app --reload #### Подсказки и инструкции -* Проверьте <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">существующие пул-реквесты</a> для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. +* Проверьте <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">существующие пул-реквесты</a> для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. !!! tip "Подсказка" Вы можете <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">добавлять комментарии с предложениями по изменению</a> в существующие пул-реквесты. Ознакомьтесь с документацией о <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">добавлении отзыва к пул-реквесту</a>, чтобы утвердить его или запросить изменения. -* Проверьте <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">проблемы и вопросы</a>, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. +* Проверьте <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">проблемы и вопросы</a>, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. * Добавляйте один пул-реквест для каждой отдельной переведённой страницы. Это значительно облегчит другим его просмотр. diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md index 2448ef82e..0a4cda27b 100644 --- a/docs/ru/docs/external-links.md +++ b/docs/ru/docs/external-links.md @@ -7,7 +7,7 @@ Вот неполный список некоторых из них. !!! tip - Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>. + Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>. {% for section_name, section_content in external_links.items() %} diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md index fa70d168e..31bb2798e 100644 --- a/docs/ru/docs/fastapi-people.md +++ b/docs/ru/docs/fastapi-people.md @@ -89,7 +89,7 @@ hide: </div> {% endif %} -На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors page</a>. 👷 +На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors page</a>. 👷 ## Рейтинг ревьюеров @@ -177,7 +177,7 @@ hide: Особенно это касается усилий, которые обычно менее заметны и во многих случаях более трудоемки, таких как помощь другим в решении проблем и проверка пул-реквестов с переводами. -Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">тут</a>. +Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">тут</a>. Кроме того, я также подчеркиваю вклад спонсоров. diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index d53f501f5..b007437bc 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -26,13 +26,13 @@ ## Добавить **FastAPI** звезду на GitHub -Вы можете добавить FastAPI "звезду" на GitHub (кликнуть на кнопку звезды в верхнем правом углу экрана): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️ +Вы можете добавить FastAPI "звезду" на GitHub (кликнуть на кнопку звезды в верхнем правом углу экрана): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. ⭐️ Чем больше звёзд, тем легче другим пользователям найти нас и увидеть, что проект уже стал полезным для многих. ## Отслеживать свежие выпуски в репозитории на GitHub -Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Там же Вы можете указать в настройках - "Releases only". @@ -59,7 +59,7 @@ ## Оставить сообщение в Twitter о **FastAPI** -<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">Оставьте сообщение в Twitter о **FastAPI**</a> и позвольте мне и другим узнать - почему он Вам нравится. 🎉 +<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi" class="external-link" target="_blank">Оставьте сообщение в Twitter о **FastAPI**</a> и позвольте мне и другим узнать - почему он Вам нравится. 🎉 Я люблю узнавать о том, как **FastAPI** используется, что Вам понравилось в нём, в каких проектах/компаниях Вы используете его и т.п. @@ -71,7 +71,7 @@ ## Помочь другим с их проблемами на GitHub -Вы можете посмотреть, какие <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">проблемы</a> испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓 +Вы можете посмотреть, какие <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">проблемы</a> испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓 Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. 🎉 @@ -117,7 +117,7 @@ ## Отслеживать репозиторий на GitHub -Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 Если Вы выберете "Watching" вместо "Releases only", то будете получать уведомления когда кто-либо попросит о помощи с решением его проблемы. @@ -125,7 +125,7 @@ ## Запросить помощь с решением проблемы -Вы можете <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">создать новый запрос с просьбой о помощи</a> в репозитории на GitHub, например: +Вы можете <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">создать новый запрос с просьбой о помощи</a> в репозитории на GitHub, например: * Задать **вопрос** или попросить помощи в решении **проблемы**. * Предложить новое **улучшение**. @@ -188,7 +188,7 @@ Вы можете [сделать вклад](contributing.md){.internal-link target=_blank} в код фреймворка используя пул-реквесты, например: * Исправить опечатку, которую Вы нашли в документации. -* Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">изменив этот файл</a>. +* Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">изменив этот файл</a>. * Убедитесь, что Вы добавили свою ссылку в начало соответствующего раздела. * Помочь с [переводом документации](contributing.md#_8){.internal-link target=_blank} на Ваш язык. * Вы также можете проверять переводы сделанные другими. @@ -219,7 +219,7 @@ Подключайтесь к 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank"> чату в Discord</a> 👥 и общайтесь с другими участниками сообщества FastAPI. !!! tip "Подсказка" - Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. + Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. Используйте этот чат только для бесед на отвлечённые темы. diff --git a/docs/ru/docs/history-design-future.md b/docs/ru/docs/history-design-future.md index e9572a6d6..96604e3a4 100644 --- a/docs/ru/docs/history-design-future.md +++ b/docs/ru/docs/history-design-future.md @@ -1,6 +1,6 @@ # История создания и дальнейшее развитие -Однажды, <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">один из пользователей **FastAPI** задал вопрос</a>: +Однажды, <a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">один из пользователей **FastAPI** задал вопрос</a>: > Какова история этого проекта? Создаётся впечатление, что он явился из ниоткуда и завоевал мир за несколько недель [...] diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 7148131dc..313e980d8 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -11,11 +11,11 @@ <em>Готовый к внедрению высокопроизводительный фреймворк, простой в изучении и разработке.</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **Документация**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Исходный код**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Исходный код**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -69,7 +69,7 @@ FastAPI — это современный, быстрый (высокопрои "_В последнее время я много где использую **FastAPI**. [...] На самом деле я планирую использовать его для всех **сервисов машинного обучения моей команды в Microsoft**. Некоторые из них интегрируются в основной продукт **Windows**, а некоторые — в продукты **Office**._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/ru/docs/project-generation.md b/docs/ru/docs/project-generation.md index 76253d6f2..efd6794ad 100644 --- a/docs/ru/docs/project-generation.md +++ b/docs/ru/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" clas * Развёртывается в режиме Docker Swarm. * Интегрирован с **Docker Compose** и оптимизирован для локальной разработки. * **Готовый к реальной работе** веб-сервер Python использующий Uvicorn и Gunicorn. -* Бэкенд построен на фреймворке <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a>: +* Бэкенд построен на фреймворке <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a>: * **Быстрый**: Высокопроизводительный, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic). * **Интуитивно понятный**: Отличная поддержка редактора. <dfn title="также известное как автозаполнение, интеллектуальность, автозавершение">Автодополнение кода</dfn> везде. Меньше времени на отладку. * **Простой**: Разработан так, чтоб быть простым в использовании и изучении. Меньше времени на чтение документации. diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md index 78eaf1729..209ab922c 100644 --- a/docs/tr/docs/external-links.md +++ b/docs/tr/docs/external-links.md @@ -7,7 +7,7 @@ Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. !!! tip "İpucu" - Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a> oluşturabilirsiniz. + Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a> oluşturabilirsiniz. {% for section_name, section_content in external_links.items() %} diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md index 6dd4ec061..de62c57c4 100644 --- a/docs/tr/docs/fastapi-people.md +++ b/docs/tr/docs/fastapi-people.md @@ -89,7 +89,7 @@ Kaynak koduna, dökümantasyona, çevirilere ve bir sürü şeye katkıda bulund </div> {% endif %} -Bunlar dışında katkıda bulunan, yüzden fazla, bir sürü insan var. Hepsini <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Katkıda Bulunanlar</a> sayfasında görebilirsin. 👷 +Bunlar dışında katkıda bulunan, yüzden fazla, bir sürü insan var. Hepsini <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Katkıda Bulunanlar</a> sayfasında görebilirsin. 👷 ## En Fazla Değerlendirme Yapanlar @@ -176,7 +176,7 @@ Bu sayfanın temel amacı, topluluğun başkalarına yardım etme çabasını vu Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorularında yardımcı olmak, çevirileri ve Pull Request'leri gözden geçirmek gibi çabalar dahil. -Veriler ayda bir hesaplanır, <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kaynak kodu buradan</a> okuyabilirsin. +Veriler ayda bir hesaplanır, <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kaynak kodu buradan</a> okuyabilirsin. Burada sponsorların katkılarını da vurguluyorum. diff --git a/docs/tr/docs/history-design-future.md b/docs/tr/docs/history-design-future.md index 1dd0e637f..8b2662bc3 100644 --- a/docs/tr/docs/history-design-future.md +++ b/docs/tr/docs/history-design-future.md @@ -1,6 +1,6 @@ # Geçmişi, Tasarımı ve Geleceği -Bir süre önce, <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">bir **FastAPI** kullanıcısı sordu</a>: +Bir süre önce, <a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">bir **FastAPI** kullanıcısı sordu</a>: > Bu projenin geçmişi nedir? Birkaç hafta içinde hiçbir yerden harika bir şeye dönüşmüş gibi görünüyor [...] diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 3dc624a68..7d96b4edc 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI framework, yüksek performanslı, öğrenmesi oldukça kolay, kodlaması hızlı, kullanıma hazır</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **Dokümantasyon**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Kaynak Kod**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Kaynak Kod**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -69,7 +69,7 @@ Temel özellikleri şunlardır: "_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum. [...] Aslında bunu ekibimin **Microsoft'taki Machine Learning servislerinin** tamamında kullanmayı planlıyorum. Bunlardan bazıları **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre ediliyor._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/tr/docs/project-generation.md b/docs/tr/docs/project-generation.md index 75e3ae339..c9dc24acc 100644 --- a/docs/tr/docs/project-generation.md +++ b/docs/tr/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" clas * Docker Swarm Mode ile deployment. * **Docker Compose** entegrasyonu ve lokal geliştirme için optimizasyon. * Uvicorn ve Gunicorn ile **Production ready** Python web server'ı. -* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> backend: +* Python <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a> backend: * **Hızlı**: **NodeJS** ve **Go** ile eşit, çok yüksek performans (Starlette ve Pydantic'e teşekkürler). * **Sezgisel**: Editor desteğı. <abbr title="auto-complete, IntelliSense gibi isimlerle de bilinir">Otomatik tamamlama</abbr>. Daha az debugging. * **Kolay**: Kolay öğrenip kolay kullanmak için tasarlandı. Daha az döküman okuma daha çok iş. diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md index 152a7b098..c6a6451d8 100644 --- a/docs/uk/docs/fastapi-people.md +++ b/docs/uk/docs/fastapi-people.md @@ -89,7 +89,7 @@ FastAPI має дивовижну спільноту, яка вітає люде </div> {% endif %} -Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors</a>. 👷 +Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors</a>. 👷 ## Найкращі рецензенти @@ -176,7 +176,7 @@ FastAPI має дивовижну спільноту, яка вітає люде Особливо враховуючи зусилля, які зазвичай менш помітні, а в багатьох випадках більш важкі, як-от допомога іншим із проблемами та перегляд пул реквестів перекладів. -Дані розраховуються щомісяця, ви можете ознайомитися з <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">вихідним кодом тут</a>. +Дані розраховуються щомісяця, ви можете ознайомитися з <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">вихідним кодом тут</a>. Тут я також підкреслюю внески спонсорів. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index 29e19025a..ffcb8fd13 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -5,11 +5,11 @@ <em>Готовий до продакшину, високопродуктивний, простий у вивченні та швидкий для написання коду фреймворк</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -23,7 +23,7 @@ **Документація**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Програмний код**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Програмний код**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -64,7 +64,7 @@ FastAPI - це сучасний, швидкий (високопродуктив "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index c75af9fa8..5fc1400fd 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI framework, hiệu năng cao, dễ học, dễ code, sẵn sàng để tạo ra sản phẩm</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **Tài liệu**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Mã nguồn**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Mã nguồn**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -69,7 +69,7 @@ Những tính năng như: "_[...] Tôi đang sử dụng **FastAPI** vô cùng nhiều vào những ngày này. [...] Tôi thực sự đang lên kế hoạch sử dụng nó cho tất cả các nhóm **dịch vụ ML tại Microsoft**. Một vài trong số đó đang tích hợp vào sản phẩm lõi của **Window** và một vài sản phẩm cho **Office**._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index c2780a086..eb20adbb5 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -11,11 +11,11 @@ <em>Ìlànà wẹ́ẹ́bù FastAPI, iṣẹ́ gíga, ó rọrùn láti kọ̀, o yára láti kóòdù, ó sì ṣetán fún iṣelọpọ ní lílo</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **Àkọsílẹ̀**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**Orisun Kóòdù**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**Orisun Kóòdù**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -69,7 +69,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b "_[...] Mò ń lo **FastAPI** púpọ̀ ní lẹ́nu àìpẹ́ yìí. [...] Mo n gbero láti lo o pẹ̀lú àwọn ẹgbẹ mi fún gbogbo iṣẹ **ML wa ni Microsoft**. Diẹ nínú wọn ni afikun ti ifilelẹ àwọn ẹya ara ti ọja **Windows** wa pẹ̀lú àwọn ti **Office**._" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md index 0bc00f9c6..cc671cacf 100644 --- a/docs/zh-hant/docs/fastapi-people.md +++ b/docs/zh-hant/docs/fastapi-people.md @@ -148,7 +148,7 @@ FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 </div> {% endif %} -還有許多其他的貢獻者(超過一百位),你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 貢獻者頁面</a>查看。 👷 +還有許多其他的貢獻者(超過一百位),你可以在 <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 貢獻者頁面</a>查看。 👷 ## 主要翻譯審核者 @@ -229,7 +229,7 @@ FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 特別是那些通常不太顯眼但往往更加艱辛的工作,例如幫助他人解答問題和審查包含翻譯的 Pull Requests。 -這些數據每月計算一次,你可以在這查看<a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">原始碼</a>。 +這些數據每月計算一次,你可以在這查看<a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">原始碼</a>。 此外,我也特別表揚贊助者的貢獻。 diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index cdd98ae84..c98a3098f 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -5,11 +5,11 @@ <em>FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> </a> -<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/fastapi" target="_blank"> - <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/fastapi.svg" alt="Coverage"> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -23,7 +23,7 @@ **文件**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**程式碼**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**程式碼**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -63,7 +63,7 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python "_[...] 近期大量的使用 **FastAPI**。 [...] 目前正在計畫在**微軟**團隊的**機器學習**服務中導入。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_" -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md index 3dfc3db7c..91be2edbb 100644 --- a/docs/zh/docs/contributing.md +++ b/docs/zh/docs/contributing.md @@ -254,22 +254,22 @@ $ uvicorn tutorial001:app --reload #### 建议和指南 -* 在当前 <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">已有的 pull requests</a> 中查找你使用的语言,添加要求修改或同意合并的评审意见。 +* 在当前 <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">已有的 pull requests</a> 中查找你使用的语言,添加要求修改或同意合并的评审意见。 !!! tip 你可以为已有的 pull requests <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">添加包含修改建议的评论</a>。 详情可查看关于 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">添加 pull request 评审意见</a> 以同意合并或要求修改的文档。 -* 检查在 <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 +* 检查在 <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 * 每翻译一个页面新增一个 pull request。这将使其他人更容易对其进行评审。 对于我(译注:作者使用西班牙语和英语)不懂的语言,我将在等待其他人评审翻译之后将其合并。 * 你还可以查看是否有你所用语言的翻译,并对其进行评审,这将帮助我了解翻译是否正确以及能否将其合并。 - * 可以在 <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussions</a> 中查看。 - * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3A%22awaiting+review%22" class="external-link" target="_blank">`lang-es`</a>。 + * 可以在 <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussions</a> 中查看。 + * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 <a href="https://github.com/fastapi/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3A%22awaiting+review%22" class="external-link" target="_blank">`lang-es`</a>。 * 请使用相同的 Python 示例,且只需翻译文档中的文本,不用修改其它东西。 diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md index d6a3e66c3..87e6c8e6b 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -148,7 +148,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 </div> {% endif %} -还有很多别的贡献者(超过100个),你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷 +还有很多别的贡献者(超过100个),你可以在 <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷 ## 杰出翻译审核者 @@ -229,7 +229,7 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 尤其是那些不引人注目且涉及更困难的任务,例如帮助他人解决问题或者评审翻译 Pull Requests。 -该数据每月计算一次,您可以阅读 <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">源代码</a>。 +该数据每月计算一次,您可以阅读 <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">源代码</a>。 这里也强调了赞助商的贡献。 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index d2a210c39..e3aa5575c 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -26,13 +26,13 @@ ## 在 GitHub 上为 **FastAPI** 加星 -您可以在 GitHub 上 **Star** FastAPI(只要点击右上角的星星就可以了): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi。</a>⭐️ +您可以在 GitHub 上 **Star** FastAPI(只要点击右上角的星星就可以了): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi。</a>⭐️ **Star** 以后,其它用户就能更容易找到 FastAPI,并了解到已经有其他用户在使用它了。 ## 关注 GitHub 资源库的版本发布 -您还可以在 GitHub 上 **Watch** FastAPI,(点击右上角的 **Watch** 按钮)<a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi。</a>👀 +您还可以在 GitHub 上 **Watch** FastAPI,(点击右上角的 **Watch** 按钮)<a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi。</a>👀 您可以选择只关注发布(**Releases only**)。 @@ -59,7 +59,7 @@ ## Tweet about **FastAPI** -<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">Tweet about **FastAPI**</a> 让我和大家知道您为什么喜欢 FastAPI。🎉 +<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi" class="external-link" target="_blank">Tweet about **FastAPI**</a> 让我和大家知道您为什么喜欢 FastAPI。🎉 知道有人使用 **FastAPI**,我会很开心,我也想知道您为什么喜欢 FastAPI,以及您在什么项目/哪些公司使用 FastAPI,等等。 @@ -70,13 +70,13 @@ ## 在 GitHub 上帮助其他人解决问题 -您可以查看<a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">现有 issues</a>,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓 +您可以查看<a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">现有 issues</a>,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓 如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#_3){.internal-link target=_blank}。🎉 ## 监听 GitHub 资源库 -您可以在 GitHub 上「监听」FastAPI(点击右上角的 "watch" 按钮): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀 +您可以在 GitHub 上「监听」FastAPI(点击右上角的 "watch" 按钮): <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>. 👀 如果您选择 "Watching" 而不是 "Releases only",有人创建新 Issue 时,您会接收到通知。 @@ -84,7 +84,7 @@ ## 创建 Issue -您可以在 GitHub 资源库中<a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">创建 Issue</a>,例如: +您可以在 GitHub 资源库中<a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">创建 Issue</a>,例如: * 提出**问题**或**意见** * 提出新**特性**建议 @@ -96,7 +96,7 @@ 您可以创建 PR 为源代码做[贡献](contributing.md){.internal-link target=_blank},例如: * 修改文档错别字 -* <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">编辑这个文件</a>,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成 +* <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">编辑这个文件</a>,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成 * 注意,添加的链接要放在对应区块的开头 * [翻译文档](contributing.md#_8){.internal-link target=_blank} * 审阅别人翻译的文档 @@ -110,7 +110,7 @@ !!! tip "提示" - 如有问题,请在 <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 + 如有问题,请在 <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 聊天室仅供闲聊。 diff --git a/docs/zh/docs/history-design-future.md b/docs/zh/docs/history-design-future.md index 798b8fb5f..48cfef524 100644 --- a/docs/zh/docs/history-design-future.md +++ b/docs/zh/docs/history-design-future.md @@ -1,6 +1,6 @@ # 历史、设计、未来 -不久前,<a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">曾有 **FastAPI** 用户问过</a>: +不久前,<a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">曾有 **FastAPI** 用户问过</a>: > 这个项目有怎样的历史?好像它只用了几周就从默默无闻变得众所周知…… diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 0933a0291..d1238fdd2 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -11,11 +11,11 @@ <em>FastAPI 框架,高性能,易于学习,高效编码,生产可用</em> </p> <p align="center"> -<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank"> - <img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg" alt="Test"> </a> -<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> - <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage"> +<a href="https://codecov.io/gh/fastapi/fastapi" target="_blank"> + <img src="https://img.shields.io/codecov/c/github/fastapi/fastapi?color=%2334D058" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> @@ -29,7 +29,7 @@ **文档**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> -**源码**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> +**源码**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a> --- @@ -70,7 +70,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 「_[...] 最近我一直在使用 **FastAPI**。[...] 实际上我正在计划将其用于我所在的**微软**团队的所有**机器学习服务**。其中一些服务正被集成进核心 **Windows** 产品和一些 **Office** 产品。_」 -<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>微软</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>微软</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> --- diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md index feafa5333..0655cb0a9 100644 --- a/docs/zh/docs/project-generation.md +++ b/docs/zh/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub:<a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" cla * Docker Swarm 开发模式 * **Docker Compose** 本地开发集成与优化 * **生产可用**的 Python 网络服务器,使用 Uvicorn 或 Gunicorn -* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> 后端: +* Python <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">**FastAPI**</a> 后端: * * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic) * **直观**:强大的编辑器支持,处处皆可<abbr title="也叫自动完成、智能感知">自动补全</abbr>,减少调试时间 * **简单**:易学、易用,阅读文档所需时间更短 diff --git a/pyproject.toml b/pyproject.toml index dbaa42149..9ab6e6d69 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,9 +47,9 @@ dependencies = [ ] [project.urls] -Homepage = "https://github.com/tiangolo/fastapi" +Homepage = "https://github.com/fastapi/fastapi" Documentation = "https://fastapi.tiangolo.com/" -Repository = "https://github.com/tiangolo/fastapi" +Repository = "https://github.com/fastapi/fastapi" [project.optional-dependencies] From 2c33611c6224a88d40f45ab1adf568974aa30f64 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 29 Jul 2024 23:35:29 +0000 Subject: [PATCH 638/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a14d627c6..9a4d36960 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🚚 Rename GitHub links from tiangolo/fastapi to fastapi/fastapi. PR [#11913](https://github.com/fastapi/fastapi/pull/11913) by [@tiangolo](https://github.com/tiangolo). * 📝 Add docs about FastAPI team and project management. PR [#11908](https://github.com/tiangolo/fastapi/pull/11908) by [@tiangolo](https://github.com/tiangolo). * 📝 Re-structure docs main menu. PR [#11904](https://github.com/tiangolo/fastapi/pull/11904) by [@tiangolo](https://github.com/tiangolo). * 📝 Update Speakeasy URL. PR [#11871](https://github.com/tiangolo/fastapi/pull/11871) by [@ndimares](https://github.com/ndimares). From 0a21b371b7d8b1d7bcca3c323b1f275f2deebda6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 29 Jul 2024 20:32:30 -0500 Subject: [PATCH 639/846] =?UTF-8?q?=F0=9F=93=9D=20Tweak=20management=20doc?= =?UTF-8?q?s=20(#11918)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/management.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/management.md b/docs/en/docs/management.md index 27bf0bd1c..ac0ede75f 100644 --- a/docs/en/docs/management.md +++ b/docs/en/docs/management.md @@ -6,9 +6,7 @@ Here's a short description of how the FastAPI repository is managed and maintain I, <a href="https://github.com/tiangolo" target="_blank">@tiangolo</a>, am the creator and owner of the FastAPI repository. 🤓 -I make the final decisions on the the project. I'm the <a href="https://en.wikipedia.org/wiki/Benevolent_dictator_for_life" class="external-link" target="_blank"><abbr title="Benevolent Dictator For Life">BDFL</abbr></a>. 😅 - -I normally give the final review to each PR, commonly with some tweaking commits on top, before merging them. +I normally give the final review to each PR before merging them. I make the final decisions on the the project, I'm the <a href="https://en.wikipedia.org/wiki/Benevolent_dictator_for_life" class="external-link" target="_blank"><abbr title="Benevolent Dictator For Life">BDFL</abbr></a>. 😅 ## Team From b9e274dc11215776f6b455f564e8132b86e370fb Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 30 Jul 2024 01:32:52 +0000 Subject: [PATCH 640/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9a4d36960..b418ff445 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Tweak management docs. PR [#11918](https://github.com/fastapi/fastapi/pull/11918) by [@tiangolo](https://github.com/tiangolo). * 🚚 Rename GitHub links from tiangolo/fastapi to fastapi/fastapi. PR [#11913](https://github.com/fastapi/fastapi/pull/11913) by [@tiangolo](https://github.com/tiangolo). * 📝 Add docs about FastAPI team and project management. PR [#11908](https://github.com/tiangolo/fastapi/pull/11908) by [@tiangolo](https://github.com/tiangolo). * 📝 Re-structure docs main menu. PR [#11904](https://github.com/tiangolo/fastapi/pull/11904) by [@tiangolo](https://github.com/tiangolo). From 7723e963177a5677a20fe079e6200e810dd776ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 30 Jul 2024 21:17:52 -0500 Subject: [PATCH 641/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20tokens=20for=20?= =?UTF-8?q?GitHub=20Actions=20(#11924)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue-manager.yml | 3 +++ .github/workflows/label-approved.yml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index 260902e12..d5b947a9c 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -14,6 +14,9 @@ on: - labeled workflow_dispatch: +permissions: + issues: write + jobs: issue-manager: if: github.repository_owner == 'fastapi' diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 63fb7ff23..939444aaf 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -5,6 +5,9 @@ on: - cron: "0 12 * * *" workflow_dispatch: +permissions: + issues: write + jobs: label-approved: if: github.repository_owner == 'fastapi' From b0801e66d303ba54aaa6bac442642a16f1dbb51b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 31 Jul 2024 02:18:12 +0000 Subject: [PATCH 642/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b418ff445..7d23692a5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -25,6 +25,7 @@ hide: ### Internal +* 👷 Update tokens for GitHub Actions. PR [#11924](https://github.com/fastapi/fastapi/pull/11924) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token permissions to comment deployment URL in docs. PR [#11917](https://github.com/fastapi/fastapi/pull/11917) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token permissions for GitHub Actions. PR [#11915](https://github.com/fastapi/fastapi/pull/11915) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Actions token usage. PR [#11914](https://github.com/fastapi/fastapi/pull/11914) by [@tiangolo](https://github.com/tiangolo). From 2e35b176cf5ff73e4cb035322f0af8157d654f7d Mon Sep 17 00:00:00 2001 From: jianghuyiyuan <shuangcui@live.com> Date: Wed, 31 Jul 2024 23:09:15 +0900 Subject: [PATCH 643/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20in?= =?UTF-8?q?=20docs=20(#11926)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/management.md | 2 +- docs_src/dataclasses/tutorial002.py | 2 +- docs_src/dataclasses/tutorial003.py | 2 +- tests/test_tutorial/test_dataclasses/test_tutorial002.py | 2 +- tests/test_tutorial/test_dataclasses/test_tutorial003.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/management.md b/docs/en/docs/management.md index ac0ede75f..085a1756f 100644 --- a/docs/en/docs/management.md +++ b/docs/en/docs/management.md @@ -6,7 +6,7 @@ Here's a short description of how the FastAPI repository is managed and maintain I, <a href="https://github.com/tiangolo" target="_blank">@tiangolo</a>, am the creator and owner of the FastAPI repository. 🤓 -I normally give the final review to each PR before merging them. I make the final decisions on the the project, I'm the <a href="https://en.wikipedia.org/wiki/Benevolent_dictator_for_life" class="external-link" target="_blank"><abbr title="Benevolent Dictator For Life">BDFL</abbr></a>. 😅 +I normally give the final review to each PR before merging them. I make the final decisions on the project, I'm the <a href="https://en.wikipedia.org/wiki/Benevolent_dictator_for_life" class="external-link" target="_blank"><abbr title="Benevolent Dictator For Life">BDFL</abbr></a>. 😅 ## Team diff --git a/docs_src/dataclasses/tutorial002.py b/docs_src/dataclasses/tutorial002.py index 08a238080..ece2f150c 100644 --- a/docs_src/dataclasses/tutorial002.py +++ b/docs_src/dataclasses/tutorial002.py @@ -21,6 +21,6 @@ async def read_next_item(): return { "name": "Island In The Moon", "price": 12.99, - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", "tags": ["breater"], } diff --git a/docs_src/dataclasses/tutorial003.py b/docs_src/dataclasses/tutorial003.py index 34ce1199e..c61315513 100644 --- a/docs_src/dataclasses/tutorial003.py +++ b/docs_src/dataclasses/tutorial003.py @@ -33,7 +33,7 @@ def get_authors(): # (8) "items": [ { "name": "Island In The Moon", - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", }, {"name": "Holy Buddies"}, ], diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial002.py b/tests/test_tutorial/test_dataclasses/test_tutorial002.py index 4146f4cd6..e6d303cfc 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial002.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial002.py @@ -12,7 +12,7 @@ def test_get_item(): assert response.json() == { "name": "Island In The Moon", "price": 12.99, - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", "tags": ["breater"], "tax": None, } diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial003.py b/tests/test_tutorial/test_dataclasses/test_tutorial003.py index dd0e36735..e1fa45201 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial003.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial003.py @@ -31,7 +31,7 @@ def test_get_authors(): "items": [ { "name": "Island In The Moon", - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", }, {"name": "Holy Buddies", "description": None}, ], From c0ae16ab7a25a0b54d8201479cf31e2492f7090a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 31 Jul 2024 14:09:35 +0000 Subject: [PATCH 644/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7d23692a5..385133266 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix typos in docs. PR [#11926](https://github.com/fastapi/fastapi/pull/11926) by [@jianghuyiyuan](https://github.com/jianghuyiyuan). * 📝 Tweak management docs. PR [#11918](https://github.com/fastapi/fastapi/pull/11918) by [@tiangolo](https://github.com/tiangolo). * 🚚 Rename GitHub links from tiangolo/fastapi to fastapi/fastapi. PR [#11913](https://github.com/fastapi/fastapi/pull/11913) by [@tiangolo](https://github.com/tiangolo). * 📝 Add docs about FastAPI team and project management. PR [#11908](https://github.com/tiangolo/fastapi/pull/11908) by [@tiangolo](https://github.com/tiangolo). From 8b930f88474d3da3551fb1f3e844b0591cce1f84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 31 Jul 2024 18:40:04 -0500 Subject: [PATCH 645/846] =?UTF-8?q?=F0=9F=91=B7=20Refactor=20GitHub=20Acti?= =?UTF-8?q?on=20to=20comment=20docs=20deployment=20URLs=20and=20update=20t?= =?UTF-8?q?oken=20(#11925)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../comment-docs-preview-in-pr/Dockerfile | 9 --- .../comment-docs-preview-in-pr/action.yml | 13 ---- .../comment-docs-preview-in-pr/app/main.py | 69 ------------------- .github/workflows/deploy-docs.yml | 23 +++++-- ...nts.txt => requirements-github-actions.txt | 4 +- scripts/comment_docs_deploy_url_in_pr.py | 31 +++++++++ 6 files changed, 52 insertions(+), 97 deletions(-) delete mode 100644 .github/actions/comment-docs-preview-in-pr/Dockerfile delete mode 100644 .github/actions/comment-docs-preview-in-pr/action.yml delete mode 100644 .github/actions/comment-docs-preview-in-pr/app/main.py rename .github/actions/comment-docs-preview-in-pr/requirements.txt => requirements-github-actions.txt (55%) create mode 100644 scripts/comment_docs_deploy_url_in_pr.py diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile deleted file mode 100644 index 42627fe19..000000000 --- a/.github/actions/comment-docs-preview-in-pr/Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM python:3.10 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install -r /app/requirements.txt - -COPY ./app /app - -CMD ["python", "/app/main.py"] diff --git a/.github/actions/comment-docs-preview-in-pr/action.yml b/.github/actions/comment-docs-preview-in-pr/action.yml deleted file mode 100644 index 0eb64402d..000000000 --- a/.github/actions/comment-docs-preview-in-pr/action.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Comment Docs Preview in PR -description: Comment with the docs URL preview in the PR -author: Sebastián Ramírez <tiangolo@gmail.com> -inputs: - token: - description: Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }} - required: true - deploy_url: - description: The deployment URL to comment in the PR - required: true -runs: - using: docker - image: Dockerfile diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py deleted file mode 100644 index 8cc119fe0..000000000 --- a/.github/actions/comment-docs-preview-in-pr/app/main.py +++ /dev/null @@ -1,69 +0,0 @@ -import logging -import sys -from pathlib import Path -from typing import Union - -import httpx -from github import Github -from github.PullRequest import PullRequest -from pydantic import BaseModel, SecretStr, ValidationError -from pydantic_settings import BaseSettings - -github_api = "https://api.github.com" - - -class Settings(BaseSettings): - github_repository: str - github_event_path: Path - github_event_name: Union[str, None] = None - input_token: SecretStr - input_deploy_url: str - - -class PartialGithubEventHeadCommit(BaseModel): - id: str - - -class PartialGithubEventWorkflowRun(BaseModel): - head_commit: PartialGithubEventHeadCommit - - -class PartialGithubEvent(BaseModel): - workflow_run: PartialGithubEventWorkflowRun - - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - settings = Settings() - logging.info(f"Using config: {settings.json()}") - g = Github(settings.input_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - try: - event = PartialGithubEvent.parse_file(settings.github_event_path) - except ValidationError as e: - logging.error(f"Error parsing event file: {e.errors()}") - sys.exit(0) - use_pr: Union[PullRequest, None] = None - for pr in repo.get_pulls(): - if pr.head.sha == event.workflow_run.head_commit.id: - use_pr = pr - break - if not use_pr: - logging.error(f"No PR found for hash: {event.workflow_run.head_commit.id}") - sys.exit(0) - github_headers = { - "Authorization": f"token {settings.input_token.get_secret_value()}" - } - url = f"{github_api}/repos/{settings.github_repository}/issues/{use_pr.number}/comments" - logging.info(f"Using comments URL: {url}") - response = httpx.post( - url, - headers=github_headers, - json={ - "body": f"📝 Docs preview for commit {use_pr.head.sha} at: {settings.input_deploy_url}" - }, - ) - if not (200 <= response.status_code <= 300): - logging.error(f"Error posting comment: {response.text}") - sys.exit(1) - logging.info("Finished") diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 0f2fb4a5a..7d8846bb3 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -5,9 +5,11 @@ on: - Build Docs types: - completed + permissions: deployments: write issues: write + pull-requests: write jobs: deploy-docs: @@ -41,9 +43,22 @@ jobs: directory: './site' gitHubToken: ${{ secrets.GITHUB_TOKEN }} branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - uses: actions/cache@v4 + id: cache + with: + path: ${{ env.pythonLocation }} + key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01 + - name: Install GitHub Actions dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: pip install -r requirements-github-actions.txt - name: Comment Deploy if: steps.deploy.outputs.url != '' - uses: ./.github/actions/comment-docs-preview-in-pr - with: - token: ${{ secrets.GITHUB_TOKEN }} - deploy_url: "${{ steps.deploy.outputs.url }}" + run: python ./scripts/comment_docs_deploy_url_in_pr.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DEPLOY_URL: ${{ steps.deploy.outputs.url }} + COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} diff --git a/.github/actions/comment-docs-preview-in-pr/requirements.txt b/requirements-github-actions.txt similarity index 55% rename from .github/actions/comment-docs-preview-in-pr/requirements.txt rename to requirements-github-actions.txt index 74a3631f4..559dc06fb 100644 --- a/.github/actions/comment-docs-preview-in-pr/requirements.txt +++ b/requirements-github-actions.txt @@ -1,4 +1,4 @@ -PyGithub +PyGithub>=2.3.0,<3.0.0 pydantic>=2.5.3,<3.0.0 pydantic-settings>=2.1.0,<3.0.0 -httpx +httpx>=0.27.0,<0.28.0 diff --git a/scripts/comment_docs_deploy_url_in_pr.py b/scripts/comment_docs_deploy_url_in_pr.py new file mode 100644 index 000000000..3148a3bb4 --- /dev/null +++ b/scripts/comment_docs_deploy_url_in_pr.py @@ -0,0 +1,31 @@ +import logging +import sys + +from github import Github +from pydantic import SecretStr +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + github_repository: str + github_token: SecretStr + deploy_url: str + commit_sha: str + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + settings = Settings() + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + use_pr = next( + (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None + ) + if not use_pr: + logging.error(f"No PR found for hash: {settings.commit_sha}") + sys.exit(0) + use_pr.as_issue().create_comment( + f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}" + ) + logging.info("Finished") From b8a06527fcee1b15adb2d24b75f6dbae36ad8b40 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 31 Jul 2024 23:40:27 +0000 Subject: [PATCH 646/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 385133266..5701c21cc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Internal +* 👷 Refactor GitHub Action to comment docs deployment URLs and update token. PR [#11925](https://github.com/fastapi/fastapi/pull/11925) by [@tiangolo](https://github.com/tiangolo). * 👷 Update tokens for GitHub Actions. PR [#11924](https://github.com/fastapi/fastapi/pull/11924) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token permissions to comment deployment URL in docs. PR [#11917](https://github.com/fastapi/fastapi/pull/11917) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token permissions for GitHub Actions. PR [#11915](https://github.com/fastapi/fastapi/pull/11915) by [@tiangolo](https://github.com/tiangolo). From 643a87cc848d9daf0d44b460708f42a202c29652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 31 Jul 2024 21:18:05 -0500 Subject: [PATCH 647/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20GitHub=20Action?= =?UTF-8?q?=20label-approved=20permissions=20(#11933)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 👷 Update label-approved permissions --- .github/workflows/label-approved.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 939444aaf..0470fb606 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -6,7 +6,7 @@ on: workflow_dispatch: permissions: - issues: write + pull-requests: write jobs: label-approved: From 9d41d6e8a82affdb7e40ce16800f41eec61397ff Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 1 Aug 2024 02:18:34 +0000 Subject: [PATCH 648/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5701c21cc..62d566403 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Internal +* 👷 Update GitHub Action label-approved permissions. PR [#11933](https://github.com/fastapi/fastapi/pull/11933) by [@tiangolo](https://github.com/tiangolo). * 👷 Refactor GitHub Action to comment docs deployment URLs and update token. PR [#11925](https://github.com/fastapi/fastapi/pull/11925) by [@tiangolo](https://github.com/tiangolo). * 👷 Update tokens for GitHub Actions. PR [#11924](https://github.com/fastapi/fastapi/pull/11924) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token permissions to comment deployment URL in docs. PR [#11917](https://github.com/fastapi/fastapi/pull/11917) by [@tiangolo](https://github.com/tiangolo). From efb4a077bebf5e8cd27d1d2de076f64fac26b31f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 31 Jul 2024 23:53:51 -0500 Subject: [PATCH 649/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20add?= =?UTF-8?q?=20liblab=20(#11934)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/docs/advanced/generate-clients.md | 6 +++++- docs/en/docs/img/sponsors/liblab-banner.png | Bin 0 -> 12453 bytes docs/en/docs/img/sponsors/liblab.png | Bin 0 -> 8637 bytes docs/en/overrides/main.html | 6 ++++++ 6 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 docs/en/docs/img/sponsors/liblab-banner.png create mode 100644 docs/en/docs/img/sponsors/liblab.png diff --git a/README.md b/README.md index 43cc7198c..739e77627 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The key features are: <a href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> <a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a> <a href="https://fine.dev?ref=fastapibadge" target="_blank" title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"><img src="https://fastapi.tiangolo.com/img/sponsors/fine.png"></a> +<a href="https://liblab.com?utm_source=fastapi" target="_blank" title="liblab - Generate SDKs from FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/liblab.png"></a> <a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a> <a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a> <a href="https://speakeasy.com?utm_source=fastapi+repo&utm_medium=github+sponsorship" target="_blank" title="SDKs for your API | Speakeasy"><img src="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 39654a361..8c0956ac5 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -32,6 +32,9 @@ gold: - url: https://fine.dev?ref=fastapibadge title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" img: https://fastapi.tiangolo.com/img/sponsors/fine.png + - url: https://liblab.com?utm_source=fastapi + title: liblab - Generate SDKs from FastAPI + img: https://fastapi.tiangolo.com/img/sponsors/liblab.png silver: - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 136ddb064..0053ac9bb 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -20,7 +20,11 @@ Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-autho And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 -For example, you might want to try <a href="https://speakeasy.com/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> and <a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" class="external-link" target="_blank">Stainless</a>. +For example, you might want to try: + +* <a href="https://speakeasy.com/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> +* <a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" class="external-link" target="_blank">Stainless</a> +* <a href="https://developers.liblab.com/tutorials/sdk-for-fastapi/?utm_source=fastapi" class="external-link" target="_blank">liblab</a> There are also several other companies offering similar services that you can search and find online. 🤓 diff --git a/docs/en/docs/img/sponsors/liblab-banner.png b/docs/en/docs/img/sponsors/liblab-banner.png new file mode 100644 index 0000000000000000000000000000000000000000..299ff816b8b97e8428eb53de4abcfe011bd15f02 GIT binary patch literal 12453 zcmW+-cOcb!8$V{pK1NnHAtAX!$T&u_S9W%G_TGDBlMu3!Bq7=JP+19CNj6!@&gOl* z=MOjc<~YCa_jx|gXFNAnL+w5ZAw3}ifgpLHD5r%$U^&B|xsllLwbkPfJNyI39sNKD zi9}A$sn5c<rhYp59$Mz!EG}-&)^?7MSv-7Q9<#`3Xxv61kXZ{#>ix=my(+rg+`a03 zUmq-KA#f}y`6-ntm5bzXaBzrlkOD#i0>Zed3evTAb-0HRc$xH>1~2Hc>0aR6jv2s1 zDArQ-h>ge!A`mQy2XZnxJ~<nYe5JMZ8l^-|m=qORaFHA=F-GP7n6W^+uHzB01&yv! zbtA?a!}V63`{iR}wf3V``HUH*iDC;T8IAeeh1_9m*dKZ*Sdt_DoVd*}n>K6;%e+z( z@AE%B*Kl+HYtXj4v5Z@w=21wQdng}j{-doq>hhZlnfz3#_H!}<g4nn?%2+whw4Tj_ zHvJYVLiu8?2OJbhT?=jvVt19f#I`R;Evhn4Q`Ab@q_1N&%W_bh$p)^;!GB=B5-S&m zQc_iI@mT#{tekQDZzC>9Ox9d53t7Pbs4+*vcjs4w`>mEe3N*Kb#3{{+Gnd#<Y_PJ6 zC_}_xcMAI*`h?-tPp$#I&u$=D`7=(^*2s~#$O7}uD1&m{rYRFm&6L#CFccvH!4aO{ zRIHlE{0tt|VUk)&bW{{u#J`Qnl2QAappz%z80lgya<pjT#Vh&(iCi_2ES0w7(TZPA z2YKgvToK8iEmrqlUOsd5HjYS2kJbMEeqQkT-MoR|rF1=gUh2r5w)m(a!g+Iqtq^@$ zPlTWu-O*VPeS&q3;dr?b&9!UdcHcSj1`aGtGXH;c<cFc+A$NCo`fiB`3Bk`ZB}JnO zhis9o!r6Q%<Y7RoG)oAVRY;@Ev$@?PM`3YZ-gu1J;aN~5+I4S5vuNlLep0q7`1cPu z4Ykw%wsE|-{92F&&!0cf%%qJ#;YN|*<DeCbhLTP5hgadv4`UYUHMoVcRH)-3jo-a~ zjo&FSdq;<7bk&1m)C)x$6&V#Jn5B}|V^ue4YU`1^BFA;^dl;IHSU6lay%4khnz=e$ zvhE?q&~=5Fw$iF6b#PF_B~qhwq%)c<_;kC=n19^58WZR0>Z+b6dCzT8F;6n^kC%8P z8Y7@mGW@8?i-gtV&yT8yWx7=pf8M?0jY#gCL;l4|>!BiyjPU+qCD<_KL>j%Y?PF+Y zIBTw`7&Bxmhurp&&~OnT-t}w24=)IJ$_>$tS76WL@?wA=LKa%mTGvgM>#h@x48sY` zbdpUtcs1P<7XAm9%6>mFN5CAdtv%cxigSgO;m62`j+R#8@ahYAWoHu+5;95nNEc`X zNHRBfTU5Q%b*M0D36M0El?~S|dssFqnB_SCDOQL+L7|AxwDojtw9Kg1k${MZXxfJu zzjMQD(oxv|Cj5O{+c%#rwolH=bjy{Ll`X3$j*gCasfjuTN`?tOI|>_RH<zm7*3BQB zWT|l8ewwI8oxXN(6077WoISbm+pXc&mrS_63(Lb97NRI~(Zu`m^0{~2IayglyB2cA zJncIo2(WHdPW%aZ!ob8dJu*V2!7CzC7kqK<)pYhPR~*isjD)0Sa)Uo3&Nxb;$hT$s z*|TTxz<w<z#GR)>!A_U2_gbaRKHC;(G<K$0S0bbT$wnPH+PU@UwNmlU$r+S@qcF3$ z*H=ej?a~piL+p>KFJ6e5wIgity0&w2a{LeeVr8t(s%UakwaqYJy}CbU<jfl3!ca22 zy0o-ZqMpZj)8VpOQ0SN*tDU2Oh(Q|DfH@B_)8I4D2#pN>NAv%GQBY7=2^zHDoTZCR zNKjQ&46&GM^1hGk&%E7fE5vWw%D~D&9Y;s3;Nq@TO2zsy@Wd-8LS6C*_p)kkGjyE= zNlAE!GTih3Cx?90;1<a}@$1*GGQC?7$r{{_HX7vQ<j4X>aj#^fqr-(Ha`Y_68Vd`v z&FSIxqMzV@|B<5~Ja}+Hig70HWO<_=qEK}2CNa$xTdvxsV$TJYMyU>IbmzkMPmbo` zyXXB)2OWo+@n4qQVn18NecqYH;51D!QBy~uw8}=knjY~|ukZUsB&%>bI6C4IBwhBb zF@IfS<BJ}vu<O{{`EVjXH~uwwZ?Z*vwRX?0MT{WqBL|j?G`LMFXe2-AL*<XJ7i)0q z@LcV3RSXLEgAz<v@@$%7bbTRBH|UywwQYusIarH_WXNcqj6MPX%y({B#X~Gtp(v#Z zprF}gQ@wvXbSWl29#>CIS(!*;&aJ_z?xcZ}HOd@2wB5c2pF0VY562>W?VVc1xI^^> zw(fIu0q!4E-oWzi(aSsXIy~tZvsux<ZVlZ<Q69L&oxhyCyGXQXYjk)X3ubwGdLmgv zrQ5BmRXMe<I2_88|GEd~v%G6=b4F=sBS0%q{Dl8Xt{RszJ409OnIe898o-)A<7Rzo zd(5rouS;$O%SchdJ--&M(mz8*U4R?1va%QlqICL%FLl#?>zlzB;^-KKqR?kiQY^P> z!)5WLY1%H%PoQqmucgp$-o5+tCE?m)$4cZkZcC2S5$~QmxO;Pv4hsPJq+Oc_ly@p8 z9K~|q581*2cdcVN8JU`rG2>xlHIp`Rvk=oDDk($r&1Lc)3i9%*a8TS45<-ns=<oze znyRXjXhvboa5?V%cZq{b9%7^Ro&t7+xY+Q`?hyb3xn0|BTH?F`8zK5YNoLkYF+nn@ z$F~%5pS4OqzIuhr`f1MPoUtPeT2)R?I{Dea^8NewX=rFBH~yLa)QTcl+&y9-jYb#v zNHCS_UXv&@=BIfj>T#8dJ0jVz+)FH1&KEzNoSy#esD0jmDq_(MJ5;)Cl$1f#1sW4T zQdM2u^rLMG6ql2ewE!&~Dm%O7+DNJU@;62?4{nSqLi(Q6gYO+To4hvMnx-~e4w#}l zOW(Yql?n<FuLx<k5}>WT{m1Kss9xSqh(1^C%D+FmM-og)<LevsFQiL`0fiP9Ld3R= zBO{fHU#PsciB(Nel#BTIGOn^xAXlv}@Z{h7M@>wU0X`S!XV{@3opXPtTbf?IvRdj* zA1Kr_W48PfZ_whm4|iJUIDt;~M{rQY>XyL}K^9b5c74!)_w(n^lY>q6h?rhGp%=re zj=P?;w=lnvA^Pa@bJ4*{dV2a8?5e7&(a}-HoGWJ67rrDIeXxpEDz*^JqEGl;R?*tq z-95YQbFs5>ZDn8kwMy1qckA)@j|_NqEiD(ILTVi+c9Oi429{6G&V}{px?Gu(Y=pC8 zd&pk%^Q04+4+~=%upn7E(^fsi%tOP9b@EFYcpWh}Z~N{nwg#TKH5mW+fi8eyZovDT z>7HNn`SCg+d3Q2vX=$li38mMF`sgSQikZ31X5eMe*|F#P7>Oar9+jXpHK0LsClor& zClyZ0jJ}85RE#4u+*C?dR#pK45;_*b*(CVk6OLY@495H-{QRWEb^ox|K7O`<dcqIK zSXay6zaOsmrr&AMRtVL7KZ&WltgP(qTfd)A-@bi&dU{$n6Vy~(TpVswaho_ifB#b~ z<^4p4yB;eV5y^@i7FGHcE&mKRr&~13mS~A9l@{H6m6QlYo7-Kf5m_p)N9}3&4EMI? zI(vJ2&rS|(tgLcGT??U+W-;Ny*{U2AFx~xHrVnO<FW~APKYqMa&dtvs1o${qbU#os zZ^99O{93wFq#|7ViGzbfTwELm@A<Q5BZGsLPE(Cs>Mut|Mu3LhFV!g=>ona6@0=47 z5%FFhdot4+*y4Zit*58KXS=X-4uO51;U9Sz5M*g-iAHxoA8TuCJHubvo|mtlIIZT0 zfzFHjY*9V&(|BcT%cX2o%z3)Gu#m0Bu*G|G8rVyHy=WmKx^w#|phPYA?fdtfX%-J3 zKGfA6gF&v!nWo6`G(O&=!MIGX!pYwL#eX)5T?+&(L()^Y^@uDQMAuI!!_3>3Fmv9U zv^+(9Ff3Oq(dJ2)^xIp350l2F9(1^6?&T$XC^;zQh^#k$Ki%RV9T5?7tM>i-_o_0C z6cjrvLq)%T|6W{Ne0k5GFcKY(ae)z3G(<~7qo=2LCD)faQ{}Z*>AN>?LXx0mH-NMP z3s5V$`TtjVRk*&BJC$_N!QUxaWCHyir2>t^v-9uYzZ=y#71;DWgm)|%&Q-HPqtSA5 zpWxQlw|!Vn8LnN+e(|Ew|G<eqBReGpOE45;hK%f(Wyp$&K{ib}31`EtkfZya^Q}*} zh-c<N{}4uY%(;XtQRH*S%CQw_AcOehK4VvpSU(uy(e(cN>#qB66;T#aCR>-X>l_@4 z9I0?Hy-RN47y*~r_8&if%(8NEagkjU{!^4Bd3?NHAyefk$`BhH%dQZg+_%J(biZV{ z$La%o?(53Wd5!Cn2bTR?rs4dot*xJ4-XCv@B7hvQ(FS9`7ReuUpRB7lyiTBOfe$U` z1-DxDQ0&wR(US<VGbM3R5w@6AsFkqu-cn@8?lG^P@DO{{E+L)j?e6|xf&vj4*%j5d zrKJR~6Z@8;A|o-Hsc-?p@}(NwAN6_LF3vX7m6m{2Q~`^bzlk4iUSn9QW3R7IYgKGi zJ~k`qBANs6C6@bl_Xt|EVC?g!Pa|Vv)2)HoT?_jwL+p3&8dQvDt8gmP$s?f=gzwyG zfxe$=^pr(nrVvzwcpbTK?yTRtapM7J8qhC%ehwJwJn1~wuP>c!wgDgyL6J~WQid|U z(z>B|fMA|TswdEq86i!xs4)a&^7OppfyYWkP5oN8j2sPfy5G74TDiEGJiVPNq>e(D z$T6C<k;i;kK~BzbvX+mBr+33^cy;fl-utgPcPY;@`{zW1c7OLj?t9*HyjI4O4mDG$ z&)YP0j=948tKQY}XlDr|6*pDwF#lGH@9u9BCJ9jv4h~^qVF?Li78Gs5m)Ea3bJY&^ zR)-C$t?e$4M~Rn-PI?%aFR&W|0)qUck<rnm<>iZ`fnZ7Z-^5l2c+GfC<kqFNwO+@2 ztBcM6NP*|4M`Ti`0_^OvY$-oByntMf+Q(+el|L8wK{ZP?yL%K(#vDbD%(xq6-oA;{ z1>P*maLGWj#AUODi|h1xog5tjcjiY*wOMc76&F7NFoDazbEgIvD=RB2aAUb6$-v|G zkH)P5blhBQY-~I{Je-`Iyu6N`Q6yKdUe$YVjOEXB`!=~wdULace%#USa)oh2>cBGG z^R2d1w~e1Q?YgwYQMzT34-lwE5ukFI<Qr5^CmcDw31aBJ5QT+S-e|uLJja!RYkXkI zjTJ96QwZ>;O27Rz`>8fCpB^hWQ3eggIo88!oHwM+SKr);mlj?EAeeHZA&m5D%FVIE zEbjunVU;pdm2pJ02R<m!m^FuXW@T=vucsxH#>UO)<KyF#M_#{v9ia3oHTAcb_fA?4 zru(|P5qCok>#oLZ^rUg6`JXq<oblhg7YM@>STx=k&LjK(5<xv;tu1c*V29?nww~9F zn^aG3j8~XO(*RYFWB%djrK}vMR+84YB=C85n*xcOJhpUj@`ztgQL%fpOwUfp5FmOW zSDcGF?vkGMqx1ba(@M2UV~jKl3k$>gpl&oeLuA6JJLg>RN$7=a2lD~OTA|)K)8IjH z>#)Ubh6?4iOVl2g>R9bhZytaS?ucCje21Ii1+DXEqFPf^vt70)5K0FR56>l<$UcD% zrWd@(=mZz52P7vy+NA*kzI|&yoR0i+jrtB78(>lQ(#~ev#k7@RXwKfr8C*Q{�bh zi`T}_TybydNQ`Sv=N$Zo<_{ls0L*7avOu9(Sj?xe-w%-s!|Iq=^#D!dy|*$%MR=Wy z%VzksY6OZ%L0>=9qyp4rqXze$k3{hKZl2WXmhAi_^uYs;)Eb9ziZu3&K5{gu5v=#` zyONjz*P<gM`?LOA?oGd0P*6ahzzO5{HF<a7x175UWAC6HswOu8xx?&@3=PfFcukt? zp+Fsln_j>EJy;;i@-*~Kdmq5Dn9tVi<qW_LyP^G>J6)+t-}vFf8uw+jh(W*wXTdB| z=tCeD<m?J7`^O;0Xs%u*&++bmap&xKztgojKi>=r_LGOqO&~Iwr8?I{oZ{o-jhnp6 zm5O=z_;N*@Uk)t0HyBfLs$>d2eyYz4V-)(Ag!g6vO?WV?goFei9|;9x6e(lxoJ$0{ zK(`F|VV5g|=)&**Y|MNUu);>q^_T)zQHB;1ser>R?`dCXst!kC)7F5a^@=up!mK+E z)PJb(!>inudXtk;732QvW99I3psXeHoU13O`Hf+&c`tUSWQ#br0tv^#C+_a<2Ft+e z1IIIhES28}C%I}RO2x;0rsp5bFkw(69-GsQnUA80Njq?l_bY<ShgYQsdzReh?^Hg5 zk$pVvze(;4-QW-0PF6~C=*kTy5$9<~P)j>#B%U~nw81f07cy}e*Ix_U?HsRPy#i>G zi6`vZ-fTS~HMtvnE|C(Awkk@Nk<)i&xW&t>Q>rto{iD(I=FroD<;hBO9JKAvk9M<1 z;b!g#2_~{<6>r~SZ^FL>q{Lj0rH)P7`n0|u^l!ojS%64XC>b^v-r3o)x3_QfSfyZO z%+0)fA%`DVPxSUd+1&HnlSYEZH!d0GGyI5T{RBb>p5|`if|(Ec0IY=Zkr5%QZd3#+ ztw)EOiiCv3=39=;<s1nMZq=(Wk(ZaBWfjcs=S;f+j0jpwG;wpPiH7wR^kk3)?O2V2 zUWA6OE_LDpb=>36Pp@u01Ud`2j10a>MHs`YmMMU-ubCGOS{u2s(yUb)fs<!vXGa}} z*X1f|i8Ti07;X0DIj@0W(5X))IcPc+Lq|v6tvx&<>NlhIJ8qMXwUk_HED;tK7Ti>X ze~P6}=g5E@SXa|Ez8$g!E8;5|`b~ZPAz<?A>gw$DcUz%|8$wThe*FF0+WqG2qeEQ| z3QR<fn5R<3_$~d){I_p=%>=-Xs+)ZD@L?oMNnPF9&JHLnko<*h37;**^UNQjv-NcM z{5%W{=v2Zc9Km4_rX>cT5V)EbbbN#M7JT?$UVx3WJx>!86_6WKP2=`8wI4qU2@9`z zh(&j5YG@$#^Ta%Rtpt5Rn{*BT`bC_z4)qsx6na;}bM4uXZNP572st{5St{yf(OA=< z^b6pkA?ExjAZ+|m=8qaZWRO#>fs@O-XUF4hQF<&gj{9q)D+YD>GECz@6t)+8C>grk z-P}-UrQ%dkp?GuJXA?CJ8N;j1U^2c|&31ElPf%Dm-d`U|YI!9$atv^7Qc;(mk66Uf z|B3r^nbW@Jg-;NWD4(T{NFpmq>>0yyU6=hk!onTyAkQC%cxj?ULUmDSxXW<8w`FC@ zN=i?kJ_SXgV{GhLJ(17R>^9qu#m(HV8uJpkh-A=dJ*Y?8w3*FlnkgrdS6eBgWe6vV zN@^IXW41y>H2iYN(6Y;?&@J->AGGp&B{!h3XyQz>FC{Ck_`gZ#HgGy&O3EUu^mzqE zz>5lh`**q}Zs8ChD!)9#H0Wro+{m!JR@EsCh3zL6bSg@$U9P)1Q4RHa7k8rF8WH|@ z`CG0)Kqh~>5+2rmcei3hvPnhPB~D$=(X^c%H-;`o(k?yIz=uXg%GTF!-@cvi#zXZK z$OS`Jjp0Vo{UkynqV@H4R|YBQQnVsZI)#bKkB@*SpIrlBLLv)RR&2qt_|3(D@&$1L z)OcZjo>ToLF|QAFr*7F*G@r(RbMVRJ@v&cY=WY8D?g$MnEeiAsFc;B8(9xaz^2osR zqh-mwTT)VOA3u8h`!lh%HUBwIH1U>EEio(ZWF`XDexEroV&U*PpHaxU4E_O_bHKGK zE0bL~9e-3}p!cDAa7T{<TL1iUEUc|)J?0S+p`oJFHz*oHa?;-AN~<(sB)#Hu5HpJV z4O@^iB)i+{185Q8&|VHECQOM7U^7LWodh^xmz{J;oo}BW?E-ayF(R58W=^Y92a4$X zcP)l4W~m?v@4v=W&k_jT_rMmr7kDfrC3OMMk}dp%@Z}86ET`2JZY!{Qewklzb>hA| z9E&pK$9=$$NvoN^s@5C-jUi`;!tnw~oy|3=u}>ee<uD2D=C)TBxt-k)zBFGI!T37^ zoHW@L-u%biR)Xk2_WB2EYKb$OxA_16x^d$MKR;*}uLfh7Z8AuCIk}MMb@rn?)f2?u z1w*nCO}I`w8EvO<M0gfrSid+VC7D=10y|IY+O2ClBVpx8S0XrhUs#CUwH+T%O!Y~% z{l*)uQl6VPV_Dbtk5f}A21)Z(z&w=k;?E#@O%uT*M+Z{}|GrS@Yjb0l`jJ(S7b=_@ z+>&Q|+Vk?6g-~z)5=;zT7l&O^Xm{{of7Lk9ppkA>G4HX-zrDB<H_HhoG4S;6Kidmk zqKV<!h=3k}Q&1LQTAE?p8W?Kl0rkptZ`Oa8xfj8R{35TSLd=~FfFhcRbA%!8>gu|d z@FkAsR$;!1!=M<PPWXZ-G3CpUzbf&G-DBW}_#AGro}T?}+ME|{eKINh{}S^}Sn&|s zx&amNh4aWrzZKYnZ;MGXwMO=YBXp<ekQhc4nH$;e9JG5ayB}YW%-$(F`!wHANJvOd zP7Wmt=VA2GmVC={>lCwufLh?>w1(ksU*iWfrCsSNp}eYUf(qyG`o2@$wN8N)MIBSq zHqUikxP^#B!(4?Go3NS95)E#^Nf7AwFS+BK=*z6jm+x$QsNL{ub6Wfx)#3Og=mD48 zPvr_h9K0$n26CC&G7N4s3{y~Mh%zkJPYc^x+S=9C)jf-G3!+ixGXRzVQoa%<78ZrT zl-q*N{!TS9O9pVK_2g?tqN}X?U+k}sU-2<Pp$8u%DB#>RM6!a{vU^0$s}DXQSo`Fa zb>Tx8AG-MWpuvUcH-1!EB3YBVEUWZq<456^z{UM({Sb@<ZYo_}T{R$MKyZL5z)!QK zC~{E1!+=7EQC3h{iJHbUs&8#&;$_^j_%PvEGJLdFR)I~4OFy{2ztEKw%>`FqdjOsR z3-A8nw&e~-_*-${S*6+~!a_oz3qb4iNqcUnBO}qQW4TJj^u$qZXB*CQb908}&t2vd zX>ZSi8iQj4tqO`kGOq%LFu?GzeGSV|&*)1DUkX+$A^O-YDPulbM#e{)nwW)ckQoBR z;r(<jy{tZd1^ysdB_wiw_$d_K1`5AD{~4^K@4hHBuzAvGOF$}kVC-UI)@RAdz=Yb# zm7TDSH)rvmD{=^DKl%MN3%&wU_w@7xNCpqQyyr0fo>4MD^w@PRq-!CiZz=d}-842c z5$w;&x{AIf>;zsjIn1G{tU}RHM09l5moK1h0kr=efV53!m3?p8rUu6pAc?}t=)=p% zROHz4YYD$X#?Q+O0R+ebiQr@$T~pJUaw8F7a;^&s5gLF&V6Z9_t@>y!xMLOAZk6o) znb-w02U!3}7LK`eZ3rkiw~hibjZv-xz29`XsUjmIk*oz8qE5d=2_wT6M03?(E}P9$ zC>Lv$cK?bnvw<lTpOhq$-4Evg6#VYp1|SX)v6;PXPjF{>8vY;AibtbiIX*`53lzo0 zN!ta)AhOp(f)}|_#LOdxJ9daIi?Dxt?~cLW@bK76xF!-sO!pne2C&-V*RS8|@GvEn z=<vXY7YjIashgatb2epB1#eYDBVUJybqo==^W~azJ6hWD^TIYt9cUY98c>OT`)haX zzQ2O<3D>6kpf@}`3>O6N7EN+Z7$6@^FGvH_rOrOW5csp|NNHu!DL}063(_=kLBkgY zOj1|)py;BxB`v-&5JK=vn3ArTi?fM_1o39gj=V9c09$**`*r_cjDgpdQ_%KjnpwNl zz9q5TZyR2+vfJC+1_lO`wNJ9ez5h12FGDpwjf?B+?UmMBauLP&6TTG4QqiAz^XARZ zpN0tvvK-VVZ9##MAAzQyY;Z4;W5W_@9$1EO3vLyE0>9c7j64u?HejX56)rQS6sKfg z!MVx`2~~%gfb<+y+-JxQVQPbBhDieRL6DX>*$#3C%(juSaWfc`U%!4`AFtRw3W)9` zzj_rEqKsJj^XIM7T8`Nv@_5D4MMF?~Nf<MohYw}?p>Y(7z(fP8yOOSF5*p1SFllVZ z(B)unFL|_>cH8pHmXAaSD!g>jMf4LsP9)I62vo#J0L)Ve96~laUWNu0dXepDa8q^9 zK2zjCk&dr=q;aZ(xfYRK-Twg5`<Epjr#;MkSNbBauOQzUA_U+L{2A*|kZ=aF$j4Sz z&AZ>kJ;WG=cGuR{pd3O!MI{g}*IHOwnv;doPk#T7ju~5AwBku$a}fnu#huZY!Dqw? z=5mEe;OU|35BZ=r<{!Nu?S`N8KO!`-PgjDXO-)S&?*b=FhLMYh7Rs3`hSlfLthYe- z<u!70nTSPlbme+CA37IQzls^-@=0=Chm|1Yd@oW{-9SY{d4Y=vBdM&pnW6r_2n}!_ zeCIkMFDZ0NN=ilZPH(nzYgTHiVBql{SfIFhpYh}r6hHy(sRti}6A5V-8M7qrQpe^2 zs5s&5dr+ewV8I@9sTaul3LNLhJ{FRI00_OW6RCOrIT;awxgv{9<-f;*6NU0|UlJKl zfT_Y+J9DY!thhBmRY80t>Hp91LzQ&$t>e$%QLYSRq>*Um?jc+J@DxaPrQIv1?Q6uu z#r-EfJibiDUv*;3U2VwhMIgw2U+x01X@W7P=vEkz&4Csm`tU8xP@dXWY{hpGZ*suC zh9dSKx}dVQ_PKs@$attrUUr+T6TKs0w+{ZjoB*CRgXqfZ6c60pcf;_AYMp0HfCiQf z`|qvX_SrIv7zEIkwxyg>R8%w*%z_T`xJMla5d84bqbD_n@VQC8{RA%?YCO!DYz6d$ z&Ev-)tQbgRTKB#ygZ=r$$tm&aQ|vEKQ9vNZ4!0LdRI~rhMKgCaWPkefX|6Ncq2_0z z6;B;b=0?bBq-TaAhY)=^06+*awmplKFV+&dG1JMv4dn+9CcqQ}QyD@NafdNpIl-H> z#0r6dEjm2?{r#%S%GU&~V&vF>@sH=rgvTffH>f3>yELKDZ@}fEje<t`=_uU&qH4ks z3Kf)+gg7)ud#$vTG!kqM*{3hGN&yFLswWhRs@RMCgZST>RAlrmF$eAqRhoBxA07r} z;UfV(eg@NKXL9CT_{NPM>uNwaYHDheMvqvS0`BJF4kuS+-aqZJ0vmq^OqJw6xCx*l z!2c!97tQ^4Sx_!Q`fo4o&8>9?_zi&O9%Azn*EsH^;4D62V-bmeLr0xDE4VQbqR;!q z)tHwWh!uXgrna`FU=}nECO{TBvEkLcPgNt$lB`q=SJ8GdwK-Vr`*ddWN+;oS96!9G z@cdh%BTH_+uCBL@?~xBa5Y4Oc*`9|zi>QbQs8L{RltFn}|Jh)ZQwE9u_~F&Wc<PR7 z%MpG8Imb_M!V5e#zHQF5<-K@8*!XgM9q(^7T;1NDN2s&_h)A%J$T9U0u>WfEb_Q_) z^Z|;*Nl8fwCNk)pt#ukszPy1hE5U2@^w4iCP7e(Y=_x4}0I({+1QU3K@n*d+X6eTF z5R1{-+nA*JdktW6_F+h~X!j@Z#qvh&`EK0E0s{dAEGCSTL*y%dMjv!PTw_K?(lwFy zaHU|MU73-fo2+xr16>kDa!vAhg}pm~wGnp@KYEBDw~Sr;ET9}{KuAM+YAPhU;jdnC zG#CeM&0=1?dUdH@K7R%Z1G)0!Pch_g9&%oMXHk1`zNXiPMuL|t2NGXF0sZFBC3d24 zR7kp+1y#*x@d@pr0yNgAu+!7i|Fij~VlVIJwgVOU^X@%lIv4n}930P{KSvwd0Dq-r zK_S}}4}|k=Rz_h4zJC41x_WeM3>@4rn{5bIK-j0!LuR6$BPvrgH0`rMav2!Dhh$H{ z?Ejo}&(aBPyNYCW$t@fcHPqB3kM7Kp3T{;>y8LR)U-9l8taiY2<OTktdvgtI5!>*R z4ni<6yb89;UofYfryA39a~~NR5`NnRXj)MKA3=^gQ{{Ig5zSxt2%z5}hJp|saTE0Z zr5zM>CdS(j^IxV2pQy^TEeHasP!`~O*eP)+vEcJlK;y9r(_k2MFozjnx`3M*{?lo? znU0BxDWH4906RXDq4~}xrS<Q{o;1klQIVzP<*;3$s;Ua2G&UwiQC<ChImeWBO~kpH zlh~|zHY58vo*k~ZS9=H+vH&dL1clx0E@ov83V{zS_Lm+x@WkmRZ?ccoAlYS)dF`*- zK?B=XR90#f4Tb!iZVL`B(C|6=_aq`2ycGXg^J13z=Q%m?ia+@a44RDjfoJhvNN4{S z|I#xm^BsrmuTXRWkfaz*oJOw=LLNE<g$a~x!JQg|-2rTi47C?RH^5C)#K#Ia+aHGz zo|bRWA;f8Z+eaaZNi{L}(q{v?SEP{eVRC~uYO2|{8p5s(V{4p3ST6bVv&LcMjb?H` zL5MN$2z?Ub`+bg+xXNq+V(n6$WF69Qu%%(M2kHdi9446r6ByTE-Yot8P0A<+?_1*Q z>q`;)3e00TdQg2)D3<s{j2TMm5gT<}jo}kz<vxds7B8^$s%-|sjLyOGGpVwW_w_vj zsstTJK}l)AI|iv~%zvVv<W@ZzlarIZX98*Jg(K0S5^C592?@!#F(`U*FWy&%U@Hh% zApx0yb3u;>9!z<&r66fNjEx!IC=2{|=gu9sh5-1KAUMH6m5nBy0(^zKnLB?rI5-Go z6E%)_(f_;LsIE|#T<JC8NN>H&Ep~@QUh255S_+(JO2xos)`m+4V5pW3*|M-rR@<nT z>Kspb&pi26PcA|FCcO@w7rO+i!^*zPFt`oNTF{J0+9uy}>(<=%JqRm9uyE91D`sc$ zL0XTH^;g<lHE+NiEFAnCso)@(1wdQbQdZ#Y4d4&}(jl33b92+yrd%Wmz2~zsSOBm$ zHa<>6MYZ>LN*v-kKE5YAi#_<^b71G*N75xIXn6f{f*j)<?3T+w)%0TD6do5v#6?!Z z*d%F&T*Mw2nMazCy7Dq~O*wf71T^<s7r}x6VKE>IKmWHmm-a{zun1im$kiHiS8P7I zVjtuCtMgJj1ABxI07&6fXT+J7z$jj;oWU<Qkf6Z+rx3vp6uhsmPnDB01qZw1AJ`^a zu3#0Sm^dX$F(Jz!qQCa_HF>T-H!P<nj0EB1+`NqsmgAR~d3nL`wlF<Ed=T_O8;|RN zDF@uASSyy(m|ss`{xdKzR?Cj{{jt$eSiFL*IL3Q^LXgNnJA(lX;^n69J6gDZT6&hE z5qnQNyBk})NXmdM%oSL80wap3o)1=cz**AM)U0xx_yBQasg9wM5inun?j|ffhP!>! z7F9^xFi->o5WIegr-Spbh7~DO*!j{*C@d;kUt61PCy#MWb|#I+;iqVInZsrnV);9P zE-%&POe1i62%Bp4T$1O93zyqr`n-xWnJ`wr!cgjeah*Djbq&b(Q4d$1m9;emO%f$S z5--|dmL(nnw4;E*GH|Uj>DU^VfgCdm00H|PM+2V&=kFi{&ESbGflKsC%MPS~zDrF_ z4OB7eA+X){OfY|AQCAC+0HQm3-i2ga%(DNgAnt9Q+<;s;Rgt5eiu#rb@jpd*dAtZ` z7;D*?nLnU@HYV$q7Z)MLD+kpFke9Dj3QfAZJaCJf8%aU}p+3wnh-rZy0xGOcRF^;~ zegcW0X`{ytC^=3}{J%C~FQp~#tErK4yv6K3eM&h0{Dbi5O<J_2Wsz<f9_tx{5pMjh zOgR1>5s~mUaymMK)*i?=>pQ|7@3b=-z{&_)iZop%8a6OsYeL%OULVm($Akk0a4eZU zDUHJ1m0_kWSgKj^Tjc)9nM;}_{3ap7C0Jf_{#Bono12@FaeoBgrD@7V^7<_2eL-m* zinGvK*oy;OLDPuqY_jchQs*410YMvucR@w&>M5x|wRlYMFw&UmV`d0$2Ld-3>UGi= z?^oS`XC$O)Zr8E2Ws<c+L{gNBCCh%>oDuT*KJVtEcsVkghbbPieL{*lq&ZdnHphv! z`*fNn{vbZ`@Hz2^y6jW$>`vCr55f+zQZIXEm0~onEau~cI3iRy(=xOEIV;-QFltsh z!9zY%T7rZ36q|Z_^(OGIo@GYOb&TA6(c}iHqVn*n2T<|{%F0c_7eTP@Db0dBEX_sC zO0^D<XR=NEooCkjlM{9_&kEhi?gts+#Mkc1fK8~s-g7--FqV>Q+IKlOA_BL2R-v3L zo1kVLDi6f@qFaM#qJN8tix-Of)~$>lD}laGc!^sg<h{4ER3KGC`9|JUW+B7Vu@Lo2 z&dnuB`4$oiL4AWUX~r*9BSGQ<xMhF!S=GsLrwn+h<EP97AR_`YQ8sF5YN}qK0k9~? z2CJ%o_k*%^ll@kLm=s6BERaZ1=J?^T{}&k@Eh~kIhbS8MWo9Ety9vTFMUuMGl!{$Y z&y|Whj(|)$2xhhK_AhL+aD^~T?)XT+4oVPdZ2d8DrvNMi)P479nFdLUj>_)0hFzkJ zK8Q-EoGQx8YYfX_?aYG>sF|671e3a~Y-jb~eaMkuWwAg5Ry!!i4cH?7cs2chI$}+P zODp4tv%;W)EmRkq)U$2cD3~T&TU&tqP{19=-`DpEBe5l%7Jtq!EHIMZ4-5=!SLxts zPj?W&Eesj5#a(V3Uyn5VFXulEo^&0an$pq-72|MmSt|JdA!PmnAKCdPNS`46UIU@a zb^G>^b#>|J+Uz&@B+=2)adL%k-|_$hcWZ#KJ`znJxuX`;XC@F471e9?p|MfykZ*SR z2Qv#rG%2H@o?glLI_#8O8f#$Cy?ghLO!5$MrjH$R>j_YtyLaz`U(^r!xu?g@-X0V& zIY&V)WfA^W2bd*R1Y|Ea!2iCQ=!tl5+<;wii8*ATlfNV}n}Rj$Vm+|oRW@qxQt<i9 zmyUu^*#E$*3qu*U2KWM}33(2i4KQ&)m$E!yMsz*lRDB`G?+XA8mY*z|iVplHDJf>B zy679n1`H2exIU}DCF~UVa9tkpb(F^Ttbrh<4fl=CnmXfQT+PlcIz|Mp`AHnM@}OE4 zO@4A7`IAG{9JLZ@mU^!ZL$FsMU8kg=m~EXAj-`-h1>c+LuA3Dm43B$-;wd6T_8b#_ z1r%-QSE-6|BORRx6hvTRfZB3$5nT%fL$<Te6p)W?Y&vT?iSdhSYySb?a6!I-xsZQ* zXmt;0HOAE_OGVeni0GJUh|opb_PUsuA22XrhSSwHNl+O+5>$kr0qB7@!}LWK011H_ zWazrbM0RKZsLyX)AA;&|&4GPO2qz&oR#sIFyf`}mXRn}^0m3BUmPpo89m0QW?)pAm zTkm{i#92NzBTh$VDEz9%g87@JoiCmk`BF>EIJJFs&zLo>SJ(*coD0z*ldfEvu&!EJ zS+SX7QdG!}a?S41LH$8GHTJJ7v$3<YQjz&L^-mHMT&<52J)DHV&unbM`ko8xLxE>X zkC!+3z2`5k{v3`0i-SXBwj9f{{$8jtehxjj7G@WnvQ1OdzwwqrpIFi+F0iF=v$0`2 zlURrd3xm<klTLr_8j&jO9t+W90x1EU6Df#0bJT1eKD?T)l-{?LFC(2RoLyd3mE!Uj z7iz=a))tY?%)k$6&L;s^23RYHfTU|1R@>We>CB40*DV99I~>EJHXpkE3pRWyDA>}K ydfFZXaqp&y^n{IjSgyU?@&5nv{qlS;0-sQ!S8L!^4*ZV>hzIg&a_`Y*VgCc8oYOV{ literal 0 HcmV?d00001 diff --git a/docs/en/docs/img/sponsors/liblab.png b/docs/en/docs/img/sponsors/liblab.png new file mode 100644 index 0000000000000000000000000000000000000000..ee461d7bcad65f6edd6c622492ad162d33acca3c GIT binary patch literal 8637 zcmZX4WmME(wDuq%2uP=dlr)GmNGM%OO9+w@qI9>?-O{ZvNP{9E(m6_plG4)MAl&_5 z@2B_Pvlh&P^@BOF_fu!W)t@Td#<_!oKp<`_DavZX>n?m*VBdi6!Yv$e@Ph6vt)z{O zjXgE5HU~c%dui*rXqvjyJ2=@}+Pr>A@8aq3lK!!}`U3<4J8e-}txts;rTUDG4W;(u zr_!<}0^OX1heU-$r9c)P9UT`Pn^%CBR|q3P{!y){Hro&aGxbiYemYeKRXX~EumMbj zVl8Q}*r*I20zr>Zl6|c0k-3#+qes#^9>7V@@R*rPI<Au!2d^&g1|!~j0R1~;9YeVY zQ+ZF=ucH_-riiJ<ephNtA_w*Q?RQA@9$9iZ2bs4-E*64eT&5IpSAL@hV<W;!?qUpt zjbHy5XKk-<kF2eK(kki~#YEix|3}|7u}lb_sQb3zn>XAcrYkEe%JHq;-B|6F5fKqG zq4-o(RP1s$(<|uE(F0RcDe*#`I0YC51d=+<*yV`RE6B{v&EGx>_{aMFgS0v2`}p`g zQYC9IZjPl;5)zVnLmtFjtkl)-N>iEGFlJhR|Lb?}ZXf~*3Kl17tdhC$`*ho8zk8d? zoL=lSqa!T)GbdCGtW{K0gfg-c6Vd&>JUrOs=+Y~0;fIb455F`0eeic+KKq4E9vY&n zs|(ga8S=5PkOLlhft`n%UtB~FHEg~*=bR2S)g!ni7rno~pUA3q1Hq!2YGPuN``Xdk z3p0ppva=Htq5k~2_rXdZT~a9V>PSRXR1o#{_BM(nw2<PlUf#T3B@&6m3eLj`Yz?4x zu*ODE3RuVOcjT?f5k9ll(a}LX($dl*z>y(q+}AQPx{VkdAAgoDBJdr%4d*r|YOXcV zTb(j(-a*96%L@^JLMgxeAw9ymD&sN-%l7m0D=aJ&r>m%|OGQ$~cJuS|%ZMTJYio}? zBPm9g9h{uZ_|h03Hv63Iuk=wTpv3$xJ?i$BdP&w#^3RMrP$-<qo*3GPH&1@1K0r^~ zl8>T{kBb}p{X2{(E-8t5WUJ#Z6Oo{x;Ly-eNJvP}Yb#Szv;kC4PYdtnVs|W#pGW$& za=CFcKIdSa<07J5Iy5wtM5k#RIT#0zBav)A!T5N1K~mlWq%6_HL^@=<yB>{~mp(!n zMp|0@uIt)R1{=RB7I9_e<zLh}<ki$@T^a@>X%GmZ3|bl*ahqZ0%cr=wxK>tH)-~S$ z&W|ch+mU~eoYt>id3k$3*Vjiwh>3~u@$)ApCVH=o3q+XqCfq|t|3smrr|RqLndGBZ zA3P{j%eh(`VRbp#+<aX(G&+h=qDwHhzHXqSb8pz*!qW22ojb=-2>9EP!Y7RORj{4@ z*H;o;U8j4Cavg*?!TtUH63!<(&DYtA6dYV!qhn)RR1d5_NEbTMcSTdXpYEDIeE9H` zpPAXBJBD_KjTEi8xR``RHDD@*$H<`B&sR=PPM3%B&Ykla_diPFq-12SSC^iL{P*t< zOire+idhY08#Vceo_ns3vgfy95zs}&#-?Z)-th79880{D+*5z?;sunOnLTSVr*1jn z7xxTdd%w$5M}i+RJ?}7aO)@OZ%?n7;#!L0lF)1Z|>ZEx*7Q1feyHQ+s#@rE%KvFJ^ z6sev5Sa9Vhde8m5kg#_zx3x+{d5_}${rjv5-9LVmeB0sayn9E@*_nS@ef-eW(^GWX z`puiI-V5a;p3#w!k-@=LDpTv8_&jM&+RbaL#?HTv4aw){Ui&ws^9X&n1W?Pip9WD2 zLj?*;n6jm50?I+<gTq8P!Pn=%n!{p*1O>MyYKmBw^B5jy<2;#N#KOQJB`3!TZd+Yl z_4{|O^gTT~`iX&o0W^V^*LhDoQ}Hy##-4g$j^DY>#qrj{#m2^lgoFf?fwvyr9Y*Y| z#3l3X>3X(Tu0#29^78U_c6Q9m(NR&SK27i6lOtMsd)WmA$A*VBKiSI@Yz)Q?4h}m1 z?dR63G(jb?BLa?(j}>C+vP2xE=?M=Tc?D$I>ZBv<bW}4%97mBF1KAQx9L=vM`1CRu zXz;DZKIt$pFhnFPYiMh0(}+0CwY)_~kq3nkVr~qsudg$DpC50jXf~<c9l9S8@vr2s z4t{zCCKZQ3@++6ENx{p3g@uLBp9K>37mnY;;jzgQr(ZuIEp^)bUDb|4y@FLB0;;R| z?%ut-zps`fc^epmfFM)~3g_H-?$iD56H80Wu4Si**T*Hg6|yU|-U(>vH(}dg_*`Aq zL#Z}27_gCY?4A=}Q$2a|geS$;#00wcbbIC-&(kUPI%#yo<>jT&>)*K*6>9lni{W8m zbv|d+U%t3PRqf!JVj%GDN@n&r{Td!#SX*Q77Tnt0T<Oo+SX&cySyjKh0sx04bjRLR zkeA;-^YQHX7?qJR^}EXa4HU@MR&;c9C$4~y5KQFi>~BtZczA_z^Ru}!)~A`Pi;IiP z%lC-q42_Miul`*e9v=SjyLiGvV3D?Wa1hA9&%(ko<3Vl4qLz(^Nmz{LBr}wPj+oor zRMoD|%X_?39eY=b<z$&xSh(4BgIt4391|1s@#Du!qU_7N%ajschfr>uoSely0X-;` zL6uqXsDE-t3cBB!kdP2Gp!RlZVj>A4A^lN|hs9uC{9i|X{WR4Rb<&R?KRU?h7iX|Z z+v#Kq*l3!X&W{#r6&tQk**D*Y5`%5cZ!*==8u{kFv$C{QYV_^d_@+1%O_5p-4;x$D z)Whgjlhd;^3I8h^&nF4|UWcnSRs)t+RvGE(D0c<E*(Tpe(^RLK>mX@{5K~4OwfeO} z@^hH1Y%uId@n=;ih|fRM_!Snk)a~<>lu<Y|EJ`0rOQTk~NJm*YzkK;pUS6&}%RWXf zCN561E@suAndhPGPDo9Si%5N7-j#4qC5i2(C<jN-HAiMrJUV$K83o1HS7RKW!Jt2c zGG>xT_6!?bdWVKI78nxnl|RJ?V8dB0EiI+-TcO;~{RiQQpdVTZme)p#__9h03KBCi zIEQZO0f(Jz&r~-YrKYB~=wR^T;o{&VtQk5s6bG~Hg>H+@&dxG^Etr+A(JPIJz>!nZ z)YoU<!(|xC`=+R(5*Zj6n0fypPz4ML3ECC<PTtLb7bn##Srb*}SYqzWsAPwtrlzab zKrGm)IR<^X!`<CSYb2jaO7b%IgWvi@lQoo=Kb1X6wo!)?b;879dNA8`!66W0y7Q-* zb;k<3&yDewx3BN_@85lObjW(Ybg;9t6JcWj(TLOSz!^?`wQu&nmVEL2QN35O^UkaU z1w~3}DHkH3yqqUVt7>JK=bc8ajIe+}qu0@=%F4?8{CC}pw`s++b#+sw!#d_2V(28q z{I7h@EFL<q{49KuA$zCr??8@}_c520)OC9(!Cgt8)BWX0IG>7&`{DU`6Tn8WoaICe zgu1To$@*A{u>Gvh`C;$m<mB-1J`~hFso?I#t?7E_#ja?+KX|o1r+ZJlyc(cgXq+na zYvjeZ<exsp?~HH44#Xn30@*U;dg|k6Z=0v|(=7~uA%DHvZbq!QXz|V0>h!I+vm=-V zER!|deSCa;w)!RRy2?F1#|7E=8sz6e``N~L%9t_O1CS{RIa8yfu%<AJ_c7nUOQ4bo zx-FbqENgz1J;(Zz^40ziN;eq|!9~7twDC(l70|`+pig+;2rIu7Co4Hwj!x(r*lKKa zG|q5-Fi!?qN#nNq;RADioq^*Z7JdA8?~{n66oWhxV&b0XT{a_y@&0nxr`=L)IBM7^ z1LlMSIhNe{ox`;eC*%1PW52g%Y|N9|>|!oTO1F|fV=dTF@6NT)c+)Ei-MbgON}iUM z#u(ho>0)QcLuQU^z$4Ab{6JQ_&kYbW$R7W0#eGhr6Y~(alBA@h3iq;H;DzGCLitw@ zBy(bi>m&J1S`hmt*qy{ABr=TQJ#_nD8!dVhfC-A-8{M`hVX9#<Vj?187p~ICXRGhu zzXw?|_{H!{?^okeX<3<RdOj!__hm8VrI~N;!gkZSdZ)la%nIIoX|gb*A%@icR7M*c z8&OeFQrtu-$=PVSSiF9vLF_Vsl7a%Q=g(FC$;whZw-&fm2)}3+Q#7D;baHkEY?{}^ zS%_n9ivLg5f(+$JDJd!{Dk;Hro>>Gv#UQ3@NX=qXYvFY%b$yw*WZmrdk9l(10y*gF z>gph)rWT8o_P_pjf(QVW8~#?QQkq1^76wns)bHP^Sy|jwi1VGvsj1?~nS;1SjrA=O z4z;ArU}U~lM^BIS@#X~dt9e({TEY+_0Pt7K#WQ(r@A>oR#*H42M~R3;U$g)AJ%sW_ z1kgTo3k%h#ns^Q3@zJIMDHYY)++19GI?gZ7b1#OqFpI4TMZ9a~G8R#wqrAL4Tyn0s zox}1+FLwh%m-af%v*>Z~TTuf8Scsq563;IQC)ZY2*(BXf?CkK1@WRvoR$wQPHxv}e z6sp88Rm9t8Ib&gk{;DwM{3wJTEZJ1|0z<<gI3_0MCIXLINY!Fm$Zhj?WhHN2pJfef z+|kj|kOmV|fl3Nb>zjnUf4^=h;d0y7DDy253sWd}c6G6cit2~!{~$d*mHiWf$ALvg z-Pz=Ou>y_jbGqBo@<>f>0OWUmKBKYmA3(hJ8$Oc$m!R#sqB*&^qN1YUsl3q8?tHn( z+&4}@|DK+nMnt*7j~M>~*S~Ba)gESMEIDp7tKu<kQl+bz24SJ0fo9dbcQH0L28xe! zWQ)0NanFK7t=b^xMwiB^;4{UDJ+iWf?sLuCkp!osk_71XlCJ`$oKM-E6hPj>zk z@njbkvJAQM;yrKnli-qfG<&(X(8;W;qNqskC?fRW0fVTn#dxBHnOxzv`|eyTvv4vc z@684#GCfDfJz#;DyHYWC(U@6TABu{$rX74#Nh#N_S*d8gl2&kbcJ}r4{kFP!p)<F= zZD(O2Tg6+Cl~7vV$lTNuicg!)_flC|IYN~p3H?9W!E<AvEf`lRhA|`KvS;W~dV2cg z!~_xh8$eYkp1iA|YfNqd`8=j~*4EaI{@2;7jHlLS5!@~|HtZS?iXZ2Lb7EFw9+po0 zW~lNL$r1xt8!n8iT*~$IgvFMNo4c>SpXE*o4#vCE($W{yYuv(=#pTUT%gXz;SWes1 zqQuc!<8oaHI|Jn)Fg@`9_(T)qrLOw39u}(#8GrXmw!rYbIDV5a<8rKVkC24q;9x+C zgm&3M1Q3knL@p*QOg)L0i#*b2h6z^fn9@-0aDC-V{D%)JCMpU~L`DHai6&P(Eioy9 zlZZ|50;#G_WDhI{hph6R>v4?>-~qqoPtaW+XZs&LGRd+tGc%umwd>^|Q_}2p-54jL z<r5HCIyl2IR{jU9Juxu>j>{w18Kfdeb)So4ZjH~3ODlaD%!^o5Kiztsekhg8QD2QG zcE;6s%dAKq3sTF%;scGFyS|prqZj}69<lx8XC->VFcI{%jg9;8tF6f|GYQfN#PjD< zkrek)Ue8oiaO+vW;*p*AWe7X8cXrCL_u`pYzIgj+u;fO$S8CQncNEdrn~1QOnB(1D zdNHrl-T55<D^UrF?;k$M>gbFO4gDu&_mzH^(R!$>6ZWDG_|Ro^L9bdk-O<K|R&xlN zN<KvpH8s#r)YXaX73FTv85<f-(`ssbm2oHH2#<P6P1^Q_LWJh2tZdMYL~+H=jt&gh zzKfHcovI6t%yQ-|Wkto^qoXa<%(sO$2D&t93=Q0w!9n^GXX0#-Lz>~y$$eAX|Bn$f zC4J9<3P8UT(2B_>#cOET`tql#0y}@P{nfT(1)T^u_f?hegrh5pDls8}vD>L1B<GG7 zT>@yOvxC1sh$tI;FWiJOo=84RR5mio`u5FRQ!|04p2&S`^61C?W|!sdAP135+h65M zTeKE}NfDvJkp;UyuO#j=<Njx-C0*B(MnmPqeNN-VMdZd)rQO|65)z0b-0kh`W*b~N z5hhR*vM<>_(WsvY^6^E4hv#{?<Fzj=E^>2oFMEFDd*FNSLh8#+)cI_+qoadCCWP&h z-RniD{7WeD_V#uS;=7KLewUOK6bkp;-_ty<22VLv`-VxkI9Pf<oP<@qXD(a9J4{(K zlbws5{qalr7#b>SY89uG;o)J>@{WsLO1?fs4FdFFTN0402n68z%WApR^>t$XZ+EDv zzuBzm5uasbWbBb-zIyda)|8eqL`PS5@x<EJmZUx>l9C2u1Q6q*H28_V7JO+i>#VFS zh%|B}ee<_zQD#+P)i+#RT;eXo;q4si4G*Q@r_UfZzkC@RACFMIZ)<H$SkD_KPC8Vw zxw%O?ln2}&6&-zXv{6)E-fzM8P)sa6BLke6?W<QXA*GH&AcFrj&eB)i1}tyij^=(| z3y`}x^_AcbMc})4b%u5}Hf#3H|Kyz(#><|AoB5G)|DM;<p&un)SEi`5xVSh>Mau6o zH7<_cnArACTAX1Xw6p)^p2B4|NN>oFsD<sASy)gmfw!rJ9<dgKvb3M5#zgEwiRH<J z!rrHf^EH*1$F$EIHu+2p48$VwLfiGfdwqdKA}x(7vA49m99;8WZz5|vdR;^WDw<k& zaPwA(De%j^d-wMC_IxDoUZ|=0NJ&Z6HME=`Z45Cc;!^Mg5oztret-VmOYjH_a0^wc zUo$xH^QS5+E9-iZJJz#j&%jJ3d$4hEDC6%~=ubc~WnNzFFaLmb$(kK>blSdt4Jfe% zY0Ms74Q!a3n;RkkW})?c5A1l@3bRHNWyI;lMLS8nv5>0Mql5(tO<mnkQ%dDWOfgke zjv5;AbwS2WK95UY;8F1ftv=rV(|mscgPMXO)Kt&PiWT)5P-JRo=&h-qzCM*w47Q_u zEZyxLO?CB3&}G1*XN~)0KftktUq!!}s&)N$4*C_eEX#TrBpLG$gTuO0iNb$POoUVH zfNOMU?)av-S33n13Zf8!0I7O?`Bw@HkFwITFP%vtM%~>rG9uzrX{ok`M!oZ2{7x;T zF;zKPLR=g|mxWf?jz;w=#)&zXEW8|?lYs%sg3nWYwj-Pb$Z}?81_*sma;MS(K-AY) z0%0=w*@lA0P#yF<HU`WKwz`0aI%5AfNZX^!dI@<;%fhe>EY}@%Vj%Qpmo?3JW<hKS zE*dXd8a)qyk-4fY%*+-55uucTuhDPZfKvJo6(BY{Jaj4MQ!E|?@dl32;ahPrJ0s(} zRueq~gEpKurlzL0wz!Bo?-QPVs#G!8SAUv(F>j!W$NyMv3;X;Q9cy7mOV)&!5~gL| z9kVr3Gyod?L%HJ{OUs+OCnC-(cm@?Gpp7LZC6kkrSC68o_;1=_U||&mTf>S$sDmG8 zeUiR3H-{*&$HT)jF<?3!X>VuZ;d%PxNm+IE@Yooc+y(-%xwS=0OIvSf2hRhj)uoiy z)Eul170lO`lyJIyR#a01kP7i+yDRQ7I5Dxdwe@fLM+$^yOkbm+@}Fjk47If6e)_~A zDoQ1EZ}s}^lS$~VKh6F-(5s-pXj3t6yoClzNl5`nP-km&-=R}FX77Oxl54CW<lx`{ zK6v`{DR2BEC#PyfL{546_Gg=sn*?;zv$NSbIsSk9vp}oR(q^%16}B7)x0*b<SN7%0 z5h|H;RTe4sJ|)G<!UCAlYJaJh245k+UG3R3a^-s`-FN+4m>VG!Ezr!n7pRTzv%3Wn z%j6<<T-~6?@-|n<01H8l621LHVPRpto5gJl9HAj0@@8g?O)0l<aRH9#HAI1nO?p9< zCyHa^Rh{k52liYA1Ry-lfo|usi?xc{BsiayI=H&Nv9s&qRi!7K8{q|bnyq(M_#h+h zd;U30<pQKp$3<T-E=7K`+1dUwz@!89x%~0g)X73;BxBL##h>f#Uln&7EdeR#`oSy! zS&=569j+w?2X~H@=niGq)(SD+l^87|8MCCO&VaNoJgmxQghjgrg5NTdTg6DEgM$O5 zsMCj2rp2uH0)m3`)$CAP5GDp<`kl^W6)!;jwPqm;HWE;8UwsM>zvZGJ2@)54T<<_a zve7rU$C%BK*Fr=9@>(-%0&F)J$W+x8SmqN|RlDiBc;LkSdhp%z?V;$1Y;jLUC$U%U z>ivqN?>AOgr<;5;`YdIhps#2Jzn*Cr8yTr7E8}Kik!K@)n#$WcK2E;Q>X9w!`^v%s zLqQ5+(Mn?uPEHvf4=j9|!QtWa%QI)N6{e;Ph&gc4yMg!F*?ar?XoX%woSY%y?Pg_F z6jojj90da=O+Y8^(G$l2VKf-xO(--dT2PHaw@5}uN8NU2xpT6ep%&tq6d;L#v-k`4 zDmyzHng<`K0kZM5H=xZc%F2uk4QVJStV~RJU!q7^5+@+11NMuH<2CERhAa@TJ=ZJT zpBBQ)(0(u7azjtZJY{5Lz$L-HunNjkipsdN^QBv>r{?6u8Y?|z;Qrju;034>V!FJ% z%*&P5Y7!J0+Fql0GZ@ID<Hz{qBoJ4mnrDcC;~r6LQ4y<nkijZQnn(fh1;=|J#9Daq zc>2(mnNex)47ff|vt3ny=yh;*Hs__RM60c=47dPsGB?bi%0l9*-yU)sy^g%$<44Tn zIH2U7aG%*m&t3Abb~A0frC@fTn+-WeF+lnL6)|~cj|eC$+k!n9M6}Gz(7q3~*>Q1o zogaYmY`bB|<K7WQw0gc<rt}ln3*;_d`<yjgFJ<Kc>+VK|G4ACT6wFLdPtVK%C3Zu| z(2|9mVz7t4;sDcZ2id8C!6caeT>Qb=*%;{&Qq8>XC@OT^mH;_y6uzP++;D&y^pR|? zsUgwnfMcWgKbV^{snhaV<~e-O!X|MukRibXXUss{;Q<mNKY;nVh6Z9$33MB>bHMJ? zHc(c<7kh4O6ciMftf3qNvmtTW*)gViMn<&5p2s_X2qKlD%vkuC!i4>xN@^_olvPyP zby;o(YQTj?Ggc}>iMc!pDZR12Ui;;XX&u7qbB_*$+S+@(c<mXay_}zu=qGY>=^^Kb z;q83^@Z03~uK_YqR<&$xlNF-F=ml=pmoHyxk1I#SLNw^t7#}}W{ql#&fStAV>dp>9 zEF-tH;WBumn+QZZZ(Uqya4@E-xa;|$jmRZf-l|jS8=%NYaDrb8JrofU5f!a(Y^1Tb zDeMQd+>_F%c=v00uvRhs$>lq{-H(2!yJ+8yq73+QLG97gATx$XN2kBo>N+|?j5q-~ z{NNzDkvJP0vaBo`=tAyo$)`_kZEYVyR0h%oagQmv$T{IXL_{c$4v_Y(5TO4T;=g!t z1(gf2;`zmema(XAtt>zMKZuv%^kBzj#|elAMM4-MS#?0qNqC{7lg#!WBmd*a;3VC* zj|l1LUKkj7oopKgl%Q2gQ;?B`f6#PubbPy)t)!#`1ccB%I`i?<)B6qb8;E@%Q<UH5 z)WN4xRbD;>pbSi2k!l)bxn?FN4)blnpa4J)X%s4u4;@MQU*QSw3ZlP>l-+P~bBi#H z?opM$F&h=Y%D`X>nh8o7eD31GS!ZV_BQ8frSC^#ce#f6b{?O(yanO18>gwtW3Rq{# zsYvJJlM{u$+a0~VO4FCFa5<81TB2>CVjdvIhrE^7kBRvg;>DhH-CO!2bB6>St*vjZ z`_K>p5bA-_QIs_QaQ2uaBRiXJRB-;&T$pKl$Un%%5D2_>x9#b0J1pVq>gxT2gS_RA z>1o3yds+c&5D#MjHqajL0t5exv`RLL)#INKhNB@KjUYWDO~0B!cmvm7h!&6}@Jxl# zH<sDMSGKmgy1MpLwct?udwQ^WPC|%NTGb+3P3B}O@owMFD=TeiIKNK=;Ukua^N0L6 z%{;(MYbZe&=H@lvVN=a_;0ke2D13b(f{asyCI*CN@)2*|L~{3{W4$36Su$L8Q4-); zWxKk#yngdWX<8goa7|6k!=od}f@P$on=ZD$X%xtpz4(5ooP2t65(n!PIRpieCGJ_B zlJX0(-u(Rh>Y5tUIV*r71A{wU=(sTJ_8319D-P@b-H17O<Q5jXU0t3*)G30at)&$h zm<Rak?i*bXKDL##6bcM5f(F04v-6&S04a_?{1MNK97b!JTijBgK7CSbg~aw{m7ed# z@ptFHPnDH%UVE)?Y~=k$8U^Yrz_rJJBnGKMo!>7AGEM*CV`EpgJ$U__7pbE>Dn^Re zJ1QK)e+P_6WYkBD8)%05*%s<y##z%76I7SY!PIJUa+oyoiZrCaK<SD?0@xQvzl_6C zpKELFepjLyMfY0N*4CO)zK@FwaD%%%zq5VJ_DZ;^gHx?C?`{)yz-tHC*7z(G&xAP3 zRiA$Na&7n{v7DUJ+)yrIjtCC^<nF<J5ZHm8%;oo<+J$b96cOP3_Jb=nXf8-8(o6Ai zaSx7<<=>6{`qeIVyPfJ2Z15hsOP+d<SruFz&gZbq&KCGk4hpf3sp78<=MthVL#=~y z35>=<<d&D)!RE4+y>xV}ij5^u;(MiNZOx{vhJF<EUryfgh?F=pB}LeC-y(r5?pc|^ z7qd<r>(*fCqr##hZ!fR>lV}5LMQ?9!(6~7Rf2zy@m^vYL8)BfQrncs4=VXQWbC4Xg zC^aSJ>FN-ZySuwc9rV=w$j(p2#c;(-pfvk5Ei5c7Rn(cK>D9{ea$mMYhMAj7@ZiwU z1FL=-WPh6~JwPrFK7L4FWqP`Sk58B<i9CGl;Of860yL(i=*r9A3^C=^e$GZ35)_n+ zX9QWM?Re?qTg_m)tgWoDT#JH&F!nSg(-pK$n92|*8aD%57xz+CEukk*<APU{0FPf; zTVKM_tpZh_^$Gv^{PnBWNjk590DLmR+TI>S!&+L$8v0GV!C${B%FD^IF`S~hKC~@6 z&5sHz9Z%W8EokTTbY`mwT!6M>fq5{knK*4u>9aiWXoL=Q-<b`kUW1%~-+C~2WyLbp zu~6aT4w}DpFhAr_v$anD0PMX~M?NzA-6$DUWl6N2cY3K|Y#bXE3sd;N<GS@4En&)5 Vi{?tz6m|lkB==OdT-xN_{{VhF)*Ao- literal 0 HcmV?d00001 diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index d647a8df4..229cbca71 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -88,6 +88,12 @@ <img class="sponsor-image" src="/img/sponsors/fine-banner.png" /> </a> </div> + <div class="item"> + <a title="liblab - Generate SDKs from FastAPI" style="display: block; position: relative;" href="https://liblab.com?utm_source=fastapi" target="_blank"> + <span class="sponsor-badge">sponsor</span> + <img class="sponsor-image" src="/img/sponsors/liblab-banner.png" /> + </a> + </div> </div> </div> {% endblock %} From 12a4476c3d1cd9500d350850ec4d68366a8d73a9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 1 Aug 2024 04:54:12 +0000 Subject: [PATCH 650/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 62d566403..748c4182c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Internal +* 🔧 Update sponsors: add liblab. PR [#11934](https://github.com/fastapi/fastapi/pull/11934) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action label-approved permissions. PR [#11933](https://github.com/fastapi/fastapi/pull/11933) by [@tiangolo](https://github.com/tiangolo). * 👷 Refactor GitHub Action to comment docs deployment URLs and update token. PR [#11925](https://github.com/fastapi/fastapi/pull/11925) by [@tiangolo](https://github.com/tiangolo). * 👷 Update tokens for GitHub Actions. PR [#11924](https://github.com/fastapi/fastapi/pull/11924) by [@tiangolo](https://github.com/tiangolo). From 1f7dcc58defe54aa2b391a6837c1e9f2ca2e30d4 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Thu, 1 Aug 2024 02:09:45 -0300 Subject: [PATCH 651/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/alternatives.md`=20(#11931)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/alternatives.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index ba721536f..0e79c4f77 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -1,6 +1,6 @@ # Alternativas, Inspiração e Comparações -O que inspirou **FastAPI**, como ele se compara a outras alternativas e o que FastAPI aprendeu delas. +O que inspirou o **FastAPI**, como ele se compara às alternativas e o que FastAPI aprendeu delas. ## Introdução @@ -185,7 +185,7 @@ Ele utiliza a informação do Webargs e Marshmallow para gerar automaticamente _ Isso resolveu o problema de ter que escrever YAML (outra sintaxe) dentro das _docstrings_ Python. -Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir **FastAPI**. +Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir o **FastAPI**. Usando essa combinação levou a criação de vários geradores Flask _full-stack_. Há muitas _stacks_ que eu (e vários times externos) estou utilizando até agora: @@ -207,7 +207,7 @@ NestJS, que não é nem Python, é um framework NodeJS JavaScript (TypeScript) i Ele alcança de uma forma similar ao que pode ser feito com o Flask-apispec. -Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular dois. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código. +Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular 2. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código. Como os parâmetros são descritos com tipos TypeScript (similar aos _type hints_ do Python), o suporte ao editor é muito bom. @@ -247,7 +247,7 @@ Então, validação de dados, serialização e documentação tem que ser feitos !!! check "**FastAPI** inspirado para" Achar jeitos de conseguir melhor performance. - Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta`nas funções. + Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções. Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. @@ -366,7 +366,7 @@ Ele tem: * Suporte a GraphQL. * Tarefas de processamento interno por trás dos panos. * Eventos de inicialização e encerramento. -* Cliente de testes construído com requests. +* Cliente de testes construído com HTTPX. * Respostas CORS, GZip, Arquivos Estáticos, Streaming. * Suporte para Sessão e Cookie. * 100% coberto por testes. From 3990a0a510004c3ed72e9669c0623a9d50f703ed Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 1 Aug 2024 05:10:11 +0000 Subject: [PATCH 652/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 748c4182c..9fe4be05b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Translations +* 🌐 Update Portuguese translation for `docs/pt/docs/alternatives.md`. PR [#11931](https://github.com/fastapi/fastapi/pull/11931) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10515](https://github.com/tiangolo/fastapi/pull/10515) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-change-status-code.md`. PR [#11863](https://github.com/tiangolo/fastapi/pull/11863) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/reference/background.md`. PR [#11849](https://github.com/tiangolo/fastapi/pull/11849) by [@lucasbalieiro](https://github.com/lucasbalieiro). From a25c92ceb9ab5be49901443d7184c149797192df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 2 Aug 2024 01:03:05 -0500 Subject: [PATCH 653/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Add=20support=20fo?= =?UTF-8?q?r=20`pip=20install=20"fastapi[standard]"`=20with=20standard=20d?= =?UTF-8?q?ependencies=20and=20`python=20-m=20fastapi`=20(#11935)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ♻️ Add support for `pip install "fastapi[standard]"` and make `fastapi` not include the optional standard dependencies * 📝 Update docs to include new fastapi[standard] * ✨ Add new stub fastapi command that tells people to install fastapi[standard] * ✅ Add tests for new stub CLI * 🔧 Add new command fastapi in main fastapi project, for when fastapi-cli is not installed * ✏️ Fix types * 📝 Add note about quotes when installing fastapi[standard] * 📝 Update docs about standard extra dependencies * ⬆️ Upgrade fastapi-cli --- README.md | 41 +++++++++---------- docs/em/docs/index.md | 2 +- docs/em/docs/tutorial/index.md | 2 +- docs/en/docs/deployment/docker.md | 2 +- docs/en/docs/deployment/manually.md | 2 +- docs/en/docs/deployment/versions.md | 14 +++---- docs/en/docs/fastapi-cli.md | 2 +- docs/en/docs/index.md | 41 +++++++++---------- docs/en/docs/tutorial/index.md | 6 +-- docs/en/docs/tutorial/security/first-steps.md | 4 +- fastapi/__main__.py | 3 ++ fastapi/cli.py | 13 ++++++ pdm_build.py | 27 ++---------- pyproject.toml | 36 +++------------- tests/test_fastapi_cli.py | 32 +++++++++++++++ 15 files changed, 114 insertions(+), 113 deletions(-) create mode 100644 fastapi/__main__.py create mode 100644 fastapi/cli.py create mode 100644 tests/test_fastapi_cli.py diff --git a/README.md b/README.md index 739e77627..aa70ff2da 100644 --- a/README.md +++ b/README.md @@ -135,13 +135,15 @@ FastAPI stands on the shoulders of giants: <div class="termy"> ```console -$ pip install fastapi +$ pip install "fastapi[standard]" ---> 100% ``` </div> +**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals. + ## Example ### Create it @@ -452,11 +454,15 @@ To understand more about it, see the section <a href="https://fastapi.tiangolo.c ## Dependencies +FastAPI depends on Pydantic and Starlette. + +### `standard` Dependencies + +When you install FastAPI with `pip install "fastapi[standard]"` it comes the `standard` group of optional dependencies: + Used by Pydantic: * <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation. -* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - for settings management. -* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - for extra types to be used with Pydantic. Used by Starlette: @@ -466,33 +472,26 @@ Used by Starlette: Used by FastAPI / Starlette: -* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. +* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. * `fastapi-cli` - to provide the `fastapi` command. -When you install `fastapi` it comes these standard dependencies. - -Additional optional dependencies: - -* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. +### Without `standard` Dependencies -## `fastapi-slim` +If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`. -If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. +### Additional Optional Dependencies -When you install with: +There are some additional dependencies you might want to install. -```bash -pip install fastapi -``` +Additional optional Pydantic dependencies: -...it includes the same code and dependencies as: +* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - for settings management. +* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - for extra types to be used with Pydantic. -```bash -pip install "fastapi-slim[standard]" -``` +Additional optional FastAPI dependencies: -The standard extra dependencies are the ones mentioned above. +* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. ## License diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index a7d1d06f9..dc8c4f023 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -133,7 +133,7 @@ FastAPI 🧍 🔛 ⌚ 🐘: <div class="termy"> ```console -$ pip install fastapi +$ pip install "fastapi[standard]" ---> 100% ``` diff --git a/docs/em/docs/tutorial/index.md b/docs/em/docs/tutorial/index.md index 26b4c1913..fd6900db0 100644 --- a/docs/em/docs/tutorial/index.md +++ b/docs/em/docs/tutorial/index.md @@ -58,7 +58,7 @@ $ pip install "fastapi[all]" 👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: ``` - pip install fastapi + pip install "fastapi[standard]" ``` ❎ `uvicorn` 👷 💽: diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 5cd24eb46..157a3c003 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -113,7 +113,7 @@ You would of course use the same ideas you read in [About FastAPI versions](vers For example, your `requirements.txt` could look like: ``` -fastapi>=0.112.0,<0.113.0 +fastapi[standard]>=0.113.0,<0.114.0 pydantic>=2.7.0,<3.0.0 ``` diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index 51989d819..ad9f62f91 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -103,7 +103,7 @@ But you can also install an ASGI server manually: That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. - When you install FastAPI with something like `pip install fastapi` you already get `uvicorn[standard]` as well. + When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well. === "Hypercorn" diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index 4be9385dd..24430b0cf 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -12,23 +12,23 @@ You can create production applications with **FastAPI** right now (and you have The first thing you should do is to "pin" the version of **FastAPI** you are using to the specific latest version that you know works correctly for your application. -For example, let's say you are using version `0.45.0` in your app. +For example, let's say you are using version `0.112.0` in your app. If you use a `requirements.txt` file you could specify the version with: ```txt -fastapi==0.45.0 +fastapi[standard]==0.112.0 ``` -that would mean that you would use exactly the version `0.45.0`. +that would mean that you would use exactly the version `0.112.0`. Or you could also pin it with: ```txt -fastapi>=0.45.0,<0.46.0 +fastapi[standard]>=0.112.0,<0.113.0 ``` -that would mean that you would use the versions `0.45.0` or above, but less than `0.46.0`, for example, a version `0.45.2` would still be accepted. +that would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted. If you use any other tool to manage your installations, like Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. @@ -78,10 +78,10 @@ So, you can just let **FastAPI** use the correct Starlette version. Pydantic includes the tests for **FastAPI** with its own tests, so new versions of Pydantic (above `1.0.0`) are always compatible with FastAPI. -You can pin Pydantic to any version above `1.0.0` that works for you and below `2.0.0`. +You can pin Pydantic to any version above `1.0.0` that works for you. For example: ```txt -pydantic>=1.2.0,<2.0.0 +pydantic>=2.7.0,<3.0.0 ``` diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md index a6facde3a..0fc072ed2 100644 --- a/docs/en/docs/fastapi-cli.md +++ b/docs/en/docs/fastapi-cli.md @@ -2,7 +2,7 @@ **FastAPI CLI** is a command line program that you can use to serve your FastAPI app, manage your FastAPI project, and more. -When you install FastAPI (e.g. with `pip install fastapi`), it includes a package called `fastapi-cli`, this package provides the `fastapi` command in the terminal. +When you install FastAPI (e.g. with `pip install "fastapi[standard]"`), it includes a package called `fastapi-cli`, this package provides the `fastapi` command in the terminal. To run your FastAPI app for development, you can use the `fastapi dev` command: diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 73357542f..4fe0cd6cc 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -131,13 +131,15 @@ FastAPI stands on the shoulders of giants: <div class="termy"> ```console -$ pip install fastapi +$ pip install "fastapi[standard]" ---> 100% ``` </div> +**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals. + ## Example ### Create it @@ -448,11 +450,15 @@ To understand more about it, see the section <a href="https://fastapi.tiangolo.c ## Dependencies +FastAPI depends on Pydantic and Starlette. + +### `standard` Dependencies + +When you install FastAPI with `pip install "fastapi[standard]"` it comes the `standard` group of optional dependencies: + Used by Pydantic: * <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation. -* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - for settings management. -* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - for extra types to be used with Pydantic. Used by Starlette: @@ -462,33 +468,26 @@ Used by Starlette: Used by FastAPI / Starlette: -* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. +* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. * `fastapi-cli` - to provide the `fastapi` command. -When you install `fastapi` it comes these standard dependencies. - -Additional optional dependencies: - -* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. -* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. +### Without `standard` Dependencies -## `fastapi-slim` +If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`. -If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. +### Additional Optional Dependencies -When you install with: +There are some additional dependencies you might want to install. -```bash -pip install fastapi -``` +Additional optional Pydantic dependencies: -...it includes the same code and dependencies as: +* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - for settings management. +* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - for extra types to be used with Pydantic. -```bash -pip install "fastapi-slim[standard]" -``` +Additional optional FastAPI dependencies: -The standard extra dependencies are the ones mentioned above. +* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. ## License diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 74fe06acd..f22dc01dd 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -76,7 +76,7 @@ The first step is to install FastAPI: <div class="termy"> ```console -$ pip install fastapi +$ pip install "fastapi[standard]" ---> 100% ``` @@ -84,9 +84,9 @@ $ pip install fastapi </div> !!! note - When you install with `pip install fastapi` it comes with some default optional standard dependencies. + When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies. - If you don't want to have those optional dependencies, you can instead install `pip install fastapi-slim`. + If you don't want to have those optional dependencies, you can instead install `pip install fastapi`. ## Advanced User Guide diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index a769cc0e6..d8682a054 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -45,9 +45,9 @@ Copy the example in a file `main.py`: ## Run it !!! info - The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install fastapi` command. + The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. - However, if you use the `pip install fastapi-slim` command, the `python-multipart` package is not included by default. To install it manually, use the following command: + However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: `pip install python-multipart` diff --git a/fastapi/__main__.py b/fastapi/__main__.py new file mode 100644 index 000000000..fc36465f5 --- /dev/null +++ b/fastapi/__main__.py @@ -0,0 +1,3 @@ +from fastapi.cli import main + +main() diff --git a/fastapi/cli.py b/fastapi/cli.py new file mode 100644 index 000000000..8d3301e9d --- /dev/null +++ b/fastapi/cli.py @@ -0,0 +1,13 @@ +try: + from fastapi_cli.cli import main as cli_main + +except ImportError: # pragma: no cover + cli_main = None # type: ignore + + +def main() -> None: + if not cli_main: # type: ignore[truthy-function] + message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' + print(message) + raise RuntimeError(message) # noqa: B904 + cli_main() diff --git a/pdm_build.py b/pdm_build.py index 45922d471..c83222b33 100644 --- a/pdm_build.py +++ b/pdm_build.py @@ -1,5 +1,5 @@ import os -from typing import Any, Dict, List +from typing import Any, Dict from pdm.backend.hooks import Context @@ -11,29 +11,10 @@ def pdm_build_initialize(context: Context) -> None: # Get custom config for the current package, from the env var config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][ "_internal-slim-build" - ]["packages"][TIANGOLO_BUILD_PACKAGE] + ]["packages"].get(TIANGOLO_BUILD_PACKAGE) + if not config: + return project_config: Dict[str, Any] = config["project"] - # Get main optional dependencies, extras - optional_dependencies: Dict[str, List[str]] = metadata.get( - "optional-dependencies", {} - ) - # Get custom optional dependencies name to always include in this (non-slim) package - include_optional_dependencies: List[str] = config.get( - "include-optional-dependencies", [] - ) # Override main [project] configs with custom configs for this package for key, value in project_config.items(): metadata[key] = value - # Get custom build config for the current package - build_config: Dict[str, Any] = ( - config.get("tool", {}).get("pdm", {}).get("build", {}) - ) - # Override PDM build config with custom build config for this package - for key, value in build_config.items(): - context.config.build_config[key] = value - # Get main dependencies - dependencies: List[str] = metadata.get("dependencies", []) - # Add optional dependencies to the default dependencies for this (non-slim) package - for include_optional in include_optional_dependencies: - optional_dependencies_group = optional_dependencies.get(include_optional, []) - dependencies.extend(optional_dependencies_group) diff --git a/pyproject.toml b/pyproject.toml index 9ab6e6d69..3601e6322 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,7 +54,7 @@ Repository = "https://github.com/fastapi/fastapi" [project.optional-dependencies] standard = [ - "fastapi-cli >=0.0.2", + "fastapi-cli[standard] >=0.0.5", # For the test client "httpx >=0.23.0", # For templates @@ -73,7 +73,7 @@ standard = [ ] all = [ - "fastapi-cli >=0.0.2", + "fastapi-cli[standard] >=0.0.5", # # For the test client "httpx >=0.23.0", # For templates @@ -98,6 +98,9 @@ all = [ "pydantic-extra-types >=2.0.0", ] +[project.scripts] +fastapi = "fastapi.cli:main" + [tool.pdm] version = { source = "file", path = "fastapi/__init__.py" } distribution = true @@ -115,35 +118,6 @@ source-includes = [ [tool.tiangolo._internal-slim-build.packages.fastapi-slim.project] name = "fastapi-slim" -[tool.tiangolo._internal-slim-build.packages.fastapi] -include-optional-dependencies = ["standard"] - -[tool.tiangolo._internal-slim-build.packages.fastapi.project.optional-dependencies] -all = [ - # # For the test client - "httpx >=0.23.0", - # For templates - "jinja2 >=2.11.2", - # For forms and file uploads - "python-multipart >=0.0.7", - # For Starlette's SessionMiddleware, not commonly used with FastAPI - "itsdangerous >=1.1.0", - # For Starlette's schema generation, would not be used with FastAPI - "pyyaml >=5.3.1", - # For UJSONResponse - "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", - # For ORJSONResponse - "orjson >=3.2.1", - # To validate email fields - "email_validator >=2.0.0", - # Uvicorn with uvloop - "uvicorn[standard] >=0.12.0", - # Settings management - "pydantic-settings >=2.0.0", - # Extra Pydantic data types - "pydantic-extra-types >=2.0.0", -] - [tool.mypy] strict = true diff --git a/tests/test_fastapi_cli.py b/tests/test_fastapi_cli.py new file mode 100644 index 000000000..20c928157 --- /dev/null +++ b/tests/test_fastapi_cli.py @@ -0,0 +1,32 @@ +import subprocess +import sys +from unittest.mock import patch + +import fastapi.cli +import pytest + + +def test_fastapi_cli(): + result = subprocess.run( + [ + sys.executable, + "-m", + "coverage", + "run", + "-m", + "fastapi", + "dev", + "non_existent_file.py", + ], + capture_output=True, + encoding="utf-8", + ) + assert result.returncode == 1, result.stdout + assert "Using path non_existent_file.py" in result.stdout + + +def test_fastapi_cli_not_installed(): + with patch.object(fastapi.cli, "cli_main", None): + with pytest.raises(RuntimeError) as exc_info: + fastapi.cli.main() + assert "To use the fastapi command, please install" in str(exc_info.value) From 450bff65f48a342473809336c1ddd2299838c702 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 2 Aug 2024 06:03:26 +0000 Subject: [PATCH 654/846] =?UTF-8?q?=F0=9F=93=9D=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 9fe4be05b..2da66b783 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Breaking Changes + +* ♻️ Add support for `pip install "fastapi[standard]"` with standard dependencies and `python -m fastapi`. PR [#11935](https://github.com/fastapi/fastapi/pull/11935) by [@tiangolo](https://github.com/tiangolo). + ### Docs * ✏️ Fix typos in docs. PR [#11926](https://github.com/fastapi/fastapi/pull/11926) by [@jianghuyiyuan](https://github.com/jianghuyiyuan). From 003d45428f4da83f730c736b24082a34e0fc7403 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 2 Aug 2024 01:08:25 -0500 Subject: [PATCH 655/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2da66b783..70142b434 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,38 @@ hide: * ♻️ Add support for `pip install "fastapi[standard]"` with standard dependencies and `python -m fastapi`. PR [#11935](https://github.com/fastapi/fastapi/pull/11935) by [@tiangolo](https://github.com/tiangolo). +#### Summary + +Install with: + +```bash +pip install "fastapi[standard]" +``` + +#### Other Changes + +* This adds support for calling the CLI as: + +```bash +python -m python +``` + +* And it upgrades `fastapi-cli[standard] >=0.0.5`. + +#### Technical Details + +Before this, `fastapi` would include the standard dependencies, with Uvicorn and the `fastapi-cli`, etc. + +And `fastapi-slim` would not include those standard dependencies. + +Now `fastapi` doesn't include those standard dependencies unless you install with `pip install "fastapi[standard]"`. + +Before, you would install `pip install fastapi`, now you should include the `standard` optional dependencies (unless you want to exclude one of those): `pip install "fastapi[standard]"`. + +This change is because having the standard optional dependencies installed by default was being inconvenient to several users, and having to install instead `fastapi-slim` was not being a feasible solution. + +Discussed here: [#11522](https://github.com/fastapi/fastapi/pull/11522) and here: [#11525](https://github.com/fastapi/fastapi/discussions/11525) + ### Docs * ✏️ Fix typos in docs. PR [#11926](https://github.com/fastapi/fastapi/pull/11926) by [@jianghuyiyuan](https://github.com/jianghuyiyuan). From b2e233867cdd255ac7cb86878d643d953c78f418 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 2 Aug 2024 01:09:03 -0500 Subject: [PATCH 656/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?2.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 70142b434..bcfdb07cf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.112.0 + ### Breaking Changes * ♻️ Add support for `pip install "fastapi[standard]"` with standard dependencies and `python -m fastapi`. PR [#11935](https://github.com/fastapi/fastapi/pull/11935) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 4d60bc7de..3413dffc8 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.111.1" +__version__ = "0.112.0" from starlette import status as status From e4ab536dc56af33c14467949fea9990b83673559 Mon Sep 17 00:00:00 2001 From: "P-E. Brian" <pebrian@outlook.fr> Date: Fri, 2 Aug 2024 21:37:52 +0200 Subject: [PATCH 657/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20French=20translati?= =?UTF-8?q?on=20for=20`docs/fr/docs/tutorial/path-params-numeric-validatio?= =?UTF-8?q?ns.md`=20(#11788)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-params-numeric-validations.md | 318 ++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 docs/fr/docs/tutorial/path-params-numeric-validations.md diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..e8dcd37fb --- /dev/null +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,318 @@ +# Paramètres de chemin et validations numériques + +De la même façon que vous pouvez déclarer plus de validations et de métadonnées pour les paramètres de requête avec `Query`, vous pouvez déclarer le même type de validations et de métadonnées pour les paramètres de chemin avec `Path`. + +## Importer Path + +Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : + +=== "Python 3.10+" + + ```Python hl_lines="1 3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="1 3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3-4" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="3" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` + +!!! info + FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0. + + Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`. + + Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`. + +## Déclarer des métadonnées + +Vous pouvez déclarer les mêmes paramètres que pour `Query`. + +Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire : + +=== "Python 3.10+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="11" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} + ``` + +=== "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!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} + ``` + +!!! note + Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis. + +## Ordonnez les paramètres comme vous le souhaitez + +!!! tip + Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis. + +Et vous n'avez pas besoin de déclarer autre chose pour ce paramètre, donc vous n'avez pas vraiment besoin d'utiliser `Query`. + +Mais vous avez toujours besoin d'utiliser `Path` pour le paramètre de chemin `item_id`. Et vous ne voulez pas utiliser `Annotated` pour une raison quelconque. + +Python se plaindra si vous mettez une valeur avec une "défaut" avant une valeur qui n'a pas de "défaut". + +Mais vous pouvez les réorganiser, et avoir la valeur sans défaut (le paramètre de requête `q`) en premier. + +Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par leurs noms, types et déclarations par défaut (`Query`, `Path`, etc), il ne se soucie pas de l'ordre. + +Ainsi, vous pouvez déclarer votre fonction comme suit : + +=== "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!} + ``` + +Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`. + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} + ``` + +## Ordonnez les paramètres comme vous le souhaitez (astuces) + +!!! tip + Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin. + +Si vous voulez : + +* déclarer le paramètre de requête `q` sans `Query` ni valeur par défaut +* déclarer le paramètre de chemin `item_id` en utilisant `Path` +* les avoir dans un ordre différent +* ne pas utiliser `Annotated` + +...Python a une petite syntaxe spéciale pour cela. + +Passez `*`, comme premier paramètre de la fonction. + +Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments "mots-clés" (paires clé-valeur), également connus sous le nom de <abbr title="De : K-ey W-ord Arg-uments"><code>kwargs</code></abbr>. Même s'ils n'ont pas de valeur par défaut. + +```Python hl_lines="7" +{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +``` + +# 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 `*`. + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} + ``` + +## Validations numériques : supérieur ou égal + +Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des contraintes numériques. + +Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`. + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="8" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} + ``` + +## Validations numériques : supérieur ou égal et inférieur ou égal + +La même chose s'applique pour : + +* `gt` : `g`reater `t`han +* `le` : `l`ess than or `e`qual + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="8" + {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} + ``` + +## Validations numériques : supérieur et inférieur ou égal + +La même chose s'applique pour : + +* `gt` : `g`reater `t`han +* `le` : `l`ess than or `e`qual + +=== "Python 3.9+" + + ```Python hl_lines="10" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="9" + {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} + ``` + +## Validations numériques : flottants, supérieur et inférieur + +Les validations numériques fonctionnent également pour les valeurs `float`. + +C'est ici qu'il devient important de pouvoir déclarer <abbr title="greater than"><code>gt</code></abbr> et pas seulement <abbr title="greater than or equal"><code>ge</code></abbr>. Avec cela, vous pouvez exiger, par exemple, qu'une valeur doit être supérieure à `0`, même si elle est inférieure à `1`. + +Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas. + +Et la même chose pour <abbr title="less than"><code>lt</code></abbr>. + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="11" + {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} + ``` + +## Pour résumer + +Avec `Query`, `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des métadonnées et des validations de chaînes de la même manière qu'avec les [Paramètres de requête et validations de chaînes](query-params-str-validations.md){.internal-link target=_blank}. + +Et vous pouvez également déclarer des validations numériques : + +* `gt` : `g`reater `t`han +* `ge` : `g`reater than or `e`qual +* `lt` : `l`ess `t`han +* `le` : `l`ess than or `e`qual + +!!! info + `Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`. + + Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment. + +!!! note "Détails techniques" + Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. + + Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom. + + Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`. + + Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types. + + De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs. From 9723721ea44a1d0eb76da4629ed4c9bf41480e7d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 2 Aug 2024 19:38:15 +0000 Subject: [PATCH 658/846] =?UTF-8?q?=F0=9F=93=9D=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 bcfdb07cf..c4df5e837 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian). + ## 0.112.0 ### Breaking Changes From 2609348471754a72061e35a99291b5a9992ad094 Mon Sep 17 00:00:00 2001 From: Wesin Ribeiro Alves <wesinec@gmail.com> Date: Fri, 2 Aug 2024 21:01:21 -0300 Subject: [PATCH 659/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/cors.md`=20and=20`docs/pt?= =?UTF-8?q?/docs/tutorial/middleware.md`=20(#11916)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/cors.md | 84 +++++++++++++++++++++++++++++ docs/pt/docs/tutorial/middleware.md | 61 +++++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 docs/pt/docs/tutorial/cors.md create mode 100644 docs/pt/docs/tutorial/middleware.md diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md new file mode 100644 index 000000000..1f434d324 --- /dev/null +++ b/docs/pt/docs/tutorial/cors.md @@ -0,0 +1,84 @@ +# CORS (Cross-Origin Resource Sharing) + +<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">CORS ou "Cross-Origin Resource Sharing"</a> refere-se às situações em que um frontend rodando em um navegador possui um código JavaScript que se comunica com um backend, e o backend está em uma "origem" diferente do frontend. + +## Origem + +Uma origem é a combinação de protocolo (`http`, `https`), domínio (`myapp.com`, `localhost`, `localhost.tiangolo.com`), e porta (`80`, `443`, `8080`). + +Então, todos estes são origens diferentes: + +* `http://localhost` +* `https://localhost` +* `http://localhost:8080` + +Mesmo se todos estiverem em `localhost`, eles usam diferentes protocolos e portas, portanto, são "origens" diferentes. + +## Passos + +Então, digamos que você tenha um frontend rodando no seu navegador em `http://localhost:8080`, e seu JavaScript esteja tentando se comunicar com um backend rodando em http://localhost (como não especificamos uma porta, o navegador assumirá a porta padrão `80`). + +Portanto, o navegador irá enviar uma requisição HTTP `OPTIONS` ao backend, e se o backend enviar os cabeçalhos apropriados autorizando a comunicação a partir de uma origem diferente (`http://localhost:8080`) então o navegador deixará o JavaScript no frontend enviar sua requisição para o backend. + +Para conseguir isso, o backend deve ter uma lista de "origens permitidas". + +Neste caso, ele terá que incluir `http://localhost:8080` para o frontend funcionar corretamente. + +## Curingas + +É possível declarar uma lista com `"*"` (um "curinga") para dizer que tudo está permitido. + +Mas isso só permitirá certos tipos de comunicação, excluindo tudo que envolva credenciais: cookies, cabeçalhos de autorização como aqueles usados com Bearer Tokens, etc. + +Então, para que tudo funcione corretamente, é melhor especificar explicitamente as origens permitidas. + +## Usar `CORSMiddleware` + +Você pode configurá-lo em sua aplicação **FastAPI** usando o `CORSMiddleware`. + +* Importe `CORSMiddleware`. +* Crie uma lista de origens permitidas (como strings). +* Adicione-a como um "middleware" à sua aplicação **FastAPI**. + +Você também pode especificar se o seu backend permite: + +* Credenciais (Cabeçalhos de autorização, Cookies, etc). +* 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!} +``` + +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. + +Os seguintes argumentos são suportados: + +* `allow_origins` - Uma lista de origens que devem ter permissão para fazer requisições de origem cruzada. Por exemplo, `['https://example.org', 'https://www.example.org']`. Você pode usar `['*']` para permitir qualquer origem. +* `allow_origin_regex` - Uma string regex para corresponder às origens que devem ter permissão para fazer requisições de origem cruzada. Por exemplo, `'https://.*\.example\.org'`. +* `allow_methods` - Uma lista de métodos HTTP que devem ser permitidos para requisições de origem cruzada. O padrão é `['GET']`. Você pode usar `['*']` para permitir todos os métodos padrão. +* `allow_headers` - Uma lista de cabeçalhos de solicitação HTTP que devem ter suporte para requisições de origem cruzada. O padrão é `[]`. Você pode usar `['*']` para permitir todos os cabeçalhos. Os cabeçalhos `Accept`, `Accept-Language`, `Content-Language` e `Content-Type` são sempre permitidos para <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests" class="external-link" rel="noopener" target="_blank">requisições CORS simples</a>. +* `allow_credentials` - Indica que os cookies devem ser suportados para requisições de origem cruzada. O padrão é `False`. Além disso, `allow_origins` não pode ser definido como `['*']` para que as credenciais sejam permitidas, as origens devem ser especificadas. +* `expose_headers` - Indica quaisquer cabeçalhos de resposta que devem ser disponibilizados ao navegador. O padrão é `[]`. +* `max_age` - Define um tempo máximo em segundos para os navegadores armazenarem em cache as respostas CORS. O padrão é `600`. + +O middleware responde a dois tipos específicos de solicitação HTTP... + +### Requisições CORS pré-voo (preflight) + +Estas são quaisquer solicitações `OPTIONS` com cabeçalhos `Origin` e `Access-Control-Request-Method`. + +Nesse caso, o middleware interceptará a solicitação recebida e responderá com cabeçalhos CORS apropriados e uma resposta `200` ou `400` para fins informativos. + +### Requisições Simples + +Qualquer solicitação com um cabeçalho `Origin`. Neste caso, o middleware passará a solicitação normalmente, mas incluirá cabeçalhos CORS apropriados na resposta. + +## Mais informações + +Para mais informações <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, acesse <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS documentation</a>. + +!!! note "Detalhes técnicos" + Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. + + **FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette. diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md new file mode 100644 index 000000000..be2128981 --- /dev/null +++ b/docs/pt/docs/tutorial/middleware.md @@ -0,0 +1,61 @@ +# Middleware + +Você pode adicionar middleware à suas aplicações **FastAPI**. + +Um "middleware" é uma função que manipula cada **requisição** antes de ser processada por qualquer *operação de rota* específica. E também cada **resposta** antes de retorná-la. + +* Ele pega cada **requisição** que chega ao seu aplicativo. +* Ele pode então fazer algo com essa **requisição** ou executar qualquer código necessário. +* Então ele passa a **requisição** para ser processada pelo resto do aplicativo (por alguma *operação de rota*). +* Ele então pega a **resposta** gerada pelo aplicativo (por alguma *operação de rota*). +* Ele pode fazer algo com essa **resposta** ou executar qualquer código necessário. +* Então ele retorna a **resposta**. + +!!! note "Detalhes técnicos" + Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware. + + Se houver alguma tarefa em segundo plano (documentada posteriormente), ela será executada *depois* de todo o middleware. + +## Criar um middleware + +Para criar um middleware, use o decorador `@app.middleware("http")` logo acima de uma função. + +A função middleware recebe: + +* A `request`. +* Uma função `call_next` que receberá o `request` como um parâmetro. + * Esta função passará a `request` para a *operação de rota* correspondente. + * 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!} +``` + +!!! tip "Dica" + Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">usando o prefixo 'X-'</a>. + + Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Documentos CORS da Starlette</a>. + +!!! note "Detalhes técnicos" + Você também pode usar `from starlette.requests import Request`. + + **FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. + +### Antes e depois da `response` + +Você pode adicionar código para ser executado com a `request`, antes que qualquer *operação de rota* o receba. + +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!} +``` + +## Outros middlewares + +Mais tarde, você pode ler mais sobre outros middlewares no [Guia do usuário avançado: Middleware avançado](../advanced/middleware.md){.internal-link target=_blank}. + +Você lerá sobre como manipular <abbr title="Cross-Origin Resource Sharing">CORS</abbr> com um middleware na próxima seção. From f0367e042459f339c5d9e882028d69bb7160a266 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 3 Aug 2024 00:01:47 +0000 Subject: [PATCH 660/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c4df5e837..7115e425b 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/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). * 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian). ## 0.112.0 From 25f1b1548bd1f4e42bd4576c0ff482d32973f170 Mon Sep 17 00:00:00 2001 From: marcelomarkus <marcelomarkus@gmail.com> Date: Fri, 2 Aug 2024 21:02:06 -0300 Subject: [PATCH 661/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/sub-applications.md`=20an?= =?UTF-8?q?d=20`docs/pt/docs/advanced/behind-a-proxy.md`=20(#11856)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/behind-a-proxy.md | 350 ++++++++++++++++++++++ docs/pt/docs/advanced/sub-applications.md | 73 +++++ 2 files changed, 423 insertions(+) create mode 100644 docs/pt/docs/advanced/behind-a-proxy.md create mode 100644 docs/pt/docs/advanced/sub-applications.md diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md new file mode 100644 index 000000000..8ac9102a3 --- /dev/null +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -0,0 +1,350 @@ +# Atrás de um Proxy + +Em algumas situações, você pode precisar usar um servidor **proxy** como Traefik ou Nginx com uma configuração que adiciona um prefixo de caminho extra que não é visto pela sua aplicação. + +Nesses casos, você pode usar `root_path` para configurar sua aplicação. + +O `root_path` é um mecanismo fornecido pela especificação ASGI (que o FastAPI utiliza, através do Starlette). + +O `root_path` é usado para lidar com esses casos específicos. + +E também é usado internamente ao montar sub-aplicações. + +## Proxy com um prefixo de caminho removido + +Ter um proxy com um prefixo de caminho removido, nesse caso, significa que você poderia declarar um caminho em `/app` no seu código, mas então, você adiciona uma camada no topo (o proxy) que colocaria sua aplicação **FastAPI** sob um caminho como `/api/v1`. + +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!} +``` + +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`. + +Até aqui, tudo funcionaria normalmente. + +Mas então, quando você abre a interface de documentação integrada (o frontend), ele esperaria obter o OpenAPI schema em `/openapi.json`, em vez de `/api/v1/openapi.json`. + +Então, o frontend (que roda no navegador) tentaria acessar `/openapi.json` e não conseguiria obter o OpenAPI schema. + +Como temos um proxy com um prefixo de caminho de `/api/v1` para nossa aplicação, o frontend precisa buscar o OpenAPI schema em `/api/v1/openapi.json`. + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy on http://0.0.0.0:9999/api/v1/app"] +server["Server on http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +!!! tip "Dica" + O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. + +A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo: + +```JSON hl_lines="4-8" +{ + "openapi": "3.1.0", + // Mais coisas aqui + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // Mais coisas aqui + } +} +``` + +Neste exemplo, o "Proxy" poderia ser algo como **Traefik**. E o servidor seria algo como CLI do FastAPI com **Uvicorn**, executando sua aplicação FastAPI. + +### Fornecendo o `root_path` + +Para conseguir isso, você pode usar a opção de linha de comando `--root-path` assim: + +<div class="termy"> + +```console +$ fastapi run main.py --root-path /api/v1 + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +Se você usar Hypercorn, ele também tem a opção `--root-path`. + +!!! note "Detalhes Técnicos" + A especificação ASGI define um `root_path` para esse caso de uso. + + E a opção de linha de comando `--root-path` fornece esse `root_path`. + +### Verificando o `root_path` atual + +Você pode obter o `root_path` atual usado pela sua aplicação para cada solicitação, ele faz parte do dicionário `scope` (que faz parte da especificação ASGI). + +Aqui estamos incluindo ele na mensagem apenas para fins de demonstração. + +```Python hl_lines="8" +{!../../../docs_src/behind_a_proxy/tutorial001.py!} +``` + +Então, se você iniciar o Uvicorn com: + +<div class="termy"> + +```console +$ fastapi run main.py --root-path /api/v1 + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +A resposta seria algo como: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Configurando o `root_path` na aplicação FastAPI + +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!} +``` + +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. + +### Sobre `root_path` + +Tenha em mente que o servidor (Uvicorn) não usará esse `root_path` para nada além de passá-lo para a aplicação. + +Mas se você acessar com seu navegador <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000/app</a> você verá a resposta normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Portanto, ele não esperará ser acessado em `http://127.0.0.1:8000/api/v1/app`. + +O Uvicorn esperará que o proxy acesse o Uvicorn em `http://127.0.0.1:8000/app`, e então seria responsabilidade do proxy adicionar o prefixo extra `/api/v1` no topo. + +## Sobre proxies com um prefixo de caminho removido + +Tenha em mente que um proxy com prefixo de caminho removido é apenas uma das maneiras de configurá-lo. + +Provavelmente, em muitos casos, o padrão será que o proxy não tenha um prefixo de caminho removido. + +Em um caso como esse (sem um prefixo de caminho removido), o proxy escutaria em algo como `https://myawesomeapp.com`, e então se o navegador acessar `https://myawesomeapp.com/api/v1/app` e seu servidor (por exemplo, Uvicorn) escutar em `http://127.0.0.1:8000` o proxy (sem um prefixo de caminho removido) acessaria o Uvicorn no mesmo caminho: `http://127.0.0.1:8000/api/v1/app`. + +## Testando localmente com Traefik + +Você pode facilmente executar o experimento localmente com um prefixo de caminho removido usando <a href="https://docs.traefik.io/" class="external-link" target="_blank">Traefik</a>. + +<a href="https://github.com/containous/traefik/releases" class="external-link" target="_blank">Faça o download do Traefik.</a>, Ele é um único binário e você pode extrair o arquivo compactado e executá-lo diretamente do terminal. + +Então, crie um arquivo `traefik.toml` com: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`. + +!!! tip "Dica" + Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). + +Agora crie esse outro arquivo `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +Esse arquivo configura o Traefik para usar o prefixo de caminho `/api/v1`. + +E então ele redirecionará suas solicitações para seu Uvicorn rodando em `http://127.0.0.1:8000`. + +Agora inicie o Traefik: + +<div class="termy"> + +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +</div> + +E agora inicie sua aplicação, usando a opção `--root-path`: + +<div class="termy"> + +```console +$ fastapi run main.py --root-path /api/v1 + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +### Verifique as respostas + +Agora, se você for ao URL com a porta para o Uvicorn: <a href="http://127.0.0.1:8000/app" class="external-link" target="_blank">http://127.0.0.1:8000/app</a>, você verá a resposta normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +!!! tip "Dica" + Perceba que, mesmo acessando em `http://127.0.0.1:8000/app`, ele mostra o `root_path` de `/api/v1`, retirado da opção `--root-path`. + +E agora abra o URL com a porta para o Traefik, incluindo o prefixo de caminho: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>. + +Obtemos a mesma resposta: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +mas desta vez no URL com o prefixo de caminho fornecido pelo proxy: `/api/v1`. + +Claro, a ideia aqui é que todos acessariam a aplicação através do proxy, então a versão com o prefixo de caminho `/api/v1` é a "correta". + +E a versão sem o prefixo de caminho (`http://127.0.0.1:8000/app`), fornecida diretamente pelo Uvicorn, seria exclusivamente para o _proxy_ (Traefik) acessá-la. + +Isso demonstra como o Proxy (Traefik) usa o prefixo de caminho e como o servidor (Uvicorn) usa o `root_path` da opção `--root-path`. + +### Verifique a interface de documentação + +Mas aqui está a parte divertida. ✨ + +A maneira "oficial" de acessar a aplicação seria através do proxy com o prefixo de caminho que definimos. Então, como esperaríamos, se você tentar a interface de documentação servida diretamente pelo Uvicorn, sem o prefixo de caminho no URL, ela não funcionará, porque espera ser acessada através do proxy. + +Você pode verificar em <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>: + +<img src="/img/tutorial/behind-a-proxy/image01.png"> + +Mas se acessarmos a interface de documentação no URL "oficial" usando o proxy com a porta `9999`, em `/api/v1/docs`, ela funciona corretamente! 🎉 + +Você pode verificar em <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a>: + +<img src="/img/tutorial/behind-a-proxy/image02.png"> + +Exatamente como queríamos. ✔️ + +Isso porque o FastAPI usa esse `root_path` para criar o `server` padrão no OpenAPI com o URL fornecido pelo `root_path`. + +## Servidores adicionais + +!!! warning "Aviso" + Este é um caso de uso mais avançado. Sinta-se à vontade para pular. + +Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`. + +Mas você também pode fornecer outros `servers` alternativos, por exemplo, se quiser que a *mesma* interface de documentação interaja com ambientes de staging e produção. + +Se você passar uma lista personalizada de `servers` e houver um `root_path` (porque sua API está atrás de um proxy), o **FastAPI** inserirá um "server" com esse `root_path` no início da lista. + +Por exemplo: + +```Python hl_lines="4-7" +{!../../../docs_src/behind_a_proxy/tutorial003.py!} +``` + +Gerará um OpenAPI schema como: + +```JSON hl_lines="5-7" +{ + "openapi": "3.1.0", + // Mais coisas aqui + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // Mais coisas aqui + } +} +``` + +!!! tip "Dica" + Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`. + +Na interface de documentação em <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> parecerá: + +<img src="/img/tutorial/behind-a-proxy/image03.png"> + +!!! tip "Dica" + A interface de documentação interagirá com o servidor que você selecionar. + +### Desabilitar servidor automático de `root_path` + +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!} +``` + +e então ele não será incluído no OpenAPI schema. + +## Montando uma sub-aplicação + +Se você precisar montar uma sub-aplicação (como descrito em [Sub Aplicações - Montagens](sub-applications.md){.internal-link target=_blank}) enquanto também usa um proxy com `root_path`, você pode fazer isso normalmente, como esperaria. + +O FastAPI usará internamente o `root_path` de forma inteligente, então tudo funcionará. ✨ diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md new file mode 100644 index 000000000..8149edc5a --- /dev/null +++ b/docs/pt/docs/advanced/sub-applications.md @@ -0,0 +1,73 @@ +# Sub Aplicações - Montagens + +Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu próprio OpenAPI e suas próprias interfaces de documentação, você pode ter um aplicativo principal e "montar" uma (ou mais) sub-aplicações. + +## Montando uma aplicação **FastAPI** + +"Montar" significa adicionar uma aplicação completamente "independente" em um caminho específico, que então se encarrega de lidar com tudo sob esse caminho, com as operações de rota declaradas nessa sub-aplicação. + +### Aplicação de nível superior + +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!} +``` + +### Sub-aplicação + +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!} +``` + +### Monte a sub-aplicação + +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!} +``` + +### Verifique a documentação automática da API + +Agora, execute `uvicorn` com a aplicação principal, se o seu arquivo for `main.py`, seria: + +<div class="termy"> + +```console +$ uvicorn main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +E abra a documentação em <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Você verá a documentação automática da API para a aplicação principal, incluindo apenas suas próprias _operações de rota_: + +<img src="/img/tutorial/sub-applications/image01.png"> + +E então, abra a documentação para a sub-aplicação, em <a href="http://127.0.0.1:8000/subapi/docs" class="external-link" target="_blank">http://127.0.0.1:8000/subapi/docs</a>. + +Você verá a documentação automática da API para a sub-aplicação, incluindo apenas suas próprias _operações de rota_, todas sob o prefixo de sub-caminho correto `/subapi`: + +<img src="/img/tutorial/sub-applications/image02.png"> + +Se você tentar interagir com qualquer uma das duas interfaces de usuário, elas funcionarão corretamente, porque o navegador será capaz de se comunicar com cada aplicação ou sub-aplicação específica. + +### Detalhes Técnicos: `root_path` + +Quando você monta uma sub-aplicação como descrito acima, o FastAPI se encarrega de comunicar o caminho de montagem para a sub-aplicação usando um mecanismo da especificação ASGI chamado `root_path`. + +Dessa forma, a sub-aplicação saberá usar esse prefixo de caminho para a interface de documentação. + +E a sub-aplicação também poderia ter suas próprias sub-aplicações montadas e tudo funcionaria corretamente, porque o FastAPI lida com todos esses `root_path`s automaticamente. + +Você aprenderá mais sobre o `root_path` e como usá-lo explicitamente na seção sobre [Atrás de um Proxy](behind-a-proxy.md){.internal-link target=_blank}. From 553816ae6a685810b59fcead4c485e34360788be Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 3 Aug 2024 00:03:45 +0000 Subject: [PATCH 662/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7115e425b..f7a3cbe55 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/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). * 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian). From b1774bae1bde1392944f6befecb507a702ce5aab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E5=AE=A6=E6=88=90?= <bestony@linux.com> Date: Mon, 5 Aug 2024 01:01:03 +0800 Subject: [PATCH 663/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20typo=20in=20Chi?= =?UTF-8?q?nese=20translation=20for=20`docs/zh/docs/advanced/testing-depen?= =?UTF-8?q?dencies.md`=20(#11944)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/testing-dependencies.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index dc0f88b33..487f5ebf5 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -22,7 +22,7 @@ ### 使用 `app.dependency_overrides` 属性 -对于这些用例,**FastAPI** 应用支持 `app.dependcy_overrides` 属性,该属性就是**字典**。 +对于这些用例,**FastAPI** 应用支持 `app.dependency_overrides` 属性,该属性就是**字典**。 要在测试时覆盖原有依赖项,这个字典的键应当是原依赖项(函数),值是覆盖依赖项(另一个函数)。 From 22ffde0356e8b71b5c189b8276a9d51c526060c1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 4 Aug 2024 17:01:24 +0000 Subject: [PATCH 664/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f7a3cbe55..1e2292265 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). * 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian). From f3e49e5f4e10f7dd0423ce1f9111dd86ef603f44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 4 Aug 2024 13:23:14 -0500 Subject: [PATCH 665/846] =?UTF-8?q?=F0=9F=94=87=20Ignore=20warning=20from?= =?UTF-8?q?=20attrs=20in=20Trio=20(#11949)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 3601e6322..c34838b83 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -157,7 +157,6 @@ filterwarnings = [ "ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning", # see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28 "ignore:You seem to already have a custom.*:RuntimeWarning:trio", - "ignore::trio.TrioDeprecationWarning", # TODO remove pytest-cov 'ignore::pytest.PytestDeprecationWarning:pytest_cov', # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes @@ -169,6 +168,10 @@ filterwarnings = [ # - https://github.com/mpdavis/python-jose/issues/332 # - https://github.com/mpdavis/python-jose/issues/334 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', + # Trio 24.1.0 raises a warning from attrs + # Ref: https://github.com/python-trio/trio/pull/3054 + # Remove once there's a new version of Trio + 'ignore:The `hash` argument is deprecated*:DeprecationWarning:trio', ] [tool.coverage.run] From 35fcb31dca6dbeac5f03bbaea3ae279da9cc0b8a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 4 Aug 2024 18:23:34 +0000 Subject: [PATCH 666/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1e2292265..eb270825b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). * 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian). +### Internal + +* 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.0 ### Breaking Changes From abe62d8a81145e6cce5a5e959cba7f644117d69d Mon Sep 17 00:00:00 2001 From: CAO Mingpei <caomingpei@outlook.com> Date: Mon, 5 Aug 2024 07:33:57 +0800 Subject: [PATCH 667/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/query-params.md`=20(#1155?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/query-params.md | 45 +++++++++++++++++++++------ 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index 77138de51..8b2528c9a 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -92,9 +92,19 @@ http://127.0.0.1:8000/items/?skip=20 参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型: -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} -``` + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial003.py!} + ``` + 本例中,访问: @@ -137,9 +147,18 @@ http://127.0.0.1:8000/items/foo?short=yes FastAPI 通过参数名进行检测: -```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="6 8" + {!> ../../../docs_src/query_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 10" + {!> ../../../docs_src/query_params/tutorial004.py!} + ``` + ## 必选查询参数 @@ -195,9 +214,17 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的: -```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params/tutorial006.py!} + ``` 本例中有 3 个查询参数: From 9dee1f8b28693cbe59105dc8060e348668485afb Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 4 Aug 2024 23:34:17 +0000 Subject: [PATCH 668/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index eb270825b..f662e59d0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). * 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). From dc384c4f8d6ecfe1b00361a550860a36b87a130f Mon Sep 17 00:00:00 2001 From: "P-E. Brian" <pebrian@outlook.fr> Date: Mon, 5 Aug 2024 17:48:45 +0200 Subject: [PATCH 669/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20French=20translati?= =?UTF-8?q?on=20for=20`docs/fr/docs/tutorial/body-multiple-params.md`=20(#?= =?UTF-8?q?11796)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/body-multiple-params.md | 307 ++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 docs/fr/docs/tutorial/body-multiple-params.md diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..563b601f0 --- /dev/null +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -0,0 +1,307 @@ +# Body - Paramètres multiples + +Maintenant que nous avons vu comment manipuler `Path` et `Query`, voyons comment faire pour le corps d'une requête, communément désigné par le terme anglais "body". + +## Mélanger les paramètres `Path`, `Query` et body + +Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres `Path`, `Query` et body, **FastAPI** saura quoi faire. + +Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : + +=== "Python 3.10+" + + ```Python hl_lines="18-20" + {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18-20" + {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="17-19" + {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001.py!} + ``` + +!!! note + Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). + +## Paramètres multiples du body + +Dans l'exemple précédent, les opérations de routage attendaient un body JSON avec les attributs d'un `Item`, par exemple : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : + +=== "Python 3.10+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial002.py!} + ``` + +Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). + +Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevoir quelque chose de semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note + "Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. + +**FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis. + +Il effectue également la validation des données (même imbriquées les unes dans les autres), et permet de les documenter correctement (schéma OpenAPI et documentation auto-générée). + +## Valeurs scalaires dans le body + +De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres query et path, **FastAPI** fournit un équivalent `Body`. + +Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un paramètre `importance` dans le même body, en plus des paramètres `item` et `user`. + +Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). + +Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial003.py!} + ``` + +Dans ce cas, **FastAPI** s'attendra à un body semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Encore une fois, cela convertira les types de données, les validera, permettra de générer la documentation, etc... + +## Paramètres multiples body et query + +Bien entendu, vous pouvez déclarer autant de paramètres que vous le souhaitez, en plus des paramètres body déjà déclarés. + +Par défaut, les valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) sont interprétées comme des paramètres query, donc inutile d'ajouter explicitement `Query`. Vous pouvez juste écrire : + +```Python +q: Union[str, None] = None +``` + +Ou bien, en Python 3.10 et supérieur : + +```Python +q: str | None = None +``` + +Par exemple : + +=== "Python 3.10+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="28" + {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="25" + {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004.py!} + ``` + +!!! info + `Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. + +## Inclure un paramètre imbriqué dans le body + +Disons que vous avez seulement un paramètre `item` dans le body, correspondant à un modèle Pydantic `Item`. + +Par défaut, **FastAPI** attendra sa déclaration directement dans le body. + +Cependant, si vous souhaitez qu'il interprête correctement un JSON avec une clé `item` associée au contenu du modèle, comme cela serait le cas si vous déclariez des paramètres body additionnels, vous pouvez utiliser le paramètre spécial `embed` de `Body` : + +```Python +item: Item = Body(embed=True) +``` + +Voici un exemple complet : + +=== "Python 3.10+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="15" + {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005.py!} + ``` + +Dans ce cas **FastAPI** attendra un body semblable à : + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +au lieu de : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Pour résumer + +Vous pouvez ajouter plusieurs paramètres body dans votre fonction de routage, même si une requête ne peut avoir qu'un seul body. + +Cependant, **FastAPI** se chargera de faire opérer sa magie, afin de toujours fournir à votre fonction des données correctes, les validera et documentera le schéma associé. + +Vous pouvez également déclarer des valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) à recevoir dans le body. + +Et vous pouvez indiquer à **FastAPI** d'inclure le body dans une autre variable, même lorsqu'un seul paramètre est déclaré. From af1a07052a713da96c5c75c9548203c77d0b6fd6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 5 Aug 2024 15:49:07 +0000 Subject: [PATCH 670/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f662e59d0..78e27ba7e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). * 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus). From 0cd844d3877e6ae9e9fce1c99ea68327254e9b6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 5 Aug 2024 23:48:30 -0500 Subject: [PATCH 671/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20docs=20setup=20?= =?UTF-8?q?with=20latest=20configs=20and=20plugins=20(#11953)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build-docs.yml | 23 +- docs/bn/docs/python-types.md | 303 +++-- docs/de/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 84 +- .../de/docs/advanced/advanced-dependencies.md | 161 ++- docs/de/docs/advanced/async-tests.md | 28 +- docs/de/docs/advanced/behind-a-proxy.md | 51 +- docs/de/docs/advanced/custom-response.md | 87 +- docs/de/docs/advanced/dataclasses.md | 11 +- docs/de/docs/advanced/events.md | 47 +- docs/de/docs/advanced/generate-clients.md | 87 +- docs/de/docs/advanced/index.md | 9 +- docs/de/docs/advanced/middleware.md | 9 +- docs/de/docs/advanced/openapi-callbacks.md | 39 +- docs/de/docs/advanced/openapi-webhooks.md | 14 +- .../path-operation-advanced-configuration.md | 102 +- docs/de/docs/advanced/response-cookies.md | 22 +- docs/de/docs/advanced/response-directly.md | 16 +- docs/de/docs/advanced/response-headers.md | 11 +- .../docs/advanced/security/http-basic-auth.md | 111 +- docs/de/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 724 +++++++---- docs/de/docs/advanced/settings.md | 299 +++-- docs/de/docs/advanced/templates.md | 25 +- docs/de/docs/advanced/testing-dependencies.md | 82 +- docs/de/docs/advanced/testing-websockets.md | 7 +- .../docs/advanced/using-request-directly.md | 20 +- docs/de/docs/advanced/websockets.md | 120 +- docs/de/docs/alternatives.md | 227 ++-- docs/de/docs/async.md | 32 +- docs/de/docs/contributing.md | 177 +-- docs/de/docs/deployment/concepts.md | 34 +- docs/de/docs/deployment/docker.md | 74 +- docs/de/docs/deployment/https.md | 21 +- docs/de/docs/deployment/manually.md | 90 +- docs/de/docs/deployment/server-workers.md | 9 +- docs/de/docs/deployment/versions.md | 14 +- docs/de/docs/external-links.md | 14 +- docs/de/docs/features.md | 9 +- docs/de/docs/help-fastapi.md | 20 +- docs/de/docs/how-to/custom-docs-ui-assets.md | 22 +- .../docs/how-to/custom-request-and-route.md | 40 +- docs/de/docs/how-to/extending-openapi.md | 7 +- docs/de/docs/how-to/graphql.md | 18 +- docs/de/docs/how-to/index.md | 7 +- .../docs/how-to/separate-openapi-schemas.md | 211 ++-- docs/de/docs/python-types.md | 303 +++-- docs/de/docs/reference/index.md | 7 +- docs/de/docs/reference/request.md | 7 +- docs/de/docs/reference/websockets.md | 7 +- docs/de/docs/tutorial/background-tasks.md | 64 +- docs/de/docs/tutorial/bigger-applications.md | 181 ++- docs/de/docs/tutorial/body-fields.md | 162 ++- docs/de/docs/tutorial/body-multiple-params.md | 297 +++-- docs/de/docs/tutorial/body-nested-models.md | 297 +++-- docs/de/docs/tutorial/body-updates.md | 171 ++- docs/de/docs/tutorial/body.md | 159 ++- docs/de/docs/tutorial/cookie-params.md | 144 ++- .../dependencies/classes-as-dependencies.md | 619 ++++++---- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/dependencies-with-yield.md | 222 ++-- .../dependencies/global-dependencies.md | 37 +- docs/de/docs/tutorial/dependencies/index.md | 265 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/de/docs/tutorial/encoder.md | 27 +- docs/de/docs/tutorial/extra-data-types.md | 128 +- docs/de/docs/tutorial/extra-models.md | 132 +- docs/de/docs/tutorial/first-steps.md | 64 +- docs/de/docs/tutorial/handling-errors.md | 36 +- docs/de/docs/tutorial/header-params.md | 296 +++-- docs/de/docs/tutorial/index.md | 25 +- docs/de/docs/tutorial/metadata.md | 21 +- docs/de/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 356 ++++-- docs/de/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 1067 ++++++++++------ docs/de/docs/tutorial/query-params.md | 94 +- docs/de/docs/tutorial/request-files.md | 390 +++--- .../docs/tutorial/request-forms-and-files.md | 92 +- docs/de/docs/tutorial/request-forms.md | 117 +- docs/de/docs/tutorial/response-model.md | 412 ++++--- docs/de/docs/tutorial/response-status-code.md | 46 +- docs/de/docs/tutorial/schema-extra-example.md | 324 +++-- docs/de/docs/tutorial/security/first-steps.md | 180 ++- .../tutorial/security/get-current-user.md | 375 +++--- docs/de/docs/tutorial/security/index.md | 15 +- docs/de/docs/tutorial/security/oauth2-jwt.md | 308 +++-- .../docs/tutorial/security/simple-oauth2.md | 412 ++++--- docs/de/docs/tutorial/static-files.md | 9 +- docs/de/docs/tutorial/testing.md | 109 +- docs/em/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 20 +- .../em/docs/advanced/advanced-dependencies.md | 13 +- docs/em/docs/advanced/async-tests.md | 21 +- docs/em/docs/advanced/behind-a-proxy.md | 51 +- docs/em/docs/advanced/custom-response.md | 87 +- docs/em/docs/advanced/dataclasses.md | 11 +- docs/em/docs/advanced/events.md | 45 +- docs/em/docs/advanced/generate-clients.md | 67 +- docs/em/docs/advanced/index.md | 9 +- docs/em/docs/advanced/middleware.md | 9 +- docs/em/docs/advanced/openapi-callbacks.md | 39 +- .../path-operation-advanced-configuration.md | 48 +- docs/em/docs/advanced/response-cookies.md | 22 +- docs/em/docs/advanced/response-directly.md | 16 +- docs/em/docs/advanced/response-headers.md | 11 +- docs/em/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 77 +- docs/em/docs/advanced/settings.md | 120 +- docs/em/docs/advanced/templates.md | 23 +- docs/em/docs/advanced/testing-database.md | 16 +- docs/em/docs/advanced/testing-dependencies.md | 18 +- docs/em/docs/advanced/testing-websockets.md | 7 +- .../docs/advanced/using-request-directly.md | 20 +- docs/em/docs/advanced/websockets.md | 36 +- docs/em/docs/alternatives.md | 227 ++-- docs/em/docs/async.md | 32 +- docs/em/docs/contributing.md | 124 +- docs/em/docs/deployment/concepts.md | 34 +- docs/em/docs/deployment/docker.md | 74 +- docs/em/docs/deployment/https.md | 21 +- docs/em/docs/deployment/manually.md | 90 +- docs/em/docs/deployment/server-workers.md | 9 +- docs/em/docs/deployment/versions.md | 14 +- docs/em/docs/external-links.md | 7 +- docs/em/docs/features.md | 9 +- docs/em/docs/help-fastapi.md | 20 +- .../docs/how-to/custom-request-and-route.md | 40 +- docs/em/docs/how-to/extending-openapi.md | 11 +- docs/em/docs/how-to/graphql.md | 18 +- docs/em/docs/how-to/sql-databases-peewee.md | 141 ++- docs/em/docs/python-types.md | 268 ++-- docs/em/docs/tutorial/background-tasks.md | 20 +- docs/em/docs/tutorial/bigger-applications.md | 144 ++- docs/em/docs/tutorial/body-fields.md | 76 +- docs/em/docs/tutorial/body-multiple-params.md | 120 +- docs/em/docs/tutorial/body-nested-models.md | 297 +++-- docs/em/docs/tutorial/body-updates.md | 153 ++- docs/em/docs/tutorial/body.md | 159 ++- docs/em/docs/tutorial/cookie-params.md | 56 +- docs/em/docs/tutorial/cors.md | 9 +- docs/em/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 149 ++- ...pendencies-in-path-operation-decorators.md | 20 +- .../dependencies/dependencies-with-yield.md | 93 +- docs/em/docs/tutorial/dependencies/index.md | 83 +- .../tutorial/dependencies/sub-dependencies.md | 80 +- docs/em/docs/tutorial/encoder.md | 27 +- docs/em/docs/tutorial/extra-data-types.md | 40 +- docs/em/docs/tutorial/extra-models.md | 123 +- docs/em/docs/tutorial/first-steps.md | 64 +- docs/em/docs/tutorial/handling-errors.md | 36 +- docs/em/docs/tutorial/header-params.md | 113 +- docs/em/docs/tutorial/index.md | 25 +- docs/em/docs/tutorial/metadata.md | 21 +- docs/em/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 75 +- docs/em/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 359 +++--- docs/em/docs/tutorial/query-params.md | 94 +- docs/em/docs/tutorial/request-files.md | 130 +- .../docs/tutorial/request-forms-and-files.md | 18 +- docs/em/docs/tutorial/request-forms.md | 43 +- docs/em/docs/tutorial/response-model.md | 403 +++--- docs/em/docs/tutorial/response-status-code.md | 46 +- docs/em/docs/tutorial/schema-extra-example.md | 105 +- docs/em/docs/tutorial/security/first-steps.md | 69 +- .../tutorial/security/get-current-user.md | 118 +- docs/em/docs/tutorial/security/index.md | 15 +- docs/em/docs/tutorial/security/oauth2-jwt.md | 132 +- .../docs/tutorial/security/simple-oauth2.md | 192 +-- docs/em/docs/tutorial/sql-databases.md | 456 ++++--- docs/em/docs/tutorial/static-files.md | 9 +- docs/em/docs/tutorial/testing.md | 65 +- docs/en/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 84 +- .../en/docs/advanced/advanced-dependencies.md | 161 ++- docs/en/docs/advanced/async-tests.md | 28 +- docs/en/docs/advanced/behind-a-proxy.md | 51 +- docs/en/docs/advanced/custom-response.md | 101 +- docs/en/docs/advanced/dataclasses.md | 11 +- docs/en/docs/advanced/events.md | 47 +- docs/en/docs/advanced/generate-clients.md | 87 +- docs/en/docs/advanced/index.md | 9 +- docs/en/docs/advanced/middleware.md | 9 +- docs/en/docs/advanced/openapi-callbacks.md | 39 +- docs/en/docs/advanced/openapi-webhooks.md | 14 +- .../path-operation-advanced-configuration.md | 102 +- docs/en/docs/advanced/response-cookies.md | 22 +- docs/en/docs/advanced/response-directly.md | 16 +- docs/en/docs/advanced/response-headers.md | 11 +- .../docs/advanced/security/http-basic-auth.md | 111 +- docs/en/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 724 +++++++---- docs/en/docs/advanced/settings.md | 299 +++-- docs/en/docs/advanced/templates.md | 25 +- docs/en/docs/advanced/testing-database.md | 27 +- docs/en/docs/advanced/testing-dependencies.md | 82 +- docs/en/docs/advanced/testing-websockets.md | 7 +- .../docs/advanced/using-request-directly.md | 20 +- docs/en/docs/advanced/websockets.md | 120 +- docs/en/docs/alternatives.md | 227 ++-- docs/en/docs/async.md | 32 +- docs/en/docs/contributing.md | 177 +-- docs/en/docs/deployment/concepts.md | 34 +- docs/en/docs/deployment/docker.md | 72 +- docs/en/docs/deployment/https.md | 21 +- docs/en/docs/deployment/manually.md | 111 +- docs/en/docs/deployment/server-workers.md | 9 +- docs/en/docs/deployment/versions.md | 14 +- docs/en/docs/external-links.md | 7 +- docs/en/docs/fastapi-cli.md | 7 +- docs/en/docs/fastapi-people.md | 9 +- docs/en/docs/features.md | 9 +- docs/en/docs/help-fastapi.md | 20 +- .../docs/how-to/async-sql-encode-databases.md | 66 +- docs/en/docs/how-to/custom-docs-ui-assets.md | 22 +- .../docs/how-to/custom-request-and-route.md | 40 +- docs/en/docs/how-to/extending-openapi.md | 7 +- docs/en/docs/how-to/graphql.md | 18 +- docs/en/docs/how-to/index.md | 6 +- .../docs/how-to/nosql-databases-couchbase.md | 34 +- .../docs/how-to/separate-openapi-schemas.md | 211 ++-- docs/en/docs/how-to/sql-databases-peewee.md | 161 ++- docs/en/docs/js/custom.js | 7 +- docs/en/docs/management-tasks.md | 67 +- docs/en/docs/newsletter.md | 2 +- docs/en/docs/python-types.md | 303 +++-- docs/en/docs/reference/request.md | 7 +- docs/en/docs/reference/websockets.md | 7 +- docs/en/docs/tutorial/background-tasks.md | 64 +- docs/en/docs/tutorial/bigger-applications.md | 181 ++- docs/en/docs/tutorial/body-fields.md | 164 ++- docs/en/docs/tutorial/body-multiple-params.md | 296 +++-- docs/en/docs/tutorial/body-nested-models.md | 297 +++-- docs/en/docs/tutorial/body-updates.md | 171 ++- docs/en/docs/tutorial/body.md | 159 ++- docs/en/docs/tutorial/cookie-params.md | 144 ++- docs/en/docs/tutorial/cors.md | 9 +- docs/en/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 619 ++++++---- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/dependencies-with-yield.md | 295 +++-- .../dependencies/global-dependencies.md | 37 +- docs/en/docs/tutorial/dependencies/index.md | 265 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/en/docs/tutorial/encoder.md | 27 +- docs/en/docs/tutorial/extra-data-types.md | 128 +- docs/en/docs/tutorial/extra-models.md | 132 +- docs/en/docs/tutorial/first-steps.md | 51 +- docs/en/docs/tutorial/handling-errors.md | 36 +- docs/en/docs/tutorial/header-params.md | 296 +++-- docs/en/docs/tutorial/index.md | 9 +- docs/en/docs/tutorial/metadata.md | 21 +- docs/en/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 352 ++++-- docs/en/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 1073 ++++++++++------ docs/en/docs/tutorial/query-params.md | 94 +- docs/en/docs/tutorial/request-files.md | 390 +++--- .../docs/tutorial/request-forms-and-files.md | 92 +- docs/en/docs/tutorial/request-forms.md | 117 +- docs/en/docs/tutorial/response-model.md | 412 ++++--- docs/en/docs/tutorial/response-status-code.md | 46 +- docs/en/docs/tutorial/schema-extra-example.md | 324 +++-- docs/en/docs/tutorial/security/first-steps.md | 181 ++- .../tutorial/security/get-current-user.md | 375 +++--- docs/en/docs/tutorial/security/index.md | 15 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 308 +++-- .../docs/tutorial/security/simple-oauth2.md | 412 ++++--- docs/en/docs/tutorial/sql-databases.md | 476 +++++--- docs/en/docs/tutorial/static-files.md | 9 +- docs/en/docs/tutorial/testing.md | 109 +- docs/en/mkdocs.insiders.yml | 5 + docs/en/mkdocs.yml | 109 +- .../docs/advanced/additional-status-codes.md | 20 +- docs/es/docs/advanced/index.md | 9 +- .../path-operation-advanced-configuration.md | 23 +- docs/es/docs/advanced/response-directly.md | 16 +- docs/es/docs/advanced/response-headers.md | 11 +- docs/es/docs/advanced/security/index.md | 9 +- docs/es/docs/async.md | 32 +- docs/es/docs/deployment/versions.md | 14 +- docs/es/docs/external-links.md | 7 +- docs/es/docs/features.md | 9 +- docs/es/docs/how-to/graphql.md | 18 +- docs/es/docs/python-types.md | 21 +- docs/es/docs/tutorial/cookie-params.md | 144 ++- docs/es/docs/tutorial/first-steps.md | 64 +- docs/es/docs/tutorial/index.md | 25 +- docs/es/docs/tutorial/path-params.md | 66 +- docs/es/docs/tutorial/query-params.md | 23 +- docs/fa/docs/features.md | 9 +- docs/fa/docs/tutorial/middleware.md | 24 +- docs/fa/docs/tutorial/security/index.md | 16 +- docs/fr/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 20 +- docs/fr/docs/advanced/index.md | 9 +- .../path-operation-advanced-configuration.md | 46 +- docs/fr/docs/advanced/response-directly.md | 16 +- docs/fr/docs/alternatives.md | 182 ++- docs/fr/docs/async.md | 32 +- docs/fr/docs/contributing.md | 158 ++- docs/fr/docs/deployment/docker.md | 7 +- docs/fr/docs/deployment/https.md | 7 +- docs/fr/docs/deployment/manually.md | 90 +- docs/fr/docs/deployment/versions.md | 14 +- docs/fr/docs/external-links.md | 7 +- docs/fr/docs/features.md | 9 +- docs/fr/docs/python-types.md | 30 +- docs/fr/docs/tutorial/body-multiple-params.md | 297 +++-- docs/fr/docs/tutorial/body.md | 39 +- docs/fr/docs/tutorial/debugging.md | 5 +- docs/fr/docs/tutorial/first-steps.md | 63 +- docs/fr/docs/tutorial/index.md | 25 +- .../path-params-numeric-validations.md | 389 +++--- docs/fr/docs/tutorial/path-params.md | 72 +- .../tutorial/query-params-str-validations.md | 73 +- docs/fr/docs/tutorial/query-params.md | 22 +- docs/hu/docs/index.md | 2 +- docs/id/docs/tutorial/index.md | 25 +- docs/it/docs/index.md | 1 - .../docs/advanced/additional-status-codes.md | 20 +- docs/ja/docs/advanced/custom-response.md | 87 +- docs/ja/docs/advanced/index.md | 9 +- .../path-operation-advanced-configuration.md | 23 +- docs/ja/docs/advanced/response-directly.md | 16 +- docs/ja/docs/advanced/websockets.md | 38 +- docs/ja/docs/alternatives.md | 229 ++-- docs/ja/docs/async.md | 18 +- docs/ja/docs/contributing.md | 124 +- docs/ja/docs/deployment/concepts.md | 38 +- docs/ja/docs/deployment/docker.md | 76 +- docs/ja/docs/deployment/https.md | 21 +- docs/ja/docs/deployment/manually.md | 79 +- docs/ja/docs/deployment/server-workers.md | 11 +- docs/ja/docs/deployment/versions.md | 14 +- docs/ja/docs/external-links.md | 7 +- docs/ja/docs/features.md | 9 +- docs/ja/docs/python-types.md | 30 +- docs/ja/docs/tutorial/body-fields.md | 27 +- docs/ja/docs/tutorial/body-multiple-params.md | 20 +- docs/ja/docs/tutorial/body-nested-models.md | 27 +- docs/ja/docs/tutorial/body-updates.md | 33 +- docs/ja/docs/tutorial/body.md | 39 +- docs/ja/docs/tutorial/cookie-params.md | 16 +- docs/ja/docs/tutorial/cors.md | 9 +- docs/ja/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 9 +- ...pendencies-in-path-operation-decorators.md | 11 +- .../dependencies/dependencies-with-yield.md | 108 +- docs/ja/docs/tutorial/dependencies/index.md | 23 +- .../tutorial/dependencies/sub-dependencies.md | 20 +- docs/ja/docs/tutorial/encoder.md | 7 +- docs/ja/docs/tutorial/extra-models.md | 16 +- docs/ja/docs/tutorial/first-steps.md | 64 +- docs/ja/docs/tutorial/handling-errors.md | 36 +- docs/ja/docs/tutorial/header-params.md | 22 +- docs/ja/docs/tutorial/index.md | 25 +- docs/ja/docs/tutorial/metadata.md | 14 +- docs/ja/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 32 +- .../path-params-numeric-validations.md | 35 +- docs/ja/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 74 +- docs/ja/docs/tutorial/query-params.md | 14 +- .../docs/tutorial/request-forms-and-files.md | 18 +- docs/ja/docs/tutorial/request-forms.md | 43 +- docs/ja/docs/tutorial/response-model.md | 70 +- docs/ja/docs/tutorial/response-status-code.md | 46 +- docs/ja/docs/tutorial/schema-extra-example.md | 7 +- docs/ja/docs/tutorial/security/first-steps.md | 69 +- .../tutorial/security/get-current-user.md | 16 +- docs/ja/docs/tutorial/security/index.md | 15 +- docs/ja/docs/tutorial/security/oauth2-jwt.md | 51 +- docs/ja/docs/tutorial/static-files.md | 9 +- docs/ja/docs/tutorial/testing.md | 56 +- docs/ko/docs/advanced/events.md | 32 +- docs/ko/docs/advanced/index.md | 9 +- docs/ko/docs/async.md | 18 +- docs/ko/docs/deployment/docker.md | 74 +- docs/ko/docs/deployment/server-workers.md | 9 +- docs/ko/docs/deployment/versions.md | 14 +- docs/ko/docs/features.md | 9 +- docs/ko/docs/python-types.md | 29 +- docs/ko/docs/tutorial/background-tasks.md | 20 +- docs/ko/docs/tutorial/body-fields.md | 164 ++- docs/ko/docs/tutorial/body-multiple-params.md | 21 +- docs/ko/docs/tutorial/body-nested-models.md | 27 +- docs/ko/docs/tutorial/body.md | 159 ++- docs/ko/docs/tutorial/cookie-params.md | 144 ++- docs/ko/docs/tutorial/cors.md | 9 +- docs/ko/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 149 ++- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/global-dependencies.md | 37 +- docs/ko/docs/tutorial/dependencies/index.md | 265 ++-- docs/ko/docs/tutorial/encoder.md | 7 +- docs/ko/docs/tutorial/extra-data-types.md | 128 +- docs/ko/docs/tutorial/first-steps.md | 64 +- docs/ko/docs/tutorial/header-params.md | 23 +- docs/ko/docs/tutorial/index.md | 25 +- docs/ko/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 32 +- .../path-params-numeric-validations.md | 35 +- docs/ko/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 73 +- docs/ko/docs/tutorial/query-params.md | 23 +- docs/ko/docs/tutorial/request-files.md | 81 +- .../docs/tutorial/request-forms-and-files.md | 18 +- docs/ko/docs/tutorial/response-model.md | 70 +- docs/ko/docs/tutorial/response-status-code.md | 46 +- docs/ko/docs/tutorial/schema-extra-example.md | 324 +++-- .../tutorial/security/get-current-user.md | 118 +- .../docs/tutorial/security/simple-oauth2.md | 192 +-- docs/ko/docs/tutorial/static-files.md | 9 +- docs/missing-translation.md | 9 +- docs/pl/docs/features.md | 9 +- docs/pl/docs/help-fastapi.md | 20 +- docs/pl/docs/tutorial/first-steps.md | 63 +- docs/pl/docs/tutorial/index.md | 25 +- docs/pt/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 84 +- .../pt/docs/advanced/advanced-dependencies.md | 161 ++- docs/pt/docs/advanced/async-tests.md | 28 +- docs/pt/docs/advanced/behind-a-proxy.md | 51 +- docs/pt/docs/advanced/events.md | 47 +- docs/pt/docs/advanced/index.md | 9 +- docs/pt/docs/advanced/openapi-webhooks.md | 14 +- docs/pt/docs/advanced/settings.md | 299 +++-- docs/pt/docs/advanced/templates.md | 23 +- docs/pt/docs/alternatives.md | 231 ++-- docs/pt/docs/async.md | 18 +- docs/pt/docs/contributing.md | 124 +- docs/pt/docs/deployment.md | 98 +- docs/pt/docs/deployment/docker.md | 73 +- docs/pt/docs/deployment/https.md | 7 +- docs/pt/docs/deployment/versions.md | 14 +- docs/pt/docs/external-links.md | 7 +- docs/pt/docs/fastapi-cli.md | 7 +- docs/pt/docs/features.md | 9 +- docs/pt/docs/help-fastapi.md | 9 +- docs/pt/docs/how-to/index.md | 6 +- docs/pt/docs/python-types.md | 29 +- docs/pt/docs/tutorial/body-fields.md | 27 +- docs/pt/docs/tutorial/body-multiple-params.md | 120 +- docs/pt/docs/tutorial/body-nested-models.md | 27 +- docs/pt/docs/tutorial/body.md | 39 +- docs/pt/docs/tutorial/cookie-params.md | 16 +- docs/pt/docs/tutorial/cors.md | 9 +- .../dependencies/classes-as-dependencies.md | 603 +++++---- ...pendencies-in-path-operation-decorators.md | 171 ++- .../dependencies/dependencies-with-yield.md | 296 +++-- .../dependencies/global-dependencies.md | 37 +- docs/pt/docs/tutorial/dependencies/index.md | 265 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/pt/docs/tutorial/encoder.md | 27 +- docs/pt/docs/tutorial/extra-models.md | 123 +- docs/pt/docs/tutorial/first-steps.md | 64 +- docs/pt/docs/tutorial/handling-errors.md | 34 +- docs/pt/docs/tutorial/header-params.md | 113 +- docs/pt/docs/tutorial/index.md | 25 +- docs/pt/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 75 +- docs/pt/docs/tutorial/path-params.md | 56 +- .../tutorial/query-params-str-validations.md | 73 +- docs/pt/docs/tutorial/query-params.md | 93 +- .../docs/tutorial/request-forms-and-files.md | 17 +- docs/pt/docs/tutorial/request-forms.md | 43 +- docs/pt/docs/tutorial/response-status-code.md | 45 +- docs/pt/docs/tutorial/schema-extra-example.md | 25 +- docs/pt/docs/tutorial/security/first-steps.md | 49 +- docs/pt/docs/tutorial/security/index.md | 15 +- docs/pt/docs/tutorial/static-files.md | 9 +- docs/ru/docs/alternatives.md | 241 ++-- docs/ru/docs/async.md | 22 +- docs/ru/docs/contributing.md | 123 +- docs/ru/docs/deployment/concepts.md | 34 +- docs/ru/docs/deployment/docker.md | 74 +- docs/ru/docs/deployment/https.md | 21 +- docs/ru/docs/deployment/manually.md | 89 +- docs/ru/docs/deployment/versions.md | 14 +- docs/ru/docs/external-links.md | 7 +- docs/ru/docs/features.md | 9 +- docs/ru/docs/help-fastapi.md | 20 +- docs/ru/docs/python-types.md | 30 +- docs/ru/docs/tutorial/background-tasks.md | 20 +- docs/ru/docs/tutorial/body-fields.md | 76 +- docs/ru/docs/tutorial/body-multiple-params.md | 296 +++-- docs/ru/docs/tutorial/body-nested-models.md | 297 +++-- docs/ru/docs/tutorial/body-updates.md | 153 ++- docs/ru/docs/tutorial/body.md | 39 +- docs/ru/docs/tutorial/cookie-params.md | 56 +- docs/ru/docs/tutorial/cors.md | 9 +- docs/ru/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 619 ++++++---- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/dependencies-with-yield.md | 182 ++- .../dependencies/global-dependencies.md | 37 +- docs/ru/docs/tutorial/dependencies/index.md | 262 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/ru/docs/tutorial/encoder.md | 27 +- docs/ru/docs/tutorial/extra-data-types.md | 40 +- docs/ru/docs/tutorial/extra-models.md | 123 +- docs/ru/docs/tutorial/first-steps.md | 64 +- docs/ru/docs/tutorial/handling-errors.md | 36 +- docs/ru/docs/tutorial/header-params.md | 296 +++-- docs/ru/docs/tutorial/index.md | 25 +- docs/ru/docs/tutorial/metadata.md | 21 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 354 ++++-- docs/ru/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 1083 ++++++++++------- docs/ru/docs/tutorial/query-params.md | 94 +- docs/ru/docs/tutorial/request-files.md | 390 +++--- .../docs/tutorial/request-forms-and-files.md | 92 +- docs/ru/docs/tutorial/request-forms.md | 117 +- docs/ru/docs/tutorial/response-model.md | 403 +++--- docs/ru/docs/tutorial/response-status-code.md | 46 +- docs/ru/docs/tutorial/schema-extra-example.md | 193 +-- docs/ru/docs/tutorial/security/first-steps.md | 177 ++- docs/ru/docs/tutorial/security/index.md | 15 +- docs/ru/docs/tutorial/static-files.md | 9 +- docs/ru/docs/tutorial/testing.md | 109 +- docs/tr/docs/advanced/index.md | 9 +- docs/tr/docs/advanced/security/index.md | 9 +- docs/tr/docs/advanced/testing-websockets.md | 7 +- docs/tr/docs/alternatives.md | 230 ++-- docs/tr/docs/async.md | 18 +- docs/tr/docs/external-links.md | 7 +- docs/tr/docs/features.md | 9 +- docs/tr/docs/how-to/index.md | 6 +- docs/tr/docs/python-types.md | 30 +- docs/tr/docs/tutorial/cookie-params.md | 144 ++- docs/tr/docs/tutorial/first-steps.md | 64 +- docs/tr/docs/tutorial/path-params.md | 66 +- docs/tr/docs/tutorial/query-params.md | 94 +- docs/tr/docs/tutorial/request-forms.md | 117 +- docs/tr/docs/tutorial/static-files.md | 9 +- docs/uk/docs/alternatives.md | 225 ++-- docs/uk/docs/python-types.md | 261 ++-- docs/uk/docs/tutorial/body-fields.md | 164 ++- docs/uk/docs/tutorial/body.md | 159 ++- docs/uk/docs/tutorial/cookie-params.md | 144 ++- docs/uk/docs/tutorial/encoder.md | 27 +- docs/uk/docs/tutorial/extra-data-types.md | 128 +- docs/uk/docs/tutorial/first-steps.md | 50 +- docs/uk/docs/tutorial/index.md | 25 +- docs/vi/docs/features.md | 9 +- docs/vi/docs/python-types.md | 302 +++-- docs/vi/docs/tutorial/first-steps.md | 64 +- docs/vi/docs/tutorial/index.md | 25 +- docs/zh-hant/docs/benchmarks.md | 68 +- docs/zh-hant/docs/fastapi-people.md | 9 +- docs/zh/docs/advanced/additional-responses.md | 40 +- .../docs/advanced/additional-status-codes.md | 20 +- .../zh/docs/advanced/advanced-dependencies.md | 12 +- docs/zh/docs/advanced/behind-a-proxy.md | 44 +- docs/zh/docs/advanced/custom-response.md | 78 +- docs/zh/docs/advanced/dataclasses.md | 10 +- docs/zh/docs/advanced/events.md | 30 +- docs/zh/docs/advanced/generate-clients.md | 67 +- docs/zh/docs/advanced/index.md | 9 +- docs/zh/docs/advanced/middleware.md | 8 +- docs/zh/docs/advanced/openapi-callbacks.md | 34 +- .../path-operation-advanced-configuration.md | 23 +- docs/zh/docs/advanced/response-cookies.md | 22 +- docs/zh/docs/advanced/response-directly.md | 16 +- docs/zh/docs/advanced/response-headers.md | 11 +- .../docs/advanced/security/http-basic-auth.md | 112 +- docs/zh/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 70 +- docs/zh/docs/advanced/settings.md | 232 ++-- docs/zh/docs/advanced/templates.md | 22 +- docs/zh/docs/advanced/testing-database.md | 14 +- docs/zh/docs/advanced/testing-dependencies.md | 16 +- docs/zh/docs/advanced/testing-websockets.md | 6 +- .../docs/advanced/using-request-directly.md | 18 +- docs/zh/docs/advanced/websockets.md | 120 +- docs/zh/docs/async.md | 32 +- docs/zh/docs/contributing.md | 177 +-- docs/zh/docs/deployment/concepts.md | 29 +- docs/zh/docs/deployment/docker.md | 73 +- docs/zh/docs/deployment/https.md | 14 +- docs/zh/docs/deployment/manually.md | 88 +- docs/zh/docs/deployment/server-workers.md | 7 +- docs/zh/docs/deployment/versions.md | 14 +- docs/zh/docs/fastapi-cli.md | 7 +- docs/zh/docs/fastapi-people.md | 9 +- docs/zh/docs/features.md | 9 +- docs/zh/docs/help-fastapi.md | 8 +- docs/zh/docs/how-to/index.md | 6 +- docs/zh/docs/python-types.md | 21 +- docs/zh/docs/tutorial/background-tasks.md | 64 +- docs/zh/docs/tutorial/bigger-applications.md | 144 ++- docs/zh/docs/tutorial/body-fields.md | 152 ++- docs/zh/docs/tutorial/body-multiple-params.md | 295 +++-- docs/zh/docs/tutorial/body-nested-models.md | 297 +++-- docs/zh/docs/tutorial/body-updates.md | 30 +- docs/zh/docs/tutorial/body.md | 156 ++- docs/zh/docs/tutorial/cookie-params.md | 142 ++- docs/zh/docs/tutorial/cors.md | 9 +- docs/zh/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 149 ++- ...pendencies-in-path-operation-decorators.md | 18 +- .../dependencies/dependencies-with-yield.md | 157 ++- docs/zh/docs/tutorial/dependencies/index.md | 20 +- .../tutorial/dependencies/sub-dependencies.md | 18 +- docs/zh/docs/tutorial/encoder.md | 27 +- docs/zh/docs/tutorial/extra-data-types.md | 128 +- docs/zh/docs/tutorial/extra-models.md | 120 +- docs/zh/docs/tutorial/first-steps.md | 63 +- docs/zh/docs/tutorial/handling-errors.md | 28 +- docs/zh/docs/tutorial/header-params.md | 292 +++-- docs/zh/docs/tutorial/index.md | 25 +- docs/zh/docs/tutorial/metadata.md | 211 ++-- docs/zh/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 28 +- .../path-params-numeric-validations.md | 180 ++- docs/zh/docs/tutorial/path-params.md | 58 +- .../tutorial/query-params-str-validations.md | 74 +- docs/zh/docs/tutorial/query-params.md | 98 +- docs/zh/docs/tutorial/request-files.md | 122 +- .../docs/tutorial/request-forms-and-files.md | 16 +- docs/zh/docs/tutorial/request-forms.md | 38 +- docs/zh/docs/tutorial/response-model.md | 160 ++- docs/zh/docs/tutorial/response-status-code.md | 40 +- docs/zh/docs/tutorial/schema-extra-example.md | 111 +- docs/zh/docs/tutorial/security/first-steps.md | 99 +- .../tutorial/security/get-current-user.md | 15 +- docs/zh/docs/tutorial/security/index.md | 15 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 238 ++-- .../docs/tutorial/security/simple-oauth2.md | 84 +- docs/zh/docs/tutorial/sql-databases.md | 465 ++++--- docs/zh/docs/tutorial/static-files.md | 9 +- docs/zh/docs/tutorial/testing.md | 109 +- requirements-docs-insiders.txt | 3 + requirements-docs.txt | 8 +- scripts/docs.py | 19 +- 643 files changed, 37192 insertions(+), 21693 deletions(-) create mode 100644 requirements-docs-insiders.txt diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 262c7fa5c..e46629e9b 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -18,7 +18,7 @@ jobs: docs: ${{ steps.filter.outputs.docs }} steps: - uses: actions/checkout@v4 - # For pull requests it's not necessary to checkout the code but for master it is + # For pull requests it's not necessary to checkout the code but for the main branch it is - uses: dorny/paths-filter@v3 id: filter with: @@ -28,9 +28,12 @@ jobs: - docs/** - docs_src/** - requirements-docs.txt + - requirements-docs-insiders.txt - pyproject.toml - mkdocs.yml - mkdocs.insiders.yml + - mkdocs.maybe-insiders.yml + - mkdocs.no-insiders.yml - .github/workflows/build-docs.yml - .github/workflows/deploy-docs.yml langs: @@ -49,17 +52,16 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v07 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt # Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps - name: Install Material for MkDocs Insiders if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + run: pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Verify Docs run: python ./scripts/docs.py verify-docs - name: Export Language Codes @@ -90,16 +92,15 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v08 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt - name: Install Material for MkDocs Insiders if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + run: pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Update Languages run: python ./scripts/docs.py update-languages - uses: actions/cache@v4 diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md index 6923363dd..d5304a65e 100644 --- a/docs/bn/docs/python-types.md +++ b/docs/bn/docs/python-types.md @@ -12,8 +12,11 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে। -!!! Note - যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান। +/// note + +যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান। + +/// ## প্রেরণা @@ -170,45 +173,55 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক। -=== "Python 3.9+" +//// tab | Python 3.9+ - ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। - টাইপ হিসেবে, `list` ব্যবহার করুন। +টাইপ হিসেবে, `list` ব্যবহার করুন। - যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: +//// tab | Python 3.8+ - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +`typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: - ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। +``` Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন। +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + +টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন। + +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: +//// - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +/// info -!!! Info - স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে। +স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে। - এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার। +এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার। + +/// এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।" -!!! Tip - যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন। +/// tip + +যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন। + +/// এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে: @@ -224,17 +237,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// এর মানে হল: @@ -249,18 +266,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` +//// এর মানে হল: @@ -276,17 +296,21 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> দ্বারা পৃথক করতে পারেন। -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`। @@ -306,23 +330,29 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ বিকল্প" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +//// + +//// tab | Python 3.8+ বিকল্প + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### `Union` বা `Optional` ব্যবহার @@ -367,46 +397,53 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন: -=== "Python 3.10+" - আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): +//// tab | Python 3.10+ + +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + +* `list` +* `tuple` +* `set` +* `dict` + +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: - * `list` - * `tuple` - * `set` - * `dict` +* `Union` +* `Optional` (Python 3.8 এর মতোই) +* ...এবং অন্যান্য। - এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: +Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ। - * `Union` - * `Optional` (Python 3.8 এর মতোই) - * ...এবং অন্যান্য। +//// - Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ। +//// tab | Python 3.9+ -=== "Python 3.9+" +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): - আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: - এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: +* `Union` +* `Optional` +* ...এবং অন্যান্য। - * `Union` - * `Optional` - * ...এবং অন্যান্য। +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...এবং অন্যান্য। +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...এবং অন্যান্য। + +//// ### ক্লাস হিসেবে টাইপস @@ -446,55 +483,71 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +[Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)। -!!! Info - [Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)। +/// **FastAPI** মূলত Pydantic-এর উপর নির্মিত। আপনি এই সমস্ত কিছুর অনেক বাস্তবসম্মত উদাহরণ পাবেন [টিউটোরিয়াল - ইউজার গাইডে](https://fastapi.tiangolo.com/tutorial/)। -!!! Tip - যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন। +/// tip + +যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন। + +/// ## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়। -=== "Python 3.9+" +//// tab | Python 3.9+ + +Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন। - Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন। +এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। - এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`। @@ -506,10 +559,13 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে। -!!! Tip - এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨ +/// tip - এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀 +এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨ + +এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀 + +/// ## **FastAPI**-এ টাইপ হিন্টস @@ -533,5 +589,8 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে। -!!! Info - যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে। +/// info + +যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে। + +/// diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index 2bfcfab33..6f2c4b2dd 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Zusätzliche Responses in OpenAPI -!!! warning "Achtung" - Dies ist ein eher fortgeschrittenes Thema. +/// warning | "Achtung" - Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. +Dies ist ein eher fortgeschrittenes Thema. + +Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. + +/// Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren. @@ -27,20 +30,26 @@ Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydan {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note "Hinweis" - Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. +/// note | "Hinweis" + +Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. + +/// + +/// info -!!! info - Der `model`-Schlüssel ist nicht Teil von OpenAPI. +Der `model`-Schlüssel ist nicht Teil von OpenAPI. - **FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. +**FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. - Die richtige Stelle ist: +Die richtige Stelle ist: - * Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: - * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: - * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. - * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. +* Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: + * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: + * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. + * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. + +/// Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten: @@ -172,13 +181,19 @@ Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note "Hinweis" - Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. +/// note | "Hinweis" + +Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. + +/// + +/// info + +Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). -!!! info - Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). +Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. - Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. +/// ## Informationen kombinieren diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index e9de267cf..672efee51 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -14,53 +14,75 @@ Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 26" +{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +``` - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! warning "Achtung" - Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. +/// - Sie wird nicht mit einem Modell usw. serialisiert. +```Python hl_lines="2 23" +{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` - Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). +//// -!!! note "Technische Details" - Sie können auch `from starlette.responses import JSONResponse` verwenden. +//// tab | Python 3.8+ nicht annotiert - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning | "Achtung" + +Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. + +Sie wird nicht mit einem Modell usw. serialisiert. + +Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). + +/// + +/// note | "Technische Details" + +Sie können auch `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. + +/// ## OpenAPI- und API-Dokumentation diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index 33b93b332..f29970872 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -18,26 +18,35 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Dazu deklarieren wir eine Methode `__call__`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. @@ -45,26 +54,35 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. @@ -72,26 +90,35 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer Wir könnten eine Instanz dieser Klasse erstellen mit: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. @@ -107,32 +134,44 @@ checker(q="somequery") ... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. -!!! tip "Tipp" - Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. +Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. - Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. +In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. - In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. +Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. - Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. +/// diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 2e2c22210..9f0bd4aa2 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynch {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. +/// tip | "Tipp" + +Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. + +/// Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. @@ -81,15 +84,24 @@ response = client.get('/') ... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. -!!! tip "Tipp" - Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. +/// tip | "Tipp" + +Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. + +/// -!!! warning "Achtung" - Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. +/// 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 <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. + +/// ## Andere asynchrone Funktionsaufrufe Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. -!!! tip "Tipp" - Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDBs MotorClient</a>), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. +/// tip | "Tipp" + +Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDBs MotorClient</a>), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. + +/// diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index ad0a92e28..18f90ebde 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -43,8 +43,11 @@ browser --> proxy proxy --> server ``` -!!! tip "Tipp" - Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. +/// tip | "Tipp" + +Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. + +/// Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel: @@ -81,10 +84,13 @@ $ uvicorn main:app --root-path /api/v1 Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. -!!! note "Technische Details" - Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. +/// note | "Technische Details" + +Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. + +Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. - Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. +/// ### Überprüfen des aktuellen `root_path` @@ -172,8 +178,11 @@ Dann erstellen Sie eine Datei `traefik.toml` mit: Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. -!!! tip "Tipp" - Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. +/// tip | "Tipp" + +Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. + +/// Erstellen Sie nun die andere Datei `routes.toml`: @@ -239,8 +248,11 @@ Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: <a href="http://127.0.0.1: } ``` -!!! tip "Tipp" - Beachten Sie, dass, obwohl Sie unter `http://127.0.0.1:8000/app` darauf zugreifen, als `root_path` angezeigt wird `/api/v1`, welches aus der Option `--root-path` stammt. +/// tip | "Tipp" + +Beachten Sie, dass, obwohl Sie unter `http://127.0.0.1:8000/app` darauf zugreifen, als `root_path` angezeigt wird `/api/v1`, welches aus der Option `--root-path` stammt. + +/// Öffnen Sie nun die URL mit dem Port für Traefik, einschließlich des Pfadpräfixes: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>. @@ -283,8 +295,11 @@ Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`ser ## Zusätzliche Server -!!! warning "Achtung" - Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. +/// warning | "Achtung" + +Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. + +/// Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`. @@ -323,15 +338,21 @@ Erzeugt ein OpenAPI-Schema, wie: } ``` -!!! tip "Tipp" - Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. +/// tip | "Tipp" + +Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. + +/// In der Dokumentationsoberfläche unter <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> würde es so aussehen: <img src="/img/tutorial/behind-a-proxy/image03.png"> -!!! tip "Tipp" - Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. +/// tip | "Tipp" + +Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. + +/// ### Den automatischen Server von `root_path` deaktivieren diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 68c037ad7..20d6a039a 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in die Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben. -!!! note "Hinweis" - Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. +/// note | "Hinweis" + +Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. + +/// ## `ORJSONResponse` verwenden @@ -31,15 +34,21 @@ Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSO {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info - Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. +/// info + +Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. + +In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt. + +Und er wird als solcher in OpenAPI dokumentiert. + +/// - In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt. +/// tip | "Tipp" - Und er wird als solcher in OpenAPI dokumentiert. +Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. -!!! tip "Tipp" - Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. +/// ## HTML-Response @@ -52,12 +61,15 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info - Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. +/// info - In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. +Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. - Und er wird als solcher in OpenAPI dokumentiert. +In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. + +Und er wird als solcher in OpenAPI dokumentiert. + +/// ### Eine `Response` zurückgeben @@ -69,11 +81,17 @@ Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so a {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "Achtung" - Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. +/// warning | "Achtung" + +Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. + +/// + +/// info -!!! info - Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. +Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. + +/// ### In OpenAPI dokumentieren und `Response` überschreiben @@ -103,10 +121,13 @@ Hier sind einige der verfügbaren Responses. Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen. -!!! note "Technische Details" - Sie können auch `from starlette.responses import HTMLResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import HTMLResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ### `Response` @@ -153,15 +174,21 @@ Eine schnelle alternative JSON-Response mit <a href="https://github.com/ijl/orjs Eine alternative JSON-Response mit <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>. -!!! warning "Achtung" - `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. +/// warning | "Achtung" + +`ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "Tipp" - Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. +/// tip | "Tipp" + +Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. + +/// ### `RedirectResponse` @@ -222,8 +249,11 @@ Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbei Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird. -!!! tip "Tipp" - Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. +/// tip | "Tipp" + +Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. + +/// ### `FileResponse` @@ -292,8 +322,11 @@ Im folgenden Beispiel verwendet **FastAPI** standardmäßig `ORJSONResponse` in {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip "Tipp" - Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. +/// tip | "Tipp" + +Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. + +/// ## Zusätzliche Dokumentation diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md index c78a6d3dd..d5a663485 100644 --- a/docs/de/docs/advanced/dataclasses.md +++ b/docs/de/docs/advanced/dataclasses.md @@ -20,12 +20,15 @@ Und natürlich wird das gleiche unterstützt: Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt. -!!! info - Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. +/// info - Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. +Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. - Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 +Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. + +Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 + +/// ## Datenklassen als `response_model` diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md index e29f61ab9..e898db49b 100644 --- a/docs/de/docs/advanced/events.md +++ b/docs/de/docs/advanced/events.md @@ -38,10 +38,13 @@ Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden. -!!! tip "Tipp" - Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. +/// tip | "Tipp" - Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 +Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. + +Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 + +/// ### Lifespan-Funktion @@ -91,10 +94,13 @@ Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontext ## Alternative Events (deprecated) -!!! warning "Achtung" - Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. +/// warning | "Achtung" + +Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. - Sie können diesen Teil wahrscheinlich überspringen. +Sie können diesen Teil wahrscheinlich überspringen. + +/// Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird. @@ -126,17 +132,23 @@ Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführ Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. -!!! info - In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. +/// info + +In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. -!!! tip "Tipp" - Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. +/// - Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. +/// tip | "Tipp" - Aber `open()` verwendet nicht `async` und `await`. +Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. - Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. +Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. + +Aber `open()` verwendet nicht `async` und `await`. + +Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. + +/// ### `startup` und `shutdown` zusammen @@ -152,10 +164,13 @@ Nur ein technisches Detail für die neugierigen Nerds. 🤓 In der technischen ASGI-Spezifikation ist dies Teil des <a href="https://asgi.readthedocs.io/en/latest/specs/lifespan.html" class="external-link" target="_blank">Lifespan Protokolls</a> und definiert Events namens `startup` und `shutdown`. -!!! info - Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlettes Lifespan-Dokumentation</a>. +/// info + +Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlettes Lifespan-Dokumentation</a>. + +Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. - Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. +/// ## Unteranwendungen diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index d69437954..b8d66fdd7 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -28,17 +28,21 @@ Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und d Beginnen wir mit einer einfachen FastAPI-Anwendung: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` + +//// Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-<abbr title="Die eigentlichen Nutzdaten, abzüglich der Metadaten">Payload</abbr> verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. @@ -123,8 +127,11 @@ Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payl <img src="/img/tutorial/generate-clients/image03.png"> -!!! tip "Tipp" - Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. +/// tip | "Tipp" + +Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. + +/// Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten: @@ -140,17 +147,21 @@ In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrs Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### Einen TypeScript-Client mit Tags generieren @@ -197,17 +208,21 @@ Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren @@ -229,17 +244,21 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: -=== "Python" +//// tab | Python - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.py!} - ``` +```Python +{!> ../../../docs_src/generate_clients/tutorial004.py!} +``` + +//// -=== "Node.js" +//// tab | Node.js + +```Javascript +{!> ../../../docs_src/generate_clients/tutorial004.js!} +``` - ```Javascript - {!> ../../../docs_src/generate_clients/tutorial004.js!} - ``` +//// Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann. diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md index 048e31e06..953ad317d 100644 --- a/docs/de/docs/advanced/index.md +++ b/docs/de/docs/advanced/index.md @@ -6,10 +6,13 @@ Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link t In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. -!!! tip "Tipp" - Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. +/// tip | "Tipp" - Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// ## Lesen Sie zuerst das Tutorial diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index 2c4e8542a..4116b30ec 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. -!!! note "Technische Details" - Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. +/// note | "Technische Details" - **FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. +Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. + +**FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index 026fdb4fe..d7b5bc885 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -35,8 +35,11 @@ Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrschei {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "Tipp" - Der Query-Parameter `callback_url` verwendet einen Pydantic-<a href="https://docs.pydantic.dev/latest/api/networks/" class="external-link" target="_blank">Url</a>-Typ. +/// tip | "Tipp" + +Der Query-Parameter `callback_url` verwendet einen Pydantic-<a href="https://docs.pydantic.dev/latest/api/networks/" class="external-link" target="_blank">Url</a>-Typ. + +/// Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist. @@ -61,10 +64,13 @@ Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API a In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. -!!! tip "Tipp" - Der eigentliche Callback ist nur ein HTTP-Request. +/// tip | "Tipp" + +Der eigentliche Callback ist nur ein HTTP-Request. - Wenn Sie den Callback selbst implementieren, können Sie beispielsweise <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> oder <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a> verwenden. +Wenn Sie den Callback selbst implementieren, können Sie beispielsweise <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> oder <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a> verwenden. + +/// ## Schreiben des Codes, der den Callback dokumentiert @@ -74,10 +80,13 @@ Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatisch Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). -!!! tip "Tipp" - Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. +/// tip | "Tipp" + +Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. - Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. +Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. + +/// ### Einen Callback-`APIRouter` erstellen @@ -154,8 +163,11 @@ und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie d } ``` -!!! tip "Tipp" - Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). +/// tip | "Tipp" + +Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). + +/// ### Den Callback-Router hinzufügen @@ -167,8 +179,11 @@ Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer AP {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. +/// tip | "Tipp" + +Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. + +/// ### Es in der Dokumentation ansehen diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index 339218080..fb0daa908 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -22,8 +22,11 @@ Mit **FastAPI** können Sie mithilfe von OpenAPI die Namen dieser Webhooks, die Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren. -!!! info - Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. +/// info + +Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. + +/// ## Eine Anwendung mit Webhooks @@ -35,8 +38,11 @@ Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. -!!! info - Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. +/// info + +Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. + +/// Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index 406a08e9e..c9cb82fe3 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning "Achtung" - Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. +/// warning | "Achtung" + +Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. + +/// Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll. @@ -23,13 +26,19 @@ Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "Tipp" - Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. +/// tip | "Tipp" + +Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. + +/// + +/// warning | "Achtung" + +Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. -!!! warning "Achtung" - Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. +Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. - Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. +/// ## Von OpenAPI ausschließen @@ -65,8 +74,11 @@ Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es un Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. -!!! note "Technische Details" - In der OpenAPI-Spezifikation wird das <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operationsobjekt</a> genannt. +/// note | "Technische Details" + +In der OpenAPI-Spezifikation wird das <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operationsobjekt</a> genannt. + +/// Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet. @@ -74,10 +86,13 @@ Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. -!!! tip "Tipp" - Dies ist ein Low-Level Erweiterungspunkt. +/// tip | "Tipp" + +Dies ist ein Low-Level Erweiterungspunkt. - Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. +Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. + +/// Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden. @@ -150,20 +165,27 @@ Und Sie könnten dies auch tun, wenn der Datentyp in der Anfrage nicht JSON ist. In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +//// -=== "Pydantic v1" +/// info - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. -!!! info - In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. +/// Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren. @@ -171,22 +193,32 @@ Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. -=== "Pydantic v1" +/// - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +/// tip | "Tipp" -!!! info - In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. +Hier verwenden wir dasselbe Pydantic-Modell wieder. -!!! tip "Tipp" - Hier verwenden wir dasselbe Pydantic-Modell wieder. +Aber genauso hätten wir es auch auf andere Weise validieren können. - Aber genauso hätten wir es auch auf andere Weise validieren können. +/// diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 0f09bd444..3d2043565 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -30,20 +30,26 @@ Setzen Sie dann Cookies darin und geben Sie sie dann zurück: {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. +/// tip | "Tipp" - Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. +Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. - Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. +Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. + +Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. + +/// ### Mehr Informationen -!!! note "Technische Details" - Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. - Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. +/// Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">Dokumentation in Starlette</a> an. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 13bca7825..377490b56 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookie Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. -!!! tip "Tipp" - `JSONResponse` selbst ist eine Unterklasse von `Response`. +/// tip | "Tipp" + +`JSONResponse` selbst ist eine Unterklasse von `Response`. + +/// Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten. @@ -35,10 +38,13 @@ In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ## Eine benutzerdefinierte `Response` zurückgeben diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md index 6f4760e7f..51a364f56 100644 --- a/docs/de/docs/advanced/response-headers.md +++ b/docs/de/docs/advanced/response-headers.md @@ -28,12 +28,15 @@ Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response- {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. - Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +/// ## Benutzerdefinierte Header diff --git a/docs/de/docs/advanced/security/http-basic-auth.md b/docs/de/docs/advanced/security/http-basic-auth.md index 9f9c0cf7d..3e7aeb8a0 100644 --- a/docs/de/docs/advanced/security/http-basic-auth.md +++ b/docs/de/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,35 @@ Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser di * Diese gibt ein Objekt vom Typ `HTTPBasicCredentials` zurück: * Es enthält den gesendeten `username` und das gesendete `password`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` +```Python hl_lines="4 8 12" +{!> ../../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../../docs_src/security/tutorial006_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +```Python hl_lines="2 6 10" +{!> ../../../docs_src/security/tutorial006.py!} +``` + +//// Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen: @@ -59,26 +68,35 @@ Um dies zu lösen, konvertieren wir zunächst den `username` und das `password` Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="1 11-21" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// Dies wäre das gleiche wie: @@ -142,23 +160,32 @@ So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, v Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="23-27" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md index a3c975bed..380e48bbf 100644 --- a/docs/de/docs/advanced/security/index.md +++ b/docs/de/docs/advanced/security/index.md @@ -4,10 +4,13 @@ Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit. -!!! tip "Tipp" - Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. +/// tip | "Tipp" - Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// ## Lesen Sie zuerst das Tutorial diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md index ffd34d65f..f02707698 100644 --- a/docs/de/docs/advanced/security/oauth2-scopes.md +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter an In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten. -!!! warning "Achtung" - Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. +/// warning | "Achtung" - Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. +Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. - Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. +Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. - Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. +Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. - In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. +Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. - Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. +In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. + +Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. + +/// ## OAuth2-Scopes und OpenAPI @@ -43,63 +46,87 @@ Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu dekla * `instagram_basic` wird von Facebook / Instagram verwendet. * `https://www.googleapis.com/auth/drive` wird von Google verwendet. -!!! info - In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. +/// info + +In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + +Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. - Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. +Diese Details sind implementierungsspezifisch. - Diese Details sind implementierungsspezifisch. +Für OAuth2 sind es einfach nur Strings. - Für OAuth2 sind es einfach nur Strings. +/// ## Gesamtübersicht Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+" +/// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +/// -=== "Python 3.9+ nicht annotiert" +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +/// + +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Sehen wir uns diese Änderungen nun Schritt für Schritt an. @@ -109,51 +136,71 @@ Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei ve Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.10+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="61-64" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="61-64" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.9+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. @@ -171,55 +218,79 @@ Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Und wir geben die Scopes als Teil des JWT-Tokens zurück. -!!! danger "Gefahr" - Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. +/// danger | "Gefahr" + +Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. - Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. +Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. -=== "Python 3.10+" +/// - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.9+" +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.9+ - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ - ```Python hl_lines="154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` -=== "Python 3.9+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +```Python hl_lines="154" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren @@ -237,62 +308,89 @@ Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängi In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). -!!! note "Hinweis" - Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. +/// note | "Hinweis" + +Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. + +Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="4 139 170" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 139 170" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 140 171" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" - Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+" +/// - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="3 138 167" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="4 140 171" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="3 138 167" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// -!!! info "Technische Details" - `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. +/// info | "Technische Details" - Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. +`Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. - Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. +Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. + +Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. + +/// ## `SecurityScopes` verwenden @@ -308,50 +406,71 @@ Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der au Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 106" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="7 104" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8 106" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="7 104" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// ## Die `scopes` verwenden @@ -365,50 +484,71 @@ Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederve In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="104 106-114" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="104 106-114" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Den `username` und das Format der Daten überprüfen @@ -424,50 +564,71 @@ Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anw Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="45 115-126" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="45 115-126" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Die `scopes` verifizieren @@ -475,50 +636,71 @@ Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von die Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="127-133" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="127-133" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.9+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Abhängigkeitsbaum und Scopes @@ -545,10 +727,13 @@ So sieht die Hierarchie der Abhängigkeiten und Scopes aus: * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. -!!! tip "Tipp" - Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. +/// tip | "Tipp" + +Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. - Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. +Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. + +/// ## Weitere Details zu `SecurityScopes`. @@ -586,10 +771,13 @@ Am häufigsten ist der „Implicit“-Flow. Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. -!!! note "Hinweis" - Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. +/// note | "Hinweis" + +Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. + +Aber am Ende implementieren sie denselben OAuth2-Standard. - Aber am Ende implementieren sie denselben OAuth2-Standard. +/// **FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`. diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index fe01d8e1f..3cd4c6c7d 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -8,44 +8,51 @@ Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestell ## Umgebungsvariablen -!!! tip "Tipp" - Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. +/// tip | "Tipp" + +Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. + +/// Eine <a href="https://de.wikipedia.org/wiki/Umgebungsvariable" class="external-link" target="_blank">Umgebungsvariable</a> (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann. Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - // Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels - $ export MY_NAME="Wade Wilson" +```console +// Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels +$ export MY_NAME="Wade Wilson" - // Dann könnten Sie diese mit anderen Programmen verwenden, etwa - $ echo "Hello $MY_NAME" +// Dann könnten Sie diese mit anderen Programmen verwenden, etwa +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +</div> - Hello Wade Wilson - ``` +//// - </div> +//// tab | Windows PowerShell -=== "Windows PowerShell" +<div class="termy"> - <div class="termy"> +```console +// Erstelle eine Umgebungsvariable MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Erstelle eine Umgebungsvariable MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Verwende sie mit anderen Programmen, etwa +$ echo "Hello $Env:MY_NAME" - // Verwende sie mit anderen Programmen, etwa - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +</div> - </div> +//// ### Umgebungsvariablen mit Python auslesen @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip "Tipp" - Das zweite Argument für <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> ist der zurückzugebende Defaultwert. +/// tip | "Tipp" + +Das zweite Argument für <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> ist der zurückzugebende Defaultwert. - Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. +Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. + +/// Dann könnten Sie dieses Python-Programm aufrufen: @@ -114,8 +124,11 @@ Hello World from Python </div> -!!! tip "Tipp" - Weitere Informationen dazu finden Sie unter <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>. +/// tip | "Tipp" + +Weitere Informationen dazu finden Sie unter <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>. + +/// ### Typen und Validierung @@ -151,8 +164,11 @@ $ pip install "fastapi[all]" </div> -!!! info - In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. +/// info + +In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. + +/// ### Das `Settings`-Objekt erstellen @@ -162,23 +178,33 @@ Auf die gleiche Weise wie bei Pydantic-Modellen deklarieren Sie Klassenattribute Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +/// info + +In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001_pv1.py!} +``` -=== "Pydantic v1" +//// - !!! info - In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. +/// tip | "Tipp" - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. -!!! tip "Tipp" - Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. +/// Wenn Sie dann eine Instanz dieser `Settings`-Klasse erstellen (in diesem Fall als `settings`-Objekt), liest Pydantic die Umgebungsvariablen ohne Berücksichtigung der Groß- und Kleinschreibung. Eine Variable `APP_NAME` in Großbuchstaben wird also als Attribut `app_name` gelesen. @@ -206,8 +232,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app </div> -!!! tip "Tipp" - Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. +/// tip | "Tipp" + +Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. + +/// Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt. @@ -231,8 +260,11 @@ Und dann verwenden Sie diese in einer Datei `main.py`: {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip "Tipp" - Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. +/// tip | "Tipp" + +Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. + +/// ## Einstellungen in einer Abhängigkeit @@ -254,54 +286,75 @@ Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erste Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Wir werden das `@lru_cache` in Kürze besprechen. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// + +/// tip | "Tipp" + +Wir werden das `@lru_cache` in Kürze besprechen. + +Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. + +/// Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// ### Einstellungen und Tests @@ -321,15 +374,21 @@ Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielle Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. -!!! tip "Tipp" - Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. +/// tip | "Tipp" + +Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. - Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. +Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. + +/// Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>. -!!! tip "Tipp" - Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. +/// tip | "Tipp" + +Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. + +/// ### Die `.env`-Datei @@ -344,26 +403,39 @@ APP_NAME="ChimichangApp" Und dann aktualisieren Sie Ihre `config.py` mit: -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/settings/app03_an/config.py!} +``` - !!! tip "Tipp" - Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/latest/concepts/config/" class="external-link" target="_blank">Pydantic: Configuration</a>. +/// tip | "Tipp" -=== "Pydantic v1" +Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/latest/concepts/config/" class="external-link" target="_blank">Pydantic: Configuration</a>. - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +/// - !!! tip "Tipp" - Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. +//// -!!! info - In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// tip | "Tipp" + +Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. + +/// + +//// + +/// info + +In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. + +/// Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten. @@ -390,26 +462,35 @@ würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index 17d821e61..abc7624f1 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -31,18 +31,27 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note "Hinweis" - Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. +/// note | "Hinweis" - Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. +Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. -!!! tip "Tipp" - Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. +Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. -!!! note "Technische Details" - Sie können auch `from starlette.templating import Jinja2Templates` verwenden. +/// - **FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. +/// tip | "Tipp" + +Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. + +/// + +/// note | "Technische Details" + +Sie können auch `from starlette.templating import Jinja2Templates` verwenden. + +**FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. + +/// ## Templates erstellen diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index e7841b5f5..f131d27cd 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -28,48 +28,67 @@ Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüsse Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="26-27 30" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} - ``` +```Python hl_lines="26-27 30" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="29-30 33" - {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="24-25 28" +{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="24-25 28" - {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001.py!} +``` - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001.py!} - ``` +//// -!!! tip "Tipp" - Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. +/// tip | "Tipp" - Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. +Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. - FastAPI kann sie in jedem Fall überschreiben. +Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. + +FastAPI kann sie in jedem Fall überschreiben. + +/// Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), indem Sie `app.dependency_overrides` auf ein leeres `dict` setzen: @@ -77,5 +96,8 @@ Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), inde app.dependency_overrides = {} ``` -!!! tip "Tipp" - Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. +/// tip | "Tipp" + +Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. + +/// diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 53de72f15..4cbc45c17 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung z {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "Hinweis" - Weitere Informationen finden Sie in der Starlette-Dokumentation zum <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Testen von WebSockets</a>. +/// note | "Hinweis" + +Weitere Informationen finden Sie in der Starlette-Dokumentation zum <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Testen von WebSockets</a>. + +/// diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index f40f5d4be..1d575a7cb 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -35,18 +35,24 @@ Dazu müssen Sie direkt auf den Request zugreifen. Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. -!!! tip "Tipp" - Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. +/// tip | "Tipp" - Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. +Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. - Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. +Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. + +Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. + +/// ## `Request`-Dokumentation Weitere Details zum <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation</a>. -!!! note "Technische Details" - Sie können auch `from starlette.requests import Request` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.requests import Request` verwenden. + +**FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. - **FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. +/// diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index e5e6a9d01..6d772b6c9 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -50,10 +50,13 @@ Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.websockets import WebSocket` verwenden. +/// note | "Technische Details" - **FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. +Sie können auch `from starlette.websockets import WebSocket` verwenden. + +**FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. + +/// ## Nachrichten erwarten und Nachrichten senden @@ -112,46 +115,65 @@ In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verw Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// + +```Python hl_lines="68-69 81" +{!> ../../../docs_src/websockets/tutorial002.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. +Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. - Sie können einen „Closing“-Code verwenden, aus den <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">gültigen Codes, die in der Spezifikation definiert sind</a>. +Sie können einen „Closing“-Code verwenden, aus den <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">gültigen Codes, die in der Spezifikation definiert sind</a>. + +/// ### WebSockets mit Abhängigkeiten ausprobieren @@ -174,8 +196,11 @@ Dort können Sie einstellen: * Die „Item ID“, die im Pfad verwendet wird. * Das „Token“, das als Query-Parameter verwendet wird. -!!! tip "Tipp" - Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. +/// tip | "Tipp" + +Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. + +/// Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfangen: @@ -185,17 +210,21 @@ Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfan Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// Zum Ausprobieren: @@ -209,12 +238,15 @@ Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients e Client #1596980209979 left the chat ``` -!!! tip "Tipp" - Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. +/// tip | "Tipp" + +Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. + +Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. - Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. +Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> an. - Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> an. +/// ## Mehr Informationen diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md index ea624ff3a..286ef1723 100644 --- a/docs/de/docs/alternatives.md +++ b/docs/de/docs/alternatives.md @@ -30,12 +30,17 @@ Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbri Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. -!!! note "Hinweis" - Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. +/// note | "Hinweis" +Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. -!!! check "Inspirierte **FastAPI**" - Eine automatische API-Dokumentationsoberfläche zu haben. +/// + +/// check | "Inspirierte **FastAPI**" + +Eine automatische API-Dokumentationsoberfläche zu haben. + +/// ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> @@ -51,11 +56,13 @@ Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframew Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. -!!! check "Inspirierte **FastAPI**" - Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. +/// check | "Inspirierte **FastAPI**" - Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. +Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. +Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. + +/// ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> @@ -91,11 +98,13 @@ def read_url(): Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. -!!! check "Inspirierte **FastAPI**" - * Über eine einfache und intuitive API zu verfügen. - * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. - * Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. +/// check | "Inspirierte **FastAPI**" + +* Über eine einfache und intuitive API zu verfügen. +* HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. +* Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -109,15 +118,18 @@ Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umben Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. -!!! check "Inspirierte **FastAPI**" - Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. +/// check | "Inspirierte **FastAPI**" + +Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. - Und Standard-basierte Tools für die Oberfläche zu integrieren: +Und Standard-basierte Tools für die Oberfläche zu integrieren: - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> - Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). +Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). + +/// ### Flask REST Frameworks @@ -135,8 +147,11 @@ Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibl Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein <abbr title="die Definition, wie Daten geformt sein werden sollen">Schema</abbr> zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. -!!! check "Inspirierte **FastAPI**" - Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. +/// check | "Inspirierte **FastAPI**" + +Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -148,11 +163,17 @@ Es verwendet unter der Haube Marshmallow, um die Datenvalidierung durchzuführen Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte. -!!! info - Webargs wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +Webargs wurde von denselben Marshmallow-Entwicklern erstellt. + +/// + +/// check | "Inspirierte **FastAPI**" -!!! check "Inspirierte **FastAPI**" - Eingehende Requestdaten automatisch zu validieren. +Eingehende Requestdaten automatisch zu validieren. + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -172,12 +193,17 @@ Aber dann haben wir wieder das Problem einer Mikrosyntax innerhalb eines Python- Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet. -!!! info - APISpec wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +APISpec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// +/// check | "Inspirierte **FastAPI**" -!!! check "Inspirierte **FastAPI**" - Den offenen Standard für APIs, OpenAPI, zu unterstützen. +Den offenen Standard für APIs, OpenAPI, zu unterstützen. + +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -199,11 +225,17 @@ Die Verwendung führte zur Entwicklung mehrerer Flask-Full-Stack-Generatoren. Di Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// -!!! check "Inspirierte **FastAPI**" - Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. +/// check | "Inspirierte **FastAPI**" + +Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (und <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) @@ -219,24 +251,33 @@ Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. -!!! check "Inspirierte **FastAPI**" - Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. +/// check | "Inspirierte **FastAPI**" + +Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. - Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. +Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. + +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. -!!! note "Technische Details" - Es verwendete <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. +/// note | "Technische Details" + +Es verwendete <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. - Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. +Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. -!!! check "Inspirierte **FastAPI**" - Einen Weg zu finden, eine hervorragende Performanz zu haben. +/// - Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). +/// check | "Inspirierte **FastAPI**" + +Einen Weg zu finden, eine hervorragende Performanz zu haben. + +Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -246,12 +287,15 @@ Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter e Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. -!!! check "Inspirierte **FastAPI**" - Wege zu finden, eine großartige Performanz zu erzielen. +/// check | "Inspirierte **FastAPI**" - Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. +Wege zu finden, eine großartige Performanz zu erzielen. - Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. +Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. + +Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. + +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -269,10 +313,13 @@ Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängig Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. -!!! check "Inspirierte **FastAPI**" - Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. +/// check | "Inspirierte **FastAPI**" + +Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. - Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). +Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). + +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -288,15 +335,21 @@ Es verfügt über eine interessante, ungewöhnliche Funktion: Mit demselben Fram Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz. -!!! info - Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. +/// info + +Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. + +/// -!!! check "Ideen, die **FastAPI** inspiriert haben" - Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. +/// check | "Ideen, die **FastAPI** inspiriert haben" - Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. +Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. - Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. +Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. + +Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. + +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (≦ 0.5) @@ -322,23 +375,29 @@ Es handelte sich nicht länger um ein API-Webframework, da sich der Entwickler a Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework. -!!! info - APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: +/// info + +APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: - * Django REST Framework - * Starlette (auf welchem **FastAPI** basiert) - * Uvicorn (verwendet von Starlette und **FastAPI**) +* Django REST Framework +* Starlette (auf welchem **FastAPI** basiert) +* Uvicorn (verwendet von Starlette und **FastAPI**) -!!! check "Inspirierte **FastAPI**" - Zu existieren. +/// - Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. +/// check | "Inspirierte **FastAPI**" - Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. +Zu existieren. - Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. +Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. - Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. +Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. + +Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. + +Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. + +/// ## Verwendet von **FastAPI** @@ -350,10 +409,13 @@ Das macht es äußerst intuitiv. Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig. -!!! check "**FastAPI** verwendet es, um" - Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. +/// check | "**FastAPI** verwendet es, um" - **FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. +Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. + +**FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. + +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -382,17 +444,23 @@ Es bietet jedoch keine automatische Datenvalidierung, Serialisierung oder Dokume Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw. -!!! note "Technische Details" - ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. +/// note | "Technische Details" + +ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. - Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. +Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. -!!! check "**FastAPI** verwendet es, um" - Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. +/// - Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. +/// check | "**FastAPI** verwendet es, um" - Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. +Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. + +Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. + +Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -402,12 +470,15 @@ Es handelt sich nicht um ein Webframework, sondern um einen Server. Beispielswei Es ist der empfohlene Server für Starlette und **FastAPI**. -!!! check "**FastAPI** empfiehlt es als" - Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. +/// check | "**FastAPI** empfiehlt es als" + +Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. + +Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. - Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. +Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. - Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. +/// ## Benchmarks und Geschwindigkeit diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md index c2a43ac66..74b6b6968 100644 --- a/docs/de/docs/async.md +++ b/docs/de/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. +/// note + +Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. + +/// --- @@ -136,8 +139,11 @@ Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨ <img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration"> -!!! info - Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -199,8 +205,11 @@ Sie essen sie und sind fertig. ⏹ Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞 -!!! info - Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -392,12 +401,15 @@ All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindrucken ## Sehr technische Details -!!! warning "Achtung" - Das folgende können Sie wahrscheinlich überspringen. +/// warning | "Achtung" + +Das folgende können Sie wahrscheinlich überspringen. + +Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. - Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. +Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. - Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. +/// ### Pfadoperation-Funktionen diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md index b1bd62496..58567ad7f 100644 --- a/docs/de/docs/contributing.md +++ b/docs/de/docs/contributing.md @@ -24,63 +24,73 @@ Das erstellt ein Verzeichnis `./env/` mit den Python-Binärdateien und Sie könn Aktivieren Sie die neue Umgebung mit: -=== "Linux, macOS" +//// tab | Linux, macOS - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +<div class="termy"> - </div> +```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +</div> + +//// + +//// tab | Windows Bash - Oder, wenn Sie Bash für Windows verwenden (z. B. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): +Oder, wenn Sie Bash für Windows verwenden (z. B. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): - <div class="termy"> +<div class="termy"> + +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +</div> - </div> +//// Um zu überprüfen, ob es funktioniert hat, geben Sie ein: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ Get-Command pip +<div class="termy"> - some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` - </div> +</div> + +//// Wenn die `pip` Binärdatei unter `env/bin/pip` angezeigt wird, hat es funktioniert. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip </div> -!!! tip "Tipp" - Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. +/// tip | "Tipp" + +Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. - Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. +Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. + +/// ### Benötigtes mit pip installieren @@ -125,10 +138,13 @@ Und wenn Sie diesen lokalen FastAPI-Quellcode aktualisieren und dann die Python- Auf diese Weise müssen Sie Ihre lokale Version nicht „installieren“, um jede Änderung testen zu können. -!!! note "Technische Details" - Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. +/// note | "Technische Details" + +Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. - Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. +Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. + +/// ### Den Code formatieren @@ -170,20 +186,23 @@ Das stellt die Dokumentation unter `http://127.0.0.1:8008` bereit. Auf diese Weise können Sie die Dokumentation/Quelldateien bearbeiten und die Änderungen live sehen. -!!! tip "Tipp" - Alternativ können Sie die Schritte des Skripts auch manuell ausführen. +/// tip | "Tipp" - Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: +Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - ```console - $ cd docs/en/ - ``` +Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: - Führen Sie dann `mkdocs` in diesem Verzeichnis aus: +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +Führen Sie dann `mkdocs` in diesem Verzeichnis aus: + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer-CLI (optional) @@ -210,8 +229,11 @@ Die Dokumentation verwendet <a href="https://www.mkdocs.org/" class="external-li 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. +/// 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/`. @@ -261,10 +283,13 @@ Hier sind die Schritte, die Ihnen bei Übersetzungen helfen. * 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 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">Kommentare mit Änderungsvorschlägen</a> zu vorhandenen Pull Requests hinzufügen. +/// tip | "Tipp" + +Sie können <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">Kommentare mit Änderungsvorschlägen</a> zu vorhandenen Pull Requests hinzufügen. + +Schauen Sie sich die Dokumentation an, <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">wie man ein Review zu einem Pull Request hinzufügt</a>, welches den PR absegnet oder Änderungen vorschlägt. - Schauen Sie sich die Dokumentation an, <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">wie man ein Review zu einem Pull Request hinzufügt</a>, welches den PR absegnet oder Änderungen vorschlägt. +/// * Überprüfen Sie, ob es eine <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub-Diskussion</a> gibt, die Übersetzungen für Ihre Sprache koordiniert. Sie können sie abonnieren, und wenn ein neuer Pull Request zum Review vorliegt, wird der Diskussion automatisch ein Kommentar hinzugefügt. @@ -278,8 +303,11 @@ Angenommen, Sie möchten eine Seite für eine Sprache übersetzen, die bereits Im Spanischen lautet der Zwei-Buchstaben-Code `es`. Das Verzeichnis für spanische Übersetzungen befindet sich also unter `docs/es/`. -!!! tip "Tipp" - Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. +/// tip | "Tipp" + +Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. + +/// Führen Sie nun den Live-Server für die Dokumentation auf Spanisch aus: @@ -296,20 +324,23 @@ $ python ./scripts/docs.py live es </div> -!!! tip "Tipp" - Alternativ können Sie die Schritte des Skripts auch manuell ausführen. +/// tip | "Tipp" + +Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: +Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +Dann führen Sie in dem Verzeichnis `mkdocs` aus: - Dann führen Sie in dem Verzeichnis `mkdocs` aus: +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// Jetzt können Sie auf <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> gehen und Ihre Änderungen live sehen. @@ -329,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "Tipp" - Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. +/// tip | "Tipp" + +Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. + +/// Wenn Sie in Ihrem Browser nachsehen, werden Sie feststellen, dass die Dokumentation jetzt Ihren neuen Abschnitt anzeigt (die Info-Box oben ist verschwunden). 🎉 @@ -365,8 +399,11 @@ Obiges Kommando hat eine Datei `docs/ht/mkdocs.yml` mit einer Minimal-Konfigurat INHERIT: ../en/mkdocs.yml ``` -!!! tip "Tipp" - Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. +/// tip | "Tipp" + +Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. + +/// Das Kommando hat auch eine Dummy-Datei `docs/ht/index.md` für die Hauptseite erstellt. Sie können mit der Übersetzung dieser Datei beginnen. diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md index 5e1a4f109..3c1c0cfce 100644 --- a/docs/de/docs/deployment/concepts.md +++ b/docs/de/docs/deployment/concepts.md @@ -151,10 +151,13 @@ Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, we Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... -!!! tip "Tipp" - ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. +/// tip | "Tipp" - Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. +... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. + +Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. + +/// Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann. @@ -238,10 +241,13 @@ Hier sind einige mögliche Kombinationen und Strategien: * **Cloud-Dienste**, welche das für Sie erledigen * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. -!!! tip "Tipp" - Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. +/// tip | "Tipp" + +Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. + +Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. - Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// ## Schritte vor dem Start @@ -257,10 +263,13 @@ Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. -!!! tip "Tipp" - Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. +/// tip | "Tipp" - In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 +Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. + +In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 + +/// ### Beispiele für Strategien für Vorab-Schritte @@ -272,8 +281,11 @@ Hier sind einige mögliche Ideen: * Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. -!!! tip "Tipp" - Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// tip | "Tipp" + +Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +/// ## Ressourcennutzung diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index b86cf92a4..2186d16c5 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -4,8 +4,11 @@ Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. -!!! tip "Tipp" - Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). +/// tip | "Tipp" + +Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). + +/// <Details> <summary>Dockerfile-Vorschau 👀</summary> @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn </div> -!!! info - Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. +/// info + +Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. - Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 +Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 + +/// ### Den **FastAPI**-Code erstellen @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. -!!! tip "Tipp" - Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 +/// tip | "Tipp" + +Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 + +/// Sie sollten jetzt eine Verzeichnisstruktur wie diese haben: @@ -293,10 +302,13 @@ $ docker build -t myimage . </div> -!!! tip "Tipp" - Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. +/// tip | "Tipp" + +Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. + +In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). - In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). +/// ### Den Docker-Container starten @@ -394,8 +406,11 @@ Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und sp Es könnte sich um einen anderen Container handeln, zum Beispiel mit <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. -!!! tip "Tipp" - Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. +/// tip | "Tipp" + +Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. + +/// Alternativ könnte HTTPS von einem Cloud-Anbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird). @@ -423,8 +438,11 @@ Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, * Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. -!!! tip "Tipp" - Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. +/// tip | "Tipp" + +Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. + +/// Und wenn Sie mit Containern arbeiten, verfügt das gleiche System, mit dem Sie diese starten und verwalten, bereits über interne Tools, um die **Netzwerkkommunikation** (z. B. HTTP-Requests) von diesem **Load Balancer** (das könnte auch ein **TLS-Terminierungsproxy** sein) zu den Containern mit Ihrer Anwendung weiterzuleiten. @@ -503,8 +521,11 @@ Wenn Sie Container (z. B. Docker, Kubernetes) verwenden, können Sie hauptsächl Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnenen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden. -!!! info - Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init-Container</a>. +/// info + +Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init-Container</a>. + +/// Wenn es in Ihrem Anwendungsfall kein Problem darstellt, diese vorherigen Schritte **mehrmals parallel** auszuführen (z. B. wenn Sie keine Datenbankmigrationen ausführen, sondern nur prüfen, ob die Datenbank bereits bereit ist), können Sie sie auch einfach in jedem Container direkt vor dem Start des Hauptprozesses einfügen. @@ -520,8 +541,11 @@ Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [C * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. -!!! warning "Achtung" - Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). +/// warning | "Achtung" + +Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +/// Dieses Image verfügt über einen **Auto-Tuning**-Mechanismus, um die **Anzahl der Arbeitsprozesse** basierend auf den verfügbaren CPU-Kernen festzulegen. @@ -529,8 +553,11 @@ Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotz Es unterstützt auch die Ausführung von <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**Vorab-Schritten vor dem Start** </a> mit einem Skript. -!!! tip "Tipp" - Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +/// tip | "Tipp" + +Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +/// ### Anzahl der Prozesse auf dem offiziellen Docker-Image @@ -657,8 +684,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. -!!! tip "Tipp" - Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. +/// tip | "Tipp" + +Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. + +/// Eine **Docker-Phase** ist ein Teil eines `Dockerfile`s, welcher als **temporäres Containerimage** fungiert und nur zum Generieren einiger Dateien für die spätere Verwendung verwendet wird. diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md index 3ebe59af2..b1f0aca77 100644 --- a/docs/de/docs/deployment/https.md +++ b/docs/de/docs/deployment/https.md @@ -4,8 +4,11 @@ Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ Aber es ist viel komplexer als das. -!!! tip "Tipp" - Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. +/// tip | "Tipp" + +Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. + +/// Um **die Grundlagen von HTTPS** aus Sicht des Benutzers zu erlernen, schauen Sie sich <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a> an. @@ -68,8 +71,11 @@ In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. -!!! tip "Tipp" - Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. +/// tip | "Tipp" + +Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. + +/// ### DNS @@ -115,8 +121,11 @@ Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verb Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. -!!! tip "Tipp" - Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. +/// tip | "Tipp" + +Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. + +/// ### HTTPS-Request diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index ddc31dc5b..2b4ed3fad 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -22,75 +22,89 @@ Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als ** Sie können einen ASGI-kompatiblen Server installieren mit: -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. - <div class="termy"> +<div class="termy"> + +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +</div> - ---> 100% - ``` +/// tip | "Tipp" - </div> +Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. - !!! tip "Tipp" - Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. +Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. - Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. +/// -=== "Hypercorn" +//// - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. +//// tab | Hypercorn - <div class="termy"> +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. - ```console - $ pip install hypercorn +<div class="termy"> + +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +</div> - </div> +... oder jeden anderen ASGI-Server. - ... oder jeden anderen ASGI-Server. +//// ## Das Serverprogramm ausführen Anschließend können Sie Ihre Anwendung auf die gleiche Weise ausführen, wie Sie es in den Tutorials getan haben, jedoch ohne die Option `--reload`, z. B.: -=== "Uvicorn" +//// tab | Uvicorn - <div class="termy"> +<div class="termy"> - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - </div> +</div> + +//// -=== "Hypercorn" +//// tab | Hypercorn - <div class="termy"> +<div class="termy"> + +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +</div> - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning | "Achtung" - </div> +Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. -!!! warning "Achtung" - Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. +Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. - Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. +Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. - Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. +/// ## Hypercorn mit Trio diff --git a/docs/de/docs/deployment/server-workers.md b/docs/de/docs/deployment/server-workers.md index 04d48dc6c..5cd282b4b 100644 --- a/docs/de/docs/deployment/server-workers.md +++ b/docs/de/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md){.internal Hier zeige ich Ihnen, wie Sie <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> mit **Uvicorn Workerprozessen** verwenden. -!!! info - Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// info - Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. +Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. + +/// ## Gunicorn mit Uvicorn-Workern diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md index d71aded22..2d10ac4b6 100644 --- a/docs/de/docs/deployment/versions.md +++ b/docs/de/docs/deployment/versions.md @@ -42,8 +42,11 @@ Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unt FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. -!!! tip "Tipp" - Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. +/// tip | "Tipp" + +Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. + +/// Sie sollten also in der Lage sein, eine Version wie folgt anzupinnen: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. -!!! tip "Tipp" - „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. +/// tip | "Tipp" + +„MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. + +/// ## Upgrade der FastAPI-Versionen diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md index 1dfa70767..ae5a6c908 100644 --- a/docs/de/docs/external-links.md +++ b/docs/de/docs/external-links.md @@ -6,11 +6,17 @@ Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. Hier ist eine unvollständige Liste einiger davon. -!!! tip "Tipp" - Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>. +/// tip | "Tipp" -!!! note "Hinweis Deutsche Übersetzung" - Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt. +Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>. + +/// + +/// note | "Hinweis Deutsche Übersetzung" + +Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index 1e68aff88..b268604fa 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -64,10 +64,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` bedeutet: +/// info - Nimm die Schlüssel-Wert-Paare des `second_user_data` <abbr title="Dictionary – Wörterbuch: In anderen Programmiersprachen auch Hash, Map, Objekt, Assoziatives Array genannt">Dicts</abbr> und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. +`**second_user_data` bedeutet: + +Nimm die Schlüssel-Wert-Paare des `second_user_data` <abbr title="Dictionary – Wörterbuch: In anderen Programmiersprachen auch Hash, Map, Objekt, Assoziatives Array genannt">Dicts</abbr> und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. + +/// ### Editor Unterstützung diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md index d7d7b3359..2c84a5e5b 100644 --- a/docs/de/docs/help-fastapi.md +++ b/docs/de/docs/help-fastapi.md @@ -169,12 +169,15 @@ Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich dir * Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben. -!!! info - Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. +/// info - Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 +Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. - Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 +Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 + +Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 + +/// * Wenn der PR irgendwie vereinfacht werden kann, fragen Sie ruhig danach, aber seien Sie nicht zu wählerisch, es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die wesentlichen Dinge konzentriert. @@ -225,10 +228,13 @@ Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalt Treten Sie dem 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord-Chatserver</a> 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. -!!! tip "Tipp" - Wenn Sie Fragen haben, stellen Sie sie bei <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Diskussionen</a>, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. +/// tip | "Tipp" + +Wenn Sie Fragen haben, stellen Sie sie bei <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Diskussionen</a>, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. + +Nutzen Sie den Chat nur für andere allgemeine Gespräche. - Nutzen Sie den Chat nur für andere allgemeine Gespräche. +/// ### Den Chat nicht für Fragen verwenden diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index a9271b3f3..e8750f7c2 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -40,12 +40,15 @@ Und genau so für ReDoc ... {!../../../docs_src/custom_docs_ui/tutorial001.py!} ``` -!!! tip "Tipp" - Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. +/// tip | "Tipp" - Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. - Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +/// ### Eine *Pfadoperation* erstellen, um es zu testen @@ -177,12 +180,15 @@ Und genau so für ReDoc ... {!../../../docs_src/custom_docs_ui/tutorial002.py!} ``` -!!! tip "Tipp" - Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. +/// tip | "Tipp" + +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. - Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. - Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. +/// ### Eine *Pfadoperation* erstellen, um statische Dateien zu testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index b51a20bfc..a0c4a0e0c 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. -!!! danger "Gefahr" - Dies ist eine „fortgeschrittene“ Funktion. +/// danger | "Gefahr" - Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. +Dies ist eine „fortgeschrittene“ Funktion. + +Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. + +/// ## Anwendungsfälle @@ -27,8 +30,11 @@ Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Reques ### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen -!!! tip "Tipp" - Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. +/// tip | "Tipp" + +Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. + +/// Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren. @@ -54,16 +60,19 @@ Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` z {!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` -!!! note "Technische Details" - Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. +/// note | "Technische Details" - Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. +Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. - Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. +Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. - Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. +Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. - Um mehr über den `Request` zu erfahren, schauen Sie sich <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlettes Dokumentation zu Requests</a> an. +Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. + +Um mehr über den `Request` zu erfahren, schauen Sie sich <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlettes Dokumentation zu Requests</a> an. + +/// Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`. @@ -75,10 +84,13 @@ Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch b ## Zugriff auf den Requestbody in einem Exceptionhandler -!!! tip "Tipp" - Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). +/// tip | "Tipp" + +Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). + +Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. - Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. +/// Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen. diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index 2fbfa13e5..347c5bed3 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -27,8 +27,11 @@ Und diese Funktion `get_openapi()` erhält als Parameter: * `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt. * `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`. -!!! info - Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. +/// info + +Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. + +/// ## Überschreiben der Standardeinstellungen diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md index b8e0bdddd..19af25bb3 100644 --- a/docs/de/docs/how-to/graphql.md +++ b/docs/de/docs/how-to/graphql.md @@ -4,12 +4,15 @@ Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **Gr Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren. -!!! tip "Tipp" - **GraphQL** löst einige sehr spezifische Anwendungsfälle. +/// tip | "Tipp" - Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**. +**GraphQL** löst einige sehr spezifische Anwendungsfälle. - Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓 +Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**. + +Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓 + +/// ## GraphQL-Bibliotheken @@ -46,8 +49,11 @@ Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integra Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a> **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. -!!! tip "Tipp" - Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. +/// tip | "Tipp" + +Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. + +/// ## Mehr darüber lernen diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md index 101829ff8..75779a01c 100644 --- a/docs/de/docs/how-to/index.md +++ b/docs/de/docs/how-to/index.md @@ -6,5 +6,8 @@ Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meis Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. -!!! tip "Tipp" - Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. +/// tip | "Tipp" + +Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index 000bcf633..eaecb27de 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -10,111 +10,123 @@ Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +```Python hl_lines="7" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - # Code unterhalb weggelassen 👇 - ``` +# Code unterhalb weggelassen 👇 +``` - <details> - <summary>👀 Vollständige Dateivorschau</summary> +<details> +<summary>👀 Vollständige Dateivorschau</summary> - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - </details> +</details> -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +//// tab | Python 3.9+ - # Code unterhalb weggelassen 👇 - ``` +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - <details> - <summary>👀 Vollständige Dateivorschau</summary> +# Code unterhalb weggelassen 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +<details> +<summary>👀 Vollständige Dateivorschau</summary> - </details> +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +</details> - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +//// - # Code unterhalb weggelassen 👇 - ``` +//// tab | Python 3.8+ - <details> - <summary>👀 Vollständige Dateivorschau</summary> +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +# Code unterhalb weggelassen 👇 +``` - </details> +<details> +<summary>👀 Vollständige Dateivorschau</summary> + +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +</details> + +//// ### Modell für Eingabe Wenn Sie dieses Modell wie hier als Eingabe verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - ```Python hl_lines="14" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +# Code unterhalb weggelassen 👇 +``` - # Code unterhalb weggelassen 👇 - ``` +<details> +<summary>👀 Vollständige Dateivorschau</summary> - <details> - <summary>👀 Vollständige Dateivorschau</summary> +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +</details> - </details> +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - # Code unterhalb weggelassen 👇 - ``` +# Code unterhalb weggelassen 👇 +``` - <details> - <summary>👀 Vollständige Dateivorschau</summary> +<details> +<summary>👀 Vollständige Dateivorschau</summary> - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` - </details> +</details> -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +//// tab | Python 3.8+ - # Code unterhalb weggelassen 👇 - ``` +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - <details> - <summary>👀 Vollständige Dateivorschau</summary> +# Code unterhalb weggelassen 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +<details> +<summary>👀 Vollständige Dateivorschau</summary> - </details> +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +</details> + +//// ... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. @@ -130,23 +142,29 @@ Sie können überprüfen, dass das Feld `description` in der Dokumentation kein Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +//// ... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. @@ -199,26 +217,35 @@ Der Hauptanwendungsfall hierfür besteht wahrscheinlich darin, dass Sie das mal In diesem Fall können Sie diese Funktion in **FastAPI** mit dem Parameter `separate_input_output_schemas=False` deaktivieren. -!!! info - Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 +/// info + +Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} - ``` +//// ### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md index d11a193dd..9bbff83d3 100644 --- a/docs/de/docs/python-types.md +++ b/docs/de/docs/python-types.md @@ -12,8 +12,11 @@ Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typh Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen. -!!! note "Hinweis" - Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. +/// note | "Hinweis" + +Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +/// ## Motivation @@ -170,45 +173,55 @@ Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die B Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll. -=== "Python 3.9+" +//// tab | Python 3.9+ - Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). +Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). - Als Typ nehmen Sie `list`. +Als Typ nehmen Sie `list`. - Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: +Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): +//// tab | Python 3.8+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): - Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). - Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. +Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. - Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: +Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -!!! tip "Tipp" - Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. +/// tip | "Tipp" - In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber). +Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. + +In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber). + +/// Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`. -!!! tip "Tipp" - Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. +/// tip | "Tipp" + +Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. + +/// Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen: @@ -224,17 +237,21 @@ Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet ent Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// Das bedeutet: @@ -249,17 +266,21 @@ Der erste Typ-Parameter ist für die Schlüssel des `dict`. Der zweite Typ-Parameter ist für die Werte des `dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// Das bedeutet: @@ -275,17 +296,21 @@ In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> aufzulisten. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann. @@ -305,23 +330,29 @@ Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "Python 3.8+ Alternative" +//// tab | Python 3.8+ Alternative - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### `Union` oder `Optional` verwenden? @@ -366,47 +397,53 @@ Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmer Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt. -=== "Python 3.10+" +//// tab | Python 3.10+ + +Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + +* `list` +* `tuple` +* `set` +* `dict` - Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): +Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: - * `list` - * `tuple` - * `set` - * `dict` +* `Union` +* `Optional` (so wie unter Python 3.8) +* ... und andere. - Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: +In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher. - * `Union` - * `Optional` (so wie unter Python 3.8) - * ... und andere. +//// - In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher. +//// tab | Python 3.9+ -=== "Python 3.9+" +Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): - Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: - Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: +* `Union` +* `Optional` +* ... und andere. - * `Union` - * `Optional` - * ... und andere. +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ... und andere. +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ... und andere. + +//// ### Klassen als Typen @@ -446,55 +483,71 @@ Und Sie erhalten volle Editor-Unterstützung für dieses Objekt. Ein Beispiel aus der offiziellen Pydantic Dokumentation: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +//// tab | Python 3.8+ -!!! info - Um mehr über <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an</a>. +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +Um mehr über <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an</a>. + +/// **FastAPI** basiert vollständig auf Pydantic. Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank} sehen. -!!! tip "Tipp" - Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> mehr erfahren. +/// tip | "Tipp" + +Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> mehr erfahren. + +/// ## Typhinweise mit Metadaten-Annotationen Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`. - In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`. +Es wird bereits mit **FastAPI** installiert sein. - Es wird bereits mit **FastAPI** installiert sein. +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`. @@ -506,10 +559,13 @@ Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standa Später werden Sie sehen, wie **mächtig** es sein kann. -!!! tip "Tipp" - Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ +/// tip | "Tipp" - Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀 +Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ + +Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀 + +/// ## Typhinweise in **FastAPI** @@ -533,5 +589,8 @@ Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt. -!!! info - Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">der „Cheat Sheet“ von `mypy`</a>. +/// info + +Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">der „Cheat Sheet“ von `mypy`</a>. + +/// diff --git a/docs/de/docs/reference/index.md b/docs/de/docs/reference/index.md index e9362b962..6fd0ef15f 100644 --- a/docs/de/docs/reference/index.md +++ b/docs/de/docs/reference/index.md @@ -4,5 +4,8 @@ Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribu Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen. -!!! note "Hinweis Deutsche Übersetzung" - Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch. +/// note | "Hinweis Deutsche Übersetzung" + +Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch. + +/// diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md index b170c1e40..cf7eb61ad 100644 --- a/docs/de/docs/reference/request.md +++ b/docs/de/docs/reference/request.md @@ -8,7 +8,10 @@ Sie können es direkt von `fastapi` importieren: from fastapi import Request ``` -!!! tip "Tipp" - Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. +/// tip | "Tipp" + +Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +/// ::: fastapi.Request diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md index 35657172c..d5597d0ee 100644 --- a/docs/de/docs/reference/websockets.md +++ b/docs/de/docs/reference/websockets.md @@ -6,8 +6,11 @@ Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter from fastapi import WebSocket ``` -!!! tip "Tipp" - Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. +/// tip | "Tipp" + +Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +/// ::: fastapi.WebSocket options: diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index a7bfd55a7..0852288d5 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -57,41 +57,57 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem <abbr title="Einb **FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengeführt und anschließend im Hintergrund ausgeführt werden: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="14 16 23 26" +{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md index 66dee0a9a..986a99a38 100644 --- a/docs/de/docs/tutorial/bigger-applications.md +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, das **FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität. -!!! info - Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints. +/// info + +Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints. + +/// ## Eine Beispiel-Dateistruktur @@ -26,16 +29,19 @@ Nehmen wir an, Sie haben eine Dateistruktur wie diese: │ └── admin.py ``` -!!! tip "Tipp" - Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. +/// tip | "Tipp" + +Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. - Das ermöglicht den Import von Code aus einer Datei in eine andere. +Das ermöglicht den Import von Code aus einer Datei in eine andere. - In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben: +In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`. * Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`. @@ -99,8 +105,11 @@ Alle die gleichen Optionen werden unterstützt. Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw. -!!! tip "Tipp" - In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. +/// tip | "Tipp" + +In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. + +/// Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`. @@ -112,31 +121,43 @@ Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`) Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` - ```Python hl_lines="3 6-8" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 5-7" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} - ``` +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="1 4-6" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app/dependencies.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen. +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | "Tipp" + +Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. + +Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen. + +/// ## Ein weiteres Modul mit `APIRouter`. @@ -180,8 +201,11 @@ Wir können auch eine Liste von `tags` und zusätzliche `responses` hinzufügen, Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden. -!!! tip "Tipp" - Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird. +/// tip | "Tipp" + +Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird. + +/// Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten: @@ -198,11 +222,17 @@ Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten: * Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten. * Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen. -!!! tip "Tipp" - `dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden. +/// tip | "Tipp" + +`dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden. + +/// + +/// check -!!! check - Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden. +Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden. + +/// ### Die Abhängigkeiten importieren @@ -218,8 +248,11 @@ Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: #### Wie relative Importe funktionieren -!!! tip "Tipp" - Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. +/// tip | "Tipp" + +Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. + +/// Ein einzelner Punkt `.`, wie in: @@ -286,10 +319,13 @@ Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *P {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip "Tipp" - Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. +/// tip | "Tipp" - Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`. +Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. + +Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`. + +/// ## Das Haupt-`FastAPI`. @@ -345,20 +381,23 @@ Wir könnten sie auch wie folgt importieren: from app.routers import items, users ``` -!!! info - Die erste Version ist ein „relativer Import“: +/// info - ```Python - from .routers import items, users - ``` +Die erste Version ist ein „relativer Import“: - Die zweite Version ist ein „absoluter Import“: +```Python +from .routers import items, users +``` + +Die zweite Version ist ein „absoluter Import“: + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +Um mehr über Python-Packages und -Module zu erfahren, lesen Sie <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">die offizielle Python-Dokumentation über Module</a>. - Um mehr über Python-Packages und -Module zu erfahren, lesen Sie <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">die offizielle Python-Dokumentation über Module</a>. +/// ### Namenskollisionen vermeiden @@ -390,26 +429,35 @@ Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`: {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`. +/// info + +`users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`. - Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`. +Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`. + +/// Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen. Es wird alle Routen von diesem Router als Teil von dieser inkludieren. -!!! note "Technische Details" - Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. +/// note | "Technische Details" + +Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. + +Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre. - Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre. +/// -!!! check - Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen. +/// check - Dies dauert Mikrosekunden und geschieht nur beim Start. +Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen. - Es hat also keinen Einfluss auf die Leistung. ⚡ +Dies dauert Mikrosekunden und geschieht nur beim Start. + +Es hat also keinen Einfluss auf die Leistung. ⚡ + +/// ### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen @@ -456,16 +504,19 @@ Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. -!!! info "Sehr technische Details" - **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. +/// info | "Sehr technische Details" + +**Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. + +--- - --- +Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert. - Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert. +Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten. - Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten. +Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen. - Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen. +/// ## Es in der automatischen API-Dokumentation ansehen diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md index 643be7489..33f7713ee 100644 --- a/docs/de/docs/tutorial/body-fields.md +++ b/docs/de/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperati Importieren Sie es zuerst: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! warning "Achtung" - Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.) +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "Achtung" + +Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.) + +/// ## Modellattribute deklarieren Dann können Sie `Field` mit Modellattributen deklarieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw. -!!! note "Technische Details" - Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist. +/// note | "Technische Details" - Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück. +Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist. - `Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind. +Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück. - Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben. +`Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind. -!!! tip "Tipp" - Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`. +Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben. + +/// + +/// tip | "Tipp" + +Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`. + +/// ## Zusätzliche Information hinzufügen @@ -105,8 +146,11 @@ Sie können zusätzliche Information in `Field`, `Query`, `Body`, usw. deklarier Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren. -!!! warning "Achtung" - Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren. +/// warning | "Achtung" + +Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren. + +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md index 6a237243e..977e17671 100644 --- a/docs/de/docs/tutorial/body-multiple-params.md +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarati Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip | "Tipp" -!!! note "Hinweis" - Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note | "Hinweis" + +Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat. + +/// ## Mehrere Body-Parameter @@ -62,17 +81,21 @@ Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Att Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind). @@ -93,8 +116,11 @@ Es wird deshalb die Parameternamen als Schlüssel (Feldnamen) im Body verwenden, } ``` -!!! note "Hinweis" - Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird. +/// note | "Hinweis" + +Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird. + +/// **FastAPI** wird die automatische Konvertierung des Requests übernehmen, sodass der Parameter `item` seinen spezifischen Inhalt bekommt, genau so wie der Parameter `user`. @@ -110,41 +136,57 @@ Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, das Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +//// In diesem Fall erwartet **FastAPI** einen Body wie: @@ -184,44 +226,63 @@ q: str | None = None Zum Beispiel: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +//// -!!! info - `Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen. +/// info + +`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen. + +/// ## Einen einzelnen Body-Parameter einbetten @@ -237,41 +298,57 @@ item: Item = Body(embed=True) so wie in: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// In diesem Fall erwartet **FastAPI** einen Body wie: diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index a7a15a6c2..8aef965f4 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt. @@ -61,23 +65,29 @@ Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen. In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Set-Typen @@ -87,23 +97,29 @@ Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das <abbr titl Deklarieren wir also `tags` als Set von Strings. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert. @@ -125,45 +141,57 @@ Alles das beliebig tief verschachtelt. Wir können zum Beispiel ein `Image`-Modell definieren. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### Das Kindmodell als Typ verwenden Und dann können wir es als Typ eines Attributes verwenden. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// Das würde bedeuten, dass **FastAPI** einen Body erwartet wie: @@ -196,23 +224,29 @@ Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich <a href="https: Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarieren, dass das eine Instanz von Pydantics `HttpUrl` sein soll, anstelle eines `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert. @@ -220,23 +254,29 @@ Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie: @@ -264,33 +304,45 @@ Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie } ``` -!!! info - Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat. +/// info + +Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat. + +/// ## Tief verschachtelte Modelle Sie können beliebig tief verschachtelte Modelle definieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat. -!!! info - Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat. +/// ## Bodys aus reinen Listen @@ -308,17 +360,21 @@ images: list[Image] so wie in: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## Editor-Unterstützung überall @@ -348,26 +404,33 @@ Das schauen wir uns mal an. Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt. -!!! tip "Tipp" - Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt. +Aber Pydantic hat automatische Datenkonvertierung. - Aber Pydantic hat automatische Datenkonvertierung. +Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren. - Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren. +Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben. - Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md index 2b3716d6f..b83554914 100644 --- a/docs/de/docs/tutorial/body-updates.md +++ b/docs/de/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ Um einen Artikel zu aktualisieren, können Sie die <a href="https://developer.mo Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas zu konvertieren, das als JSON gespeichert werden kann (in z. B. einer NoSQL-Datenbank). Zum Beispiel, um ein `datetime` in einen `str` zu konvertieren. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// `PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. @@ -48,14 +54,17 @@ Sie können auch die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/ Das bedeutet, sie senden nur die Daten, die Sie aktualisieren wollen, der Rest bleibt unverändert. -!!! note "Hinweis" - `PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`. +/// note | "Hinweis" + +`PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`. - Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen. +Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen. - Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf. +Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf. - Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden. +Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden. + +/// ### Pydantics `exclude_unset`-Parameter verwenden @@ -63,61 +72,79 @@ Wenn Sie Teil-Aktualisierungen entgegennehmen, ist der `exclude_unset`-Parameter Wie in `item.model_dump(exclude_unset=True)`. -!!! info - In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. +/// info + +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. - Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen. Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// ### Pydantics `update`-Parameter verwenden Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben. -!!! info - In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt. +/// info + +In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt. - Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können. +Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// Wie in `stored_item_model.model_copy(update=update_data)`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// ### Rekapitulation zum teilweisen Ersetzen @@ -134,32 +161,44 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: * Speichern Sie die Daten in Ihrer Datenbank. * Geben Sie das aktualisierte Modell zurück. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. -=== "Python 3.8+" +Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde. - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +/// -!!! tip "Tipp" - Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. +/// note | "Hinweis" - Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde. +Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. -!!! note "Hinweis" - Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. +Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`). - Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`). +Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden. - Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden. +/// diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 6611cb51a..3fdd4ade3 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -8,28 +8,35 @@ Ihre API sendet fast immer einen **Response**body. Aber Clients senden nicht unb Um einen **Request**body zu deklarieren, verwenden Sie <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>-Modelle mit allen deren Fähigkeiten und Vorzügen. -!!! info - Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden. +/// info - Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle. +Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden. - Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht. +Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle. + +Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht. + +/// ## Importieren Sie Pydantics `BaseModel` Zuerst müssen Sie `BaseModel` von `pydantic` importieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// ## Erstellen Sie Ihr Datenmodell @@ -37,17 +44,21 @@ Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt. Verwenden Sie Standard-Python-Typen für die Klassenattribute: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen. @@ -75,17 +86,21 @@ Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre fol Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`. @@ -134,32 +149,39 @@ Aber Sie bekommen die gleiche Editor-Unterstützung in <a href="https://www.jetb <img src="/img/tutorial/body/image05.png"> -!!! tip "Tipp" - Wenn Sie <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> als Ihren Editor verwenden, probieren Sie das <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a> aus. +/// tip | "Tipp" + +Wenn Sie <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> als Ihren Editor verwenden, probieren Sie das <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a> aus. - Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: +Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: - * Code-Vervollständigung - * Typüberprüfungen - * Refaktorisierung - * Suchen - * Inspektionen +* Code-Vervollständigung +* Typüberprüfungen +* Refaktorisierung +* Suchen +* Inspektionen + +/// ## Das Modell verwenden Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## Requestbody- + Pfad-Parameter @@ -167,17 +189,21 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. **FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## Requestbody- + Pfad- + Query-Parameter @@ -185,17 +211,21 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** **FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` + +//// Die Funktionsparameter werden wie folgt erkannt: @@ -203,10 +233,13 @@ Die Funktionsparameter werden wie folgt erkannt: * Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert. * Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert. -!!! note "Hinweis" - FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` +/// note | "Hinweis" + +FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` + +Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen. - Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen. +/// ## Ohne Pydantic diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index c95e28c7d..0060db8e8 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ So wie `Query`- und `Path`-Parameter können Sie auch <abbr title='Cookie – Importieren Sie zuerst `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/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/cookie_params/tutorial001.py!} +``` + +//// ## `Cookie`-Parameter deklarieren @@ -48,49 +64,71 @@ Dann deklarieren Sie Ihre Cookie-Parameter, auf die gleiche Weise, wie Sie auch Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Technische Details" -=== "Python 3.8+ nicht annotiert" +`Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Technische Details" - `Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. +/// info - Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. +Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. -!!! info - Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md index 9faaed715..0a9f05bf9 100644 --- a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ Bevor wir tiefer in das **Dependency Injection** System eintauchen, lassen Sie u Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Dependable“) zurückgegeben: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.10+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// Aber dann haben wir ein `dict` im Parameter `commons` der *Pfadoperation-Funktion*. @@ -103,117 +119,165 @@ Das gilt auch für Callables ohne Parameter. So wie es auch für *Pfadoperation- Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von oben in die Klasse `CommonQueryParams` ändern: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="12-16" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +/// + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse verwendet wird: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ... sie hat die gleichen Parameter wie unsere vorherige `common_parameters`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="6" +{!> ../../../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="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Diese Parameter werden von **FastAPI** verwendet, um die Abhängigkeit „aufzulösen“. @@ -229,41 +293,57 @@ In beiden Fällen werden die Daten konvertiert, validiert, im OpenAPI-Schema dok Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** ruft die Klasse `CommonQueryParams` auf. Dadurch wird eine „Instanz“ dieser Klasse erstellt und die Instanz wird als Parameter `commons` an Ihre Funktion überreicht. @@ -271,20 +351,27 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// Das letzte `CommonQueryParams`, in: @@ -300,77 +387,107 @@ Aus diesem extrahiert FastAPI die deklarierten Parameter, und dieses ist es, was In diesem Fall hat das erste `CommonQueryParams` in: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python - commons: CommonQueryParams ... - ``` +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ... keine besondere Bedeutung für **FastAPI**. FastAPI verwendet es nicht für die Datenkonvertierung, -validierung, usw. (da es dafür `Depends(CommonQueryParams)` verwendet). Sie könnten tatsächlich einfach schreiben: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python - commons = Depends(CommonQueryParams) - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// ... wie in: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` + +//// Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was als Parameter `commons` übergeben wird, und Ihnen dann bei der Codevervollständigung, Typprüfungen, usw. helfen kann: @@ -380,20 +497,27 @@ Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was al Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// **FastAPI** bietet eine Abkürzung für diese Fälle, wo die Abhängigkeit *speziell* eine Klasse ist, welche **FastAPI** aufruft, um eine Instanz der Klasse selbst zu erstellen. @@ -401,81 +525,114 @@ In diesem speziellen Fall können Sie Folgendes tun: Anstatt zu schreiben: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ... schreiben Sie: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` -=== "Python 3.8 nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8 nicht annotiert - ```Python - commons: CommonQueryParams = Depends() - ``` +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// Sie deklarieren die Abhängigkeit als Typ des Parameters und verwenden `Depends()` ohne Parameter, anstatt die vollständige Klasse *erneut* in `Depends(CommonQueryParams)` schreiben zu müssen. Dasselbe Beispiel würde dann so aussehen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` + +//// ... und **FastAPI** wird wissen, was zu tun ist. -!!! tip "Tipp" - Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht. +/// tip | "Tipp" + +Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht. + +Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren. - Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren. +/// 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 2919aebaf..47d6453c2 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 @@ -14,40 +14,55 @@ Der *Pfadoperation-Dekorator* erhält ein optionales Argument `dependencies`. Es sollte eine `list`e von `Depends()` sein: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 nicht annotiert" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// 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" - Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an. +/// tip | "Tipp" + +Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an. - Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben. +Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben. - Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten. +Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten. -!!! info - In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`. +/// - Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md){.internal-link target=_blank} erzielen. +/// info + +In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`. + +Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md){.internal-link target=_blank} erzielen. + +/// ## Abhängigkeitsfehler und -Rückgabewerte @@ -57,51 +72,69 @@ Sie können dieselben Abhängigkeits-*Funktionen* verwenden, die Sie normalerwei Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhängigkeiten deklarieren: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 nicht annotiert -=== "Python 3.8 nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Exceptions auslösen Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeiten: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 nicht annotiert - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8 nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Rückgabewerte @@ -109,26 +142,35 @@ Und sie können Werte zurückgeben oder nicht, die Werte werden nicht verwendet. Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Sie bereits an anderer Stelle verwenden, wiederverwenden, und auch wenn der Wert nicht verwendet wird, wird die Abhängigkeit ausgeführt: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8 nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## Abhängigkeiten für eine Gruppe von *Pfadoperationen* diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md index e29e87156..9c2e6dd86 100644 --- a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI unterstützt Abhängigkeiten, die nach Abschluss einige <abbr title="Man Verwenden Sie dazu `yield` statt `return` und schreiben Sie die zusätzlichen Schritte / den zusätzlichen Code danach. -!!! tip "Tipp" - Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden. +/// tip | "Tipp" -!!! note "Technische Details" - Jede Funktion, die dekoriert werden kann mit: +Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden. - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +/// - kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden. +/// note | "Technische Details" - Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern. +Jede Funktion, die dekoriert werden kann mit: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + +kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden. + +Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern. + +/// ## Eine Datenbank-Abhängigkeit mit `yield`. @@ -39,10 +45,13 @@ Der auf die `yield`-Anweisung folgende Code wird ausgeführt, nachdem die Respon {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip "Tipp" - Sie können `async`hrone oder reguläre Funktionen verwenden. +/// tip | "Tipp" + +Sie können `async`hrone oder reguläre Funktionen verwenden. + +**FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten. - **FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten. +/// ## Eine Abhängigkeit mit `yield` und `try`. @@ -66,26 +75,35 @@ Sie können Unterabhängigkeiten und „Bäume“ von Unterabhängigkeiten belie Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `dependency_a` abhängen: -=== "Python 3.9+" +//// 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!} +``` + +//// - ```Python hl_lines="6 14 22" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="5 13 21" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 12 20" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` - ```Python hl_lines="4 12 20" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// Und alle können `yield` verwenden. @@ -93,26 +111,35 @@ In diesem Fall benötigt `dependency_c` zum Ausführen seines Exit-Codes, dass d Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` genannt) für seinen Exit-Code. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +```Python hl_lines="18-19 26-27" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +```Python hl_lines="17-18 25-26" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="16-17 24-25" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` - ```Python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// Auf die gleiche Weise könnten Sie einige Abhängigkeiten mit `yield` und einige andere Abhängigkeiten mit `return` haben, und alle können beliebig voneinander abhängen. @@ -122,10 +149,13 @@ Sie können beliebige Kombinationen von Abhängigkeiten haben. **FastAPI** stellt sicher, dass alles in der richtigen Reihenfolge ausgeführt wird. -!!! note "Technische Details" - Dieses funktioniert dank Pythons <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Kontextmanager</a>. +/// note | "Technische Details" - **FastAPI** verwendet sie intern, um das zu erreichen. +Dieses funktioniert dank Pythons <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Kontextmanager</a>. + +**FastAPI** verwendet sie intern, um das zu erreichen. + +/// ## Abhängigkeiten mit `yield` und `HTTPException`. @@ -133,32 +163,43 @@ 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*. - 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*. +Aber es ist für Sie da, wenn Sie es brauchen. 🤓 - Aber es ist für Sie da, wenn Sie es brauchen. 🤓 +/// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-22 31" - {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} - ``` +```Python hl_lines="18-22 31" +{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-21 30" - {!> ../../../docs_src/dependencies/tutorial008b_an.py!} - ``` +```Python hl_lines="17-21 30" +{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="16-20 29" +{!> ../../../docs_src/dependencies/tutorial008b.py!} +``` - ```Python hl_lines="16-20 29" - {!> ../../../docs_src/dependencies/tutorial008b.py!} - ``` +//// Eine Alternative zum Abfangen von Exceptions (und möglicherweise auch zum Auslösen einer weiteren `HTTPException`) besteht darin, einen [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} zu erstellen. @@ -201,22 +242,31 @@ participant tasks as Hintergrundtasks end ``` -!!! info - Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein. +/// info - Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden. +Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein. -!!! 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. +Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden. - Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten übergeben, einschließlich `HTTPException`, und dann **erneut** an die Exceptionhandler. Wenn es für diese Exception keinen Exceptionhandler gibt, wird sie von der internen Default-`ServerErrorMiddleware` gehandhabt, was einen HTTP-Statuscode 500 zurückgibt, um den Client darüber zu informieren, dass ein Fehler auf dem Server aufgetreten ist. +/// + +/// 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. + +Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten übergeben, einschließlich `HTTPException`, und dann **erneut** an die Exceptionhandler. Wenn es für diese Exception keinen Exceptionhandler gibt, wird sie von der internen Default-`ServerErrorMiddleware` gehandhabt, was einen HTTP-Statuscode 500 zurückgibt, um den Client darüber zu informieren, dass ein Fehler auf dem Server aufgetreten ist. + +/// ## Abhängigkeiten mit `yield`, `HTTPException` und Hintergrundtasks -!!! warning "Achtung" - Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren. +/// warning | "Achtung" + +Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren. + +Diese Details sind vor allem dann nützlich, wenn Sie eine Version von FastAPI vor 0.106.0 verwendet haben und Ressourcen aus Abhängigkeiten mit `yield` in Hintergrundtasks verwendet haben. - Diese Details sind vor allem dann nützlich, wenn Sie eine Version von FastAPI vor 0.106.0 verwendet haben und Ressourcen aus Abhängigkeiten mit `yield` in Hintergrundtasks verwendet haben. +/// Vor FastAPI 0.106.0 war das Auslösen von Exceptions nach `yield` nicht möglich, der Exit-Code in Abhängigkeiten mit `yield` wurde ausgeführt, *nachdem* die Response gesendet wurde, die [Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} wären also bereits ausgeführt worden. @@ -224,11 +274,13 @@ 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). +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). - Auf diese Weise erhalten Sie wahrscheinlich saubereren Code. +Auf diese Weise erhalten Sie wahrscheinlich saubereren Code. + +/// Wenn Sie sich früher auf dieses Verhalten verlassen haben, sollten Sie jetzt die Ressourcen für Hintergrundtasks innerhalb des Hintergrundtasks selbst erstellen und intern nur Daten verwenden, die nicht von den Ressourcen von Abhängigkeiten mit `yield` abhängen. @@ -256,10 +308,13 @@ Wenn Sie eine Abhängigkeit mit `yield` erstellen, erstellt **FastAPI** dafür i ### Kontextmanager in Abhängigkeiten mit `yield` verwenden -!!! warning "Achtung" - Dies ist mehr oder weniger eine „fortgeschrittene“ Idee. +/// warning | "Achtung" + +Dies ist mehr oder weniger eine „fortgeschrittene“ Idee. + +Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen. - Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen. +/// In Python können Sie Kontextmanager erstellen, indem Sie <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">eine Klasse mit zwei Methoden erzeugen: `__enter__()` und `__exit__()`</a>. @@ -269,16 +324,19 @@ Sie können solche auch innerhalb von **FastAPI**-Abhängigkeiten mit `yield` ve {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip "Tipp" - Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind: +/// tip | "Tipp" + +Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat. - Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat. +Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet. - Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet. +Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht). - Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht). +FastAPI erledigt das intern für Sie. - FastAPI erledigt das intern für Sie. +/// diff --git a/docs/de/docs/tutorial/dependencies/global-dependencies.md b/docs/de/docs/tutorial/dependencies/global-dependencies.md index 8aa0899b8..26e631b1c 100644 --- a/docs/de/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ Bei einigen Anwendungstypen möchten Sie möglicherweise Abhängigkeiten zur ges In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 nicht annotiert" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial012.py!} +``` + +//// Und alle Ideen aus dem Abschnitt über das [Hinzufügen von `dependencies` zu den *Pfadoperation-Dekoratoren*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} gelten weiterhin, aber in diesem Fall für alle *Pfadoperationen* in der Anwendung. diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md index 6254e976d..f7d9ed510 100644 --- a/docs/de/docs/tutorial/dependencies/index.md +++ b/docs/de/docs/tutorial/dependencies/index.md @@ -30,41 +30,57 @@ Aber so können wir uns besser auf die Funktionsweise des **Dependency Injection Konzentrieren wir uns zunächst auf die Abhängigkeit - die Dependency. Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennimmt wie eine *Pfadoperation-Funktion*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// Das war's schon. @@ -84,90 +100,125 @@ In diesem Fall erwartet diese Abhängigkeit: Und dann wird einfach ein `dict` zurückgegeben, welches diese Werte enthält. -!!! info - FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. +/// info + +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. - Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. - Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. +Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +/// ### `Depends` importieren -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### Deklarieren der Abhängigkeit im <abbr title="Das Abhängige, der Verwender der Abhängigkeit">„Dependant“</abbr> So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. @@ -179,8 +230,11 @@ Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*. -!!! tip "Tipp" - Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. +/// tip | "Tipp" + +Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. + +/// Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum: @@ -201,10 +255,13 @@ common_parameters --> read_users Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen. -!!! check - Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich. +/// check + +Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich. + +Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird. - Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird. +/// ## `Annotated`-Abhängigkeiten wiederverwenden @@ -218,28 +275,37 @@ commons: Annotated[dict, Depends(common_parameters)] Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. +Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. - Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎 +Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎 + +/// Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`. @@ -255,8 +321,11 @@ Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadop Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist. -!!! note "Hinweis" - Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. +/// note | "Hinweis" + +Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. + +/// ## Integriert in OpenAPI diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index 0fa2af839..12664a8cd 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -10,41 +10,57 @@ Diese können so **tief** verschachtelt sein, wie nötig. Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9-10" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.10 nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="9-10" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 nicht annotiert" +//// tab | Python 3.8 nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8 nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. @@ -54,41 +70,57 @@ Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 nicht annotiert - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 nicht annotiert" +//// tab | Python 3.8 nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8 nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Betrachten wir die deklarierten Parameter: @@ -101,46 +133,65 @@ Betrachten wir die deklarierten Parameter: Diese Abhängigkeit verwenden wir nun wie folgt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10 nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "Python 3.10 nicht annotiert" +//// tab | Python 3.8 nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8 nicht annotiert" +/// + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +/// info -!!! info - Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`. +Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`. - Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird. +Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird. + +/// ```mermaid graph TB @@ -161,22 +212,29 @@ Und es speichert den zurückgegebenen Wert in einem <abbr title="Mechanismus, de In einem fortgeschrittenen Szenario, bei dem Sie wissen, dass die Abhängigkeit bei jedem Schritt (möglicherweise mehrmals) in derselben Anfrage aufgerufen werden muss, anstatt den zwischengespeicherten Wert zu verwenden, können Sie den Parameter `use_cache=False` festlegen, wenn Sie `Depends` verwenden: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` - ```Python hl_lines="1" - async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): - return {"fresh_value": fresh_value} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="1" - async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): - return {"fresh_value": fresh_value} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// ## Zusammenfassung @@ -186,9 +244,12 @@ 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" - All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein. +/// tip | "Tipp" + +All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein. + +Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist. - Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist. +Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen. - Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen. +/// diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md index 12f73bd12..38a881b4f 100644 --- a/docs/de/docs/tutorial/encoder.md +++ b/docs/de/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ 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: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. @@ -38,5 +42,8 @@ Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard-<a href="https:/ Es wird also kein großer `str` zurückgegeben, der die Daten im JSON-Format (als String) enthält. Es wird eine Python-Standarddatenstruktur (z. B. ein `dict`) zurückgegeben, mit Werten und Unterwerten, die alle mit JSON kompatibel sind. -!!! note "Hinweis" - `jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich. +/// note | "Hinweis" + +`jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich. + +/// diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md index 0fcb20683..334a232a8 100644 --- a/docs/de/docs/tutorial/extra-data-types.md +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ 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. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md index cdf16c4ba..cfd0230eb 100644 --- a/docs/de/docs/tutorial/extra-models.md +++ b/docs/de/docs/tutorial/extra-models.md @@ -8,31 +8,41 @@ Insbesondere Benutzermodelle, denn: * Das **herausgehende Modell** sollte kein Passwort haben. * Das **Datenbankmodell** sollte wahrscheinlich ein <abbr title='Ein aus scheinbar zufälligen Zeichen bestehender „Fingerabdruck“ eines Textes. Der Inhalt des Textes kann nicht eingesehen werden.'>gehashtes</abbr> Passwort haben. -!!! danger "Gefahr" - Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. +/// danger | "Gefahr" - Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist. +Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. + +Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist. + +/// ## Mehrere Modelle Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. -!!! info - In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. - Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. +/// ### Über `**user_in.dict()` @@ -144,8 +154,11 @@ UserInDB( ) ``` -!!! warning "Achtung" - Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. +/// warning | "Achtung" + +Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. + +/// ## Verdopplung vermeiden @@ -163,17 +176,21 @@ Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union`, oder `anyOf` @@ -183,20 +200,27 @@ Das wird in OpenAPI mit `anyOf` angezeigt. Um das zu tun, verwenden Sie Pythons Standard-Typhinweis <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: -!!! note "Hinweis" - Listen Sie, wenn Sie eine <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a> definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. +/// note | "Hinweis" -=== "Python 3.10+" +Listen Sie, wenn Sie eine <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a> definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ### `Union` in Python 3.10 @@ -218,17 +242,21 @@ Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +//// ## Response mit beliebigem `dict` @@ -238,17 +266,21 @@ Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein n In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index 27ba3ec16..b9e38707c 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note "Hinweis" - Der Befehl `uvicorn main:app` bezieht sich auf: +/// note | "Hinweis" - * `main`: die Datei `main.py` (das sogenannte Python-„Modul“). - * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. - * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. +Der Befehl `uvicorn main:app` bezieht sich auf: + +* `main`: die Datei `main.py` (das sogenannte Python-„Modul“). +* `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. +* `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. + +/// In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht: @@ -136,10 +139,13 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. -!!! note "Technische Details" - `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. +/// note | "Technische Details" + +`FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. - Sie können alle <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>-Funktionalitäten auch mit `FastAPI` nutzen. +Sie können alle <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>-Funktionalitäten auch mit `FastAPI` nutzen. + +/// ### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“ @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. +/// info + +Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. + +/// Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“. @@ -250,16 +259,19 @@ Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die * den Pfad `/` * unter der Verwendung der <abbr title="eine HTTP GET Methode"><code>get</code>-Operation</abbr> gehen -!!! info "`@decorator` Information" - Diese `@something`-Syntax wird in Python „Dekorator“ genannt. +/// info | "`@decorator` Information" - Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). +Diese `@something`-Syntax wird in Python „Dekorator“ genannt. - Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. +Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). - In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. +Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. - Dies ist der „**Pfadoperation-Dekorator**“. +In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. + +Dies ist der „**Pfadoperation-Dekorator**“. + +/// Sie können auch die anderen Operationen verwenden: @@ -274,14 +286,17 @@ Oder die exotischeren: * `@app.patch()` * `@app.trace()` -!!! tip "Tipp" - Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. +/// tip | "Tipp" + +Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. - **FastAPI** erzwingt keine bestimmte Bedeutung. +**FastAPI** erzwingt keine bestimmte Bedeutung. - Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. +Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. - Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. +Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. + +/// ### Schritt 4: Definieren der **Pfadoperation-Funktion** @@ -309,8 +324,11 @@ Sie könnten sie auch als normale Funktion anstelle von `async def` definieren: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Hinweis" - Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. +/// note | "Hinweis" + +Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. + +/// ### Schritt 5: den Inhalt zurückgeben diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md index af658b971..6ee47948c 100644 --- a/docs/de/docs/tutorial/handling-errors.md +++ b/docs/de/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existiere } ``` -!!! tip "Tipp" - Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. +/// tip | "Tipp" - Zum Beispiel ein `dict`, eine `list`, usw. +Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. - Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert. +Zum Beispiel ein `dict`, eine `list`, usw. + +Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert. + +/// ## Benutzerdefinierte Header hinzufügen @@ -106,10 +109,13 @@ Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-I {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Technische Details" - Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`. +/// ## Die Default-Exceptionhandler überschreiben @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` vs. `ValidationError` -!!! warning "Achtung" - Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. +/// warning | "Achtung" + +Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. + +/// `RequestValidationError` ist eine Unterklasse von Pydantics <a href="https://pydantic-docs.helpmanual.io/usage/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. @@ -183,10 +192,13 @@ Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zu {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.responses import PlainTextResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import PlainTextResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ### Den `RequestValidationError`-Body verwenden diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md index 3c9807f47..c8c3a4c57 100644 --- a/docs/de/docs/tutorial/header-params.md +++ b/docs/de/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch <abbr title='H Importieren Sie zuerst `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// ## `Header`-Parameter deklarieren @@ -48,49 +64,71 @@ Dann deklarieren Sie Ihre Header-Parameter, auf die gleiche Weise, wie Sie auch Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! note "Technische Details" - `Header` ist eine Schwesterklasse von `Path`, `Query` und `Cookie`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. +/// - Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Header` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` -!!! info - Um Header zu deklarieren, müssen Sie `Header` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. +//// + +/// note | "Technische Details" + +`Header` ist eine Schwesterklasse von `Path`, `Query` und `Cookie`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. + +Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Header` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. + +/// + +/// info + +Um Header zu deklarieren, müssen Sie `Header` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. + +/// ## Automatische Konvertierung @@ -108,44 +146,63 @@ Sie können also `user_agent` schreiben, wie Sie es normalerweise in Python-Code Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen zu Bindestrichen abschalten möchten, setzen Sie den Parameter `convert_underscores` auf `False`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11" +{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/header_params/tutorial002_an.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! 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. +/// + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` + +//// + +/// 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. + +/// ## Doppelte Header @@ -157,50 +214,71 @@ Sie erhalten dann alle Werte von diesem doppelten Header als Python-`list`e. Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen kann, schreiben Sie: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.9+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// Wenn Sie mit einer *Pfadoperation* kommunizieren, die zwei HTTP-Header sendet, wie: diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md index 93a30d1b3..c15d0b0bd 100644 --- a/docs/de/docs/tutorial/index.md +++ b/docs/de/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausführt. -!!! note "Hinweis" - Sie können die einzelnen Teile auch separat installieren. +/// note | "Hinweis" - Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen: +Sie können die einzelnen Teile auch separat installieren. - ``` - pip install fastapi - ``` +Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen: - Installieren Sie auch `uvicorn` als Server: +``` +pip install fastapi +``` + +Installieren Sie auch `uvicorn` als Server: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten. - Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten. +/// ## Handbuch für fortgeschrittene Benutzer diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md index 2061e2a5b..3ab56ff3e 100644 --- a/docs/de/docs/tutorial/metadata.md +++ b/docs/de/docs/tutorial/metadata.md @@ -22,8 +22,11 @@ Sie können diese wie folgt setzen: {!../../../docs_src/metadata/tutorial001.py!} ``` -!!! tip "Tipp" - Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert. +/// tip | "Tipp" + +Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert. + +/// Mit dieser Konfiguration würde die automatische API-Dokumentation wie folgt aussehen: @@ -65,8 +68,11 @@ 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" - Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. +/// tip | "Tipp" + +Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. + +/// ### Ihre Tags verwenden @@ -76,8 +82,11 @@ Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info - Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags){.internal-link target=_blank}. +/// info + +Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// ### Die Dokumentation anschauen diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md index 7d6e6b71a..62a0d1613 100644 --- a/docs/de/docs/tutorial/middleware.md +++ b/docs/de/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ 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" - Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt. +/// note | "Technische Details" - Wenn es Hintergrundaufgaben gab (später dokumentiert), werden sie *nach* allen Middlewares ausgeführt. +Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt. + +Wenn es Hintergrundaufgaben gab (später dokumentiert), werden sie *nach* allen Middlewares ausgeführt. + +/// ## Erstellung einer Middleware @@ -32,15 +35,21 @@ Die Middleware-Funktion erhält: {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">Verwenden Sie dafür das Präfix 'X-'</a>. +/// tip | "Tipp" + +Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">Verwenden Sie dafür das Präfix 'X-'</a>. + +Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette-CORS-Dokumentation</a> dokumentiert ist. + +/// + +/// note | "Technische Details" - Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette-CORS-Dokumentation</a> dokumentiert ist. +Sie könnten auch `from starlette.requests import Request` verwenden. -!!! note "Technische Details" - Sie könnten auch `from starlette.requests import Request` verwenden. +**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette. - **FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette. +/// ### Vor und nach der `response` diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md index 80a4fadc9..03980b7dd 100644 --- a/docs/de/docs/tutorial/path-operation-configuration.md +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können. -!!! warning "Achtung" - Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. +/// warning | "Achtung" + +Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. + +/// ## Response-Statuscode @@ -13,52 +16,67 @@ Sie können direkt den `int`-Code übergeben, etwa `404`. Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt. -!!! note "Technische Details" - Sie können auch `from starlette import status` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette import status` verwenden. + +**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. +/// ## Tags Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet: @@ -80,23 +98,29 @@ In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern. Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// ## Beschreibung mittels Docstring @@ -104,23 +128,29 @@ Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der Sie können im Docstring <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// In der interaktiven Dokumentation sieht das dann so aus: @@ -130,31 +160,43 @@ In der interaktiven Dokumentation sieht das dann so aus: Die Response können Sie mit dem Parameter `response_description` beschreiben: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check -!!! info - beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht. +OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt. -!!! check - OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt. +Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen. - Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen. +/// <img src="/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md index aa3b59b8b..3908a0b2d 100644 --- a/docs/de/docs/tutorial/path-params-numeric-validations.md +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metad Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// info - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. -!!! info - FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. - Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. +Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. - Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. +/// ## Metadaten deklarieren @@ -55,53 +74,75 @@ Sie können die gleichen Parameter deklarieren wie für `Query`. Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! note "Hinweis" - Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. +/// - Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen. +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich. +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note | "Hinweis" + +Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. + +Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen. + +Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich. + +/// ## Sortieren Sie die Parameter, wie Sie möchten -!!! tip "Tipp" - Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. +/// tip | "Tipp" + +Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +/// Nehmen wir an, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren. @@ -117,33 +158,45 @@ Für **FastAPI** ist es nicht wichtig. Es erkennt die Parameter anhand ihres Nam Sie können Ihre Funktion also so deklarieren: -=== "Python 3.8 nicht annotiert" +//// tab | Python 3.8 nicht annotiert + +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` + +//// ## Sortieren Sie die Parameter wie Sie möchten: Tricks -!!! tip "Tipp" - Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. +/// tip | "Tipp" + +Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +/// Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen. @@ -168,43 +221,56 @@ Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Par Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Validierung von Zahlen: Größer oder gleich Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren. Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual). -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Validierung von Zahlen: Größer und kleiner oder gleich @@ -213,26 +279,35 @@ Das Gleiche trifft zu auf: * `gt`: `g`reater `t`han – größer als * `le`: `l`ess than or `e`qual – kleiner oder gleich -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Validierung von Zahlen: Floats, größer und kleiner @@ -244,26 +319,35 @@ Hier wird es wichtig, in der Lage zu sein, <abbr title="greater than – größe Das gleiche gilt für <abbr title="less than – kleiner als"><code>lt</code></abbr>. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Zusammenfassung @@ -276,18 +360,24 @@ Und Sie können auch Validierungen für Zahlen deklarieren: * `lt`: `l`ess `t`han – kleiner als * `le`: `l`ess than or `e`qual – kleiner oder gleich -!!! info - `Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse. +/// info + +`Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse. + +Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben. + +/// + +/// note | "Technische Details" - Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben. +`Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. -!!! note "Technische Details" - `Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. +Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben. - Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben. +Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird. - Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird. +Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt. - Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt. +Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten. - Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten. +/// diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md index 8c8f2e008..2c1b691a8 100644 --- a/docs/de/docs/tutorial/path-params.md +++ b/docs/de/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Sie können den Typ eines Pfad-Parameters in der Argumentliste der Funktion dekl In diesem Fall wird `item_id` als `int` deklariert, also als Ganzzahl. -!!! check - Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw. +/// check + +Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw. + +/// ## Daten-<abbr title="Auch bekannt als: Serialisierung, Parsen, Marshalling">Konversion</abbr> @@ -35,10 +38,13 @@ Wenn Sie dieses Beispiel ausführen und Ihren Browser unter <a href="http://127. {"item_id":3} ``` -!!! check - Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String `"3"`, also ein `str`. +/// check + +Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String `"3"`, also ein `str`. + +Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch <abbr title="Den String, der von einer HTTP Anfrage kommt, in Python-Objekte konvertieren">„parsen“</abbr>. - Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch <abbr title="Den String, der von einer HTTP Anfrage kommt, in Python-Objekte konvertieren">„parsen“</abbr>. +/// ## Datenvalidierung @@ -65,12 +71,15 @@ Der Pfad-Parameter `item_id` hatte den Wert `"foo"`, was kein `int` ist. Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! check - Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung. +/// check - Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war. +Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung. - Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert. +Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war. + +Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert. + +/// ## Dokumentation @@ -78,10 +87,13 @@ Wenn Sie die Seite <a href="http://127.0.0.1:8000/docs" class="external-link" ta <img src="/img/tutorial/path-params/image01.png"> -!!! check - Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche). +/// check + +Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche). + +Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist. - Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist. +/// ## Nützliche Standards. Alternative Dokumentation @@ -141,11 +153,17 @@ Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaub {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerationen (oder kurz Enums)</a> gibt es in Python seit Version 3.4. +/// info -!!! tip "Tipp" - Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von <abbr title="Genau genommen, Deep-Learning-Modellarchitekturen">Modellen</abbr> für maschinelles Lernen. +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerationen (oder kurz Enums)</a> gibt es in Python seit Version 3.4. + +/// + +/// tip | "Tipp" + +Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von <abbr title="Genau genommen, Deep-Learning-Modellarchitekturen">Modellen</abbr> für maschinelles Lernen. + +/// ### Deklarieren Sie einen *Pfad-Parameter* @@ -181,8 +199,11 @@ Den tatsächlichen Wert (in diesem Fall ein `str`) erhalten Sie via `model_name. {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Tipp" - Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. +/// tip | "Tipp" + +Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. + +/// #### *Enum-Member* zurückgeben @@ -235,10 +256,13 @@ Sie verwenden das also wie folgt: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Tipp" - Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. +/// tip | "Tipp" + +Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. + +In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`. - In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md index 92f2bbe7c..ab30fc6cf 100644 --- a/docs/de/docs/tutorial/query-params-str-validations.md +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ Nehmen wir als Beispiel die folgende Anwendung: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich. -!!! note "Hinweis" - FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist +/// note | "Hinweis" - `Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen. +FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist + +`Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen. + +/// ## Zusätzliche Validierung @@ -34,30 +41,37 @@ Importieren Sie zuerst: * `Query` von `fastapi` * `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ - In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. +In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` -=== "Python 3.8+" +//// - In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`. +//// tab | Python 3.8+ - Es wird bereits mit FastAPI installiert sein. +In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`. - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +Es wird bereits mit FastAPI installiert sein. -!!! info - FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. +```Python hl_lines="3-4" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. +//// - Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. +/// info + +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + +Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +/// ## `Annotated` im Typ des `q`-Parameters verwenden @@ -67,31 +81,39 @@ Jetzt ist es an der Zeit, das mit FastAPI auszuprobieren. 🚀 Wir hatten diese Typannotation: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +q: str | None = None +``` + +//// - ```Python - q: str | None = None - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +q: Union[str, None] = None +``` - ```Python - q: Union[str, None] = None - ``` +//// Wir wrappen das nun in `Annotated`, sodass daraus wird: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: Annotated[str | None] = None - ``` +```Python +q: Annotated[str | None] = None +``` -=== "Python 3.8+" +//// - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`. @@ -101,17 +123,21 @@ Wenden wir uns jetzt den spannenden Dingen zu. 🎉 Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist. @@ -127,22 +153,29 @@ FastAPI wird nun: Frühere Versionen von FastAPI (vor <abbr title="vor 2023-03">0.95.0</abbr>) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen. -!!! tip "Tipp" - Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 +/// tip | "Tipp" + +Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 + +/// So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI). @@ -172,22 +205,25 @@ q: str | None = None Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren. -!!! info - Bedenken Sie, dass: +/// info - ```Python - = None - ``` +Bedenken Sie, dass: - oder: +```Python += None +``` - ```Python - = Query(default=None) - ``` +oder: - der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht. +```Python += Query(default=None) +``` + +der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht. + +Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist. - Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist. +/// Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird: @@ -239,81 +275,113 @@ Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch Sie können auch einen Parameter `min_length` hinzufügen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +//// ## Reguläre Ausdrücke hinzufügen Sie können einen <abbr title="Ein regulärer Ausdruck, auch regex oder regexp genannt, ist eine Zeichensequenz, die ein Suchmuster für Strings definiert.">Regulären Ausdruck</abbr> `pattern` definieren, mit dem der Parameter übereinstimmen muss: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +//// Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert: @@ -331,11 +399,13 @@ Vor Pydantic Version 2 und vor FastAPI Version 0.100.0, war der Name des Paramet Sie könnten immer noch Code sehen, der den alten Namen verwendet: -=== "Python 3.10+ Pydantic v1" +//// tab | Python 3.10+ Pydantic v1 + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} - ``` +//// Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓 @@ -345,29 +415,41 @@ Sie können natürlich andere Defaultwerte als `None` verwenden. Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +/// note | "Hinweis" -!!! note "Hinweis" - Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. +Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. + +/// ## Erforderliche Parameter @@ -385,75 +467,103 @@ q: Union[str, None] = None Aber jetzt deklarieren wir den Parameter mit `Query`, wie in: -=== "Annotiert" +//// tab | Annotiert - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// -=== "Nicht annotiert" +//// tab | Nicht annotiert - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +//// Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +``` -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` +Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉 - !!! tip "Tipp" - Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. +/// - Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉 +//// ### Erforderlich mit Ellipse (`...`) Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das <abbr title='Zeichenfolge, die einen Wert direkt darstellt, etwa 1, "hallowelt", True, None'>Literal</abbr> `...` setzen: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +/// info -!!! info - Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Teil von Python und wird „Ellipsis“ genannt</a> (Deutsch: Ellipse). +Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Teil von Python und wird „Ellipsis“ genannt</a> (Deutsch: Ellipse). - Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. +Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. + +/// Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist. @@ -463,47 +573,69 @@ Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erfo Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> erfahren. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> erfahren. +Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. -!!! tip "Tipp" - Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. +/// ## Query-Parameter-Liste / Mehrere Werte @@ -511,50 +643,71 @@ Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+" +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.9+ nicht annotiert - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.10+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` -=== "Python 3.9+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +//// Dann, mit einer URL wie: @@ -575,8 +728,11 @@ Die Response für diese URL wäre also: } ``` -!!! tip "Tipp" - Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. +/// tip | "Tipp" + +Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. + +/// Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte. @@ -586,35 +742,49 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jet Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +``` + +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` +/// -=== "Python 3.9+ nicht annotiert" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` + +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +//// Wenn Sie auf: @@ -637,31 +807,43 @@ gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response e Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` +/// note | "Hinweis" -!!! note "Hinweis" - Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. +Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. - Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht. +Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht. + +/// ## Deklarieren von mehr Metadaten @@ -669,86 +851,121 @@ Sie können mehr Informationen zum Parameter hinzufügen. Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet. -!!! note "Hinweis" - Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. +/// note | "Hinweis" + +Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. - Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren. +Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren. + +/// Sie können einen Titel hinzufügen – `title`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +//// Und eine Beschreibung – `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` + +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +//// ## Alias-Parameter @@ -768,41 +985,57 @@ Aber Sie möchten dennoch exakt `item-query` verwenden. Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +//// ## Parameter als deprecated ausweisen @@ -812,41 +1045,57 @@ Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie m In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// Die Dokumentation wird das so anzeigen: @@ -856,41 +1105,57 @@ Die Dokumentation wird das so anzeigen: Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index 1b9b56bea..136852216 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ gehen, werden die Parameter-Werte Ihrer Funktion sein: Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein. -!!! check - Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein. +/// check + +Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein. + +/// ## Query-Parameter Typkonvertierung Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Wenn Sie nun zu: @@ -136,17 +147,21 @@ Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren. Parameter werden anhand ihres Namens erkannt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Erforderliche Query-Parameter @@ -204,17 +219,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// In diesem Fall gibt es drei Query-Parameter: @@ -222,5 +241,8 @@ In diesem Fall gibt es drei Query-Parameter: * `skip`, ein `int` mit einem Defaultwert `0`. * `limit`, ein optionales `int`. -!!! tip "Tipp" - Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. +/// tip | "Tipp" + +Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. + +/// diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index 67b5e3a87..cf44df5f0 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -2,70 +2,97 @@ Mit `File` können sie vom Client hochzuladende Dateien definieren. -!!! info - Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. +/// info - Z. B. `pip install python-multipart`. +Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. - Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. +Z. B. `pip install python-multipart`. + +Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. + +/// ## `File` importieren Importieren Sie `File` und `UploadFile` von `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// ## `File`-Parameter definieren Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +/// info -=== "Python 3.8+ nicht annotiert" +`File` ist eine Klasse, die direkt von `Form` erbt. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// -!!! info - `File` ist eine Klasse, die direkt von `Form` erbt. +/// tip | "Tipp" - Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben +Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. -!!! tip "Tipp" - Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. +/// Die Dateien werden als „Formulardaten“ hochgeladen. @@ -79,26 +106,35 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// `UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: @@ -141,11 +177,17 @@ Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, contents = myfile.file.read() ``` -!!! note "Technische Details zu `async`" - Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem <abbr title="Mehrere unabhängige Kindprozesse">Threadpool</abbr> aus und erwartet sie. +/// note | "Technische Details zu `async`" + +Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem <abbr title="Mehrere unabhängige Kindprozesse">Threadpool</abbr> aus und erwartet sie. + +/// + +/// note | "Technische Details zu Starlette" -!!! note "Technische Details zu Starlette" - **FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. +**FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. + +/// ## Was sind „Formulardaten“ @@ -153,82 +195,113 @@ HTML-Formulare (`<form></form>`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -!!! note "Technische Details" - Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert. +/// note | "Technische Details" + +Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert. + +Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss. + +Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>. + +/// - Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss. +/// warning | "Achtung" - Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>. +Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. -!!! warning "Achtung" - Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. - Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. +/// ## Optionaler Datei-Upload Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// ## `UploadFile` mit zusätzlichen Metadaten Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8 14" - {!> ../../../docs_src/request_files/tutorial001_03_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +//// ## Mehrere Datei-Uploads @@ -238,76 +311,107 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` -=== "Python 3.9+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.9+ nicht annotiert - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. -!!! note "Technische Details" - Sie können auch `from starlette.responses import HTMLResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import HTMLResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ### Mehrere Datei-Uploads mit zusätzlichen Metadaten Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+ nicht annotiert" +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index 86b1406e6..e109595d1 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,91 @@ Sie können gleichzeitig Dateien und Formulardaten mit `File` und `Form` definieren. -!!! info - Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. +/// info - Z. B. `pip install python-multipart`. +Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + +Z. B. `pip install python-multipart`. + +/// ## `File` und `Form` importieren -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// ## `File` und `Form`-Parameter definieren Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10-12" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="9-11" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +//// Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren. -!!! warning "Achtung" - Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. +/// warning | "Achtung" + +Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. - Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 6c029b5fe..391788aff 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden. -!!! info - Um Formulare zu verwenden, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. +/// info - Z. B. `pip install python-multipart`. +Um Formulare zu verwenden, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. + +Z. B. `pip install python-multipart`. + +/// ## `Form` importieren Importieren Sie `Form` von `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## `Form`-Parameter definieren Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt <abbr title='„Passwort-Fluss“'>„password flow“</abbr>), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. @@ -63,11 +84,17 @@ Die <abbr title="Specification – Spezifikation">Spec</abbr> erfordert, dass di Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw. -!!! info - `Form` ist eine Klasse, die direkt von `Body` erbt. +/// info + +`Form` ist eine Klasse, die direkt von `Body` erbt. + +/// + +/// tip | "Tipp" -!!! tip "Tipp" - Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. +Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. + +/// ## Über „Formularfelder“ @@ -75,17 +102,23 @@ HTML-Formulare (`<form></form>`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -!!! note "Technische Details" - Daten aus Formularen werden normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert. +/// note | "Technische Details" + +Daten aus Formularen werden normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert. + +Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien. + +Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>. + +/// - Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien. +/// warning | "Achtung" - Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>. +Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. -!!! warning "Achtung" - Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. - Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index d5b92e0f9..3f632b1cb 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ Sie können den Typ der <abbr title="Response – Antwort: Daten, die zum anfrag Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten von Funktions-**Parametern** machen; verwenden Sie Pydantic-Modelle, Listen, Dicts und skalare Werte wie Nummern, Booleans, usw. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +//// FastAPI wird diesen Rückgabetyp verwenden, um: @@ -53,35 +59,47 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: * `@app.delete()` * usw. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note "Hinweis" - Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. +//// + +/// note | "Hinweis" + +Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. + +/// `response_model` nimmt denselben Typ entgegen, den Sie auch für ein Pydantic-Modellfeld deklarieren würden, also etwa ein Pydantic-Modell, aber es kann auch z. B. eine `list`e von Pydantic-Modellen sein, wie etwa `List[Item]`. FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**. -!!! tip "Tipp" - Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als <abbr title='„Irgend etwas“'>`Any`</abbr> deklarieren. +/// tip | "Tipp" + +Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als <abbr title='„Irgend etwas“'>`Any`</abbr> deklarieren. + +So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`. - So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`. +/// ### `response_model`-Priorität @@ -95,37 +113,48 @@ Sie können auch `response_model=None` verwenden, um das Erstellen eines Respons Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. -!!! info - Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +Z. B. `pip install email-validator` +oder `pip install pydantic[email]`. - Z. B. `pip install email-validator` - oder `pip install pydantic[email]`. +/// Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. @@ -133,52 +162,67 @@ Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken. -!!! danger "Gefahr" - Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. +/// danger | "Gefahr" + +Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. + +/// ## Ausgabemodell hinzufügen Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// ... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). @@ -202,17 +246,21 @@ Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` + +//// - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. @@ -278,17 +326,21 @@ Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pyd Das gleiche wird passieren, wenn Sie eine <abbr title='Eine Union mehrerer Typen bedeutet: „Irgendeiner dieser Typen“'>Union</abbr> mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +//// ... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. @@ -300,17 +352,21 @@ Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unters In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` + +//// Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 @@ -318,23 +374,29 @@ Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und d Ihr Responsemodell könnte Defaultwerte haben, wie: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// * `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. * `tax: float = 10.5` hat einen Defaultwert `10.5`. @@ -348,23 +410,29 @@ Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Da Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. @@ -377,21 +445,30 @@ Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wir } ``` -!!! info - In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. +/// info + +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// + +/// info + +FastAPI verwendet `.dict()` von Pydantic Modellen, <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">mit dessen `exclude_unset`-Parameter</a>, um das zu erreichen. - Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. +/// -!!! info - FastAPI verwendet `.dict()` von Pydantic Modellen, <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">mit dessen `exclude_unset`-Parameter</a>, um das zu erreichen. +/// info -!!! info - Sie können auch: +Sie können auch: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - verwenden, wie in der <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic Dokumentation</a> für `exclude_defaults` und `exclude_none` beschrieben. +verwenden, wie in der <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic Dokumentation</a> für `exclude_defaults` und `exclude_none` beschrieben. + +/// #### Daten mit Werten für Felder mit Defaultwerten @@ -426,10 +503,13 @@ dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, Diese Felder werden also in der JSON-Response enthalten sein. -!!! tip "Tipp" - Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. +/// tip | "Tipp" + +Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. + +Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein. - Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein. +/// ### `response_model_include` und `response_model_exclude` @@ -439,45 +519,59 @@ Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, d Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen. -!!! tip "Tipp" - Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. +/// tip | "Tipp" - Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen. +Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. - Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. +Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen. -=== "Python 3.10+" +Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` -!!! tip "Tipp" - Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. +//// - Äquivalent zu `set(["name", "description"])`. +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` + +//// + +/// tip | "Tipp" + +Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. + +Äquivalent zu `set(["name", "description"])`. + +/// #### `list`en statt `set`s verwenden Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md index a9cc238f8..5f96b83e4 100644 --- a/docs/de/docs/tutorial/response-status-code.md +++ b/docs/de/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Hinweis" - Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. +/// note | "Hinweis" + +Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. + +/// Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben. -!!! info - Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. +/// info + +Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. + +/// Das wird: @@ -27,15 +33,21 @@ Das wird: <img src="/img/tutorial/response-status-code/image01.png"> -!!! note "Hinweis" - Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. +/// note | "Hinweis" + +Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. + +FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt. - FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt. +/// ## Über HTTP-Statuscodes -!!! note "Hinweis" - Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. +/// note | "Hinweis" + +Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +/// In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode. @@ -54,8 +66,11 @@ Kurz: * Für allgemeine Fehler beim Client können Sie einfach `400` verwenden. * `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben. -!!! tip "Tipp" - Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr> Dokumentation über HTTP-Statuscodes</a>. +/// tip | "Tipp" + +Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr> Dokumentation über HTTP-Statuscodes</a>. + +/// ## Abkürzung, um die Namen zu erinnern @@ -79,10 +94,13 @@ Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese <img src="/img/tutorial/response-status-code/image02.png"> -!!! note "Technische Details" - Sie können auch `from starlette import status` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette import status` verwenden. + +**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. +/// ## Den Defaultwert ändern diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md index e8bfc9876..07b4bb759 100644 --- a/docs/de/docs/tutorial/schema-extra-example.md +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -8,71 +8,93 @@ Hier sind mehrere Möglichkeiten, das zu tun. Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden. -=== "Python 3.10+ Pydantic v2" +//// tab | Python 3.10+ Pydantic v2 - ```Python hl_lines="13-24" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-24" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.10+ Pydantic v1" +//// - ```Python hl_lines="13-23" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} - ``` +//// tab | Python 3.10+ Pydantic v1 -=== "Python 3.8+ Pydantic v2" +```Python hl_lines="13-23" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +``` - ```Python hl_lines="15-26" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// -=== "Python 3.8+ Pydantic v1" +//// tab | Python 3.8+ Pydantic v2 - ```Python hl_lines="15-25" - {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} - ``` +```Python hl_lines="15-26" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// + +//// tab | Python 3.8+ Pydantic v1 + +```Python hl_lines="15-25" +{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +``` + +//// Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet. -=== "Pydantic v2" +//// tab | Pydantic v2 + +In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic-Dokumentation: Configuration</a>. + +Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. - In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic-Dokumentation: Configuration</a>. +//// - Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. +//// tab | Pydantic v1 -=== "Pydantic v1" +In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic-Dokumentation: Schema customization</a>. - In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic-Dokumentation: Schema customization</a>. +Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. - Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. +//// -!!! tip "Tipp" - Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. +/// tip | "Tipp" - Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen. +Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. -!!! info - OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist. +Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen. - Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr> und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓 +/// - Mehr erfahren Sie am Ende dieser Seite. +/// info + +OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist. + +Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr> und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓 + +Mehr erfahren Sie am Ende dieser Seite. + +/// ## Zusätzliche Argumente für `Field` Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// ## `examples` im JSON-Schema – OpenAPI @@ -92,41 +114,57 @@ können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen dekl Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` - ```Python hl_lines="23-30" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="23-30" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` - ```Python hl_lines="18-25" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="20-27" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="18-25" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="20-27" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### Beispiel in der Dokumentations-Benutzeroberfläche @@ -138,41 +176,57 @@ Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen: Sie können natürlich auch mehrere `examples` übergeben: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24-39" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` - ```Python hl_lines="24-39" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="19-34" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="19-34" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - ```Python hl_lines="21-36" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="21-36" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten. @@ -213,41 +267,57 @@ Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten: Sie können es so verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +``` - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial005.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +``` + +//// ### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche @@ -257,17 +327,23 @@ Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehe ## Technische Details -!!! tip "Tipp" - Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. +/// tip | "Tipp" + +Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. + +Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war. + +Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓 - Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war. +/// - Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓 +/// warning | "Achtung" -!!! warning "Achtung" - Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. +Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. - Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne. +Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne. + +/// Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**. @@ -285,8 +361,11 @@ OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Sp * `File()` * `Form()` -!!! info - Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`. +/// info + +Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`. + +/// ### JSON Schemas Feld `examples` @@ -298,10 +377,13 @@ Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdef Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben). -!!! info - Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉). +/// info + +Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉). + +Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0. - Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0. +/// ### Pydantic- und FastAPI-`examples` diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index 1e75fa8d9..6bc42cf6c 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -20,35 +20,47 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie Kopieren Sie das Beispiel in eine Datei `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// ## Ausführen -!!! info - Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. +/// info - Z. B. `pip install python-multipart`. +Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>. - Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet. +Z. B. `pip install python-multipart`. + +Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet. + +/// Führen Sie das Beispiel aus mit: @@ -70,17 +82,23 @@ Sie werden etwa Folgendes sehen: <img src="/img/tutorial/security/image01.png"> -!!! check "Authorize-Button!" - Sie haben bereits einen glänzenden, neuen „Authorize“-Button. +/// check | "Authorize-Button!" + +Sie haben bereits einen glänzenden, neuen „Authorize“-Button. - Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können. +Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können. + +/// Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder): <img src="/img/tutorial/security/image02.png"> -!!! note "Hinweis" - Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. +/// note | "Hinweis" + +Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. + +/// Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren. @@ -122,53 +140,71 @@ Betrachten wir es also aus dieser vereinfachten Sicht: In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`. -!!! info - Ein „Bearer“-Token ist nicht die einzige Option. +/// info + +Ein „Bearer“-Token ist nicht die einzige Option. + +Aber es ist die beste für unseren Anwendungsfall. - Aber es ist die beste für unseren Anwendungsfall. +Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht. - Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht. +In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen. - In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen. +/// Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="8" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="7" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="6" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -!!! tip "Tipp" - Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. +/// tip | "Tipp" - Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert. +/// + +```Python hl_lines="6" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// + +/// tip | "Tipp" + +Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. + +Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen. + +Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert. + +/// Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet. Wir werden demnächst auch die eigentliche Pfadoperation erstellen. -!!! info - Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`. +/// info + +Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`. + +Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten. - Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten. +/// Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“. @@ -184,35 +220,47 @@ Es kann also mit `Depends` verwendet werden. Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. **FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren. -!!! info "Technische Details" - **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. +/// info | "Technische Details" + +**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. + +Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss. - Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss. +/// ## Was es macht diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index 09b55a20e..8a68deeef 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -2,26 +2,35 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// Aber das ist immer noch nicht so nützlich. @@ -33,41 +42,57 @@ Erstellen wir zunächst ein Pydantic-Benutzermodell. So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 13-17" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="5 13-17" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Eine `get_current_user`-Abhängigkeit erstellen @@ -79,135 +104,189 @@ Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="26" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="26" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Den Benutzer holen `get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +```Python hl_lines="20-23 27-28" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20-23 27-28" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +/// -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Den aktuellen Benutzer einfügen Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="32" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="32" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen. -!!! tip "Tipp" - Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. +/// tip | "Tipp" - Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt. +Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. -!!! check - Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben. +Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt. - Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann. +/// + +/// check + +Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben. + +Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann. + +/// ## Andere Modelle @@ -241,41 +320,57 @@ Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwe Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="31-33" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="31-33" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md index 7a11e704d..ad0927361 100644 --- a/docs/de/docs/tutorial/security/index.md +++ b/docs/de/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Heutzutage ist es nicht sehr populär und wird kaum verwendet. OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird. -!!! tip "Tipp" - Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. +/// tip | "Tipp" +Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI definiert die folgenden Sicherheitsschemas: * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist. -!!! tip "Tipp" - Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. +/// tip | "Tipp" + +Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. + +Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird. - Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird. +/// ## **FastAPI** Tools diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 9f43cccc9..88f0dbe42 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]" Hier verwenden wir das empfohlene: <a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>. -!!! tip "Tipp" - Dieses Tutorial verwendete zuvor <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>. +/// tip | "Tipp" - Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen. +Dieses Tutorial verwendete zuvor <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>. + +Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen. + +/// ## Passwort-Hashing @@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]" </div> -!!! tip "Tipp" - Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. +/// tip | "Tipp" + +Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. - So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden. +So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden. - Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden. +Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden. + +/// ## Die Passwörter hashen und überprüfen @@ -96,12 +102,15 @@ Importieren Sie die benötigten Tools aus `passlib`. Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet. -!!! tip "Tipp" - Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. +/// tip | "Tipp" + +Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. - Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen. +Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen. - Und mit allen gleichzeitig kompatibel sein. +Und mit allen gleichzeitig kompatibel sein. + +/// Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen. @@ -109,44 +118,63 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="7 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +```Python hl_lines="6 47 54-55 58-59 68-74" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="6 47 54-55 58-59 68-74" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// note | "Hinweis" - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. -!!! note "Hinweis" - Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +/// ## JWT-Token verarbeiten @@ -176,41 +204,57 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verw Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="6 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="5 11-13 27-29 77-85" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="6 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="5 11-13 27-29 77-85" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ## Die Abhängigkeiten aktualisieren @@ -220,41 +264,57 @@ Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktue Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="88-105" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="88-105" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ## Die *Pfadoperation* `/token` aktualisieren @@ -262,41 +322,57 @@ Erstellen Sie ein <abbr title="Zeitdifferenz">`timedelta`</abbr> mit der Ablaufz Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="117-132" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// - ```Python hl_lines="117-132" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="117-132" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="117-132" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="114-129" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="114-129" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ### Technische Details zum JWT-„Subjekt“ `sub` @@ -335,8 +411,11 @@ Verwenden Sie die Anmeldeinformationen: Benutzername: `johndoe` Passwort: `secret`. -!!! check - Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version. +/// check + +Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version. + +/// <img src="/img/tutorial/security/image08.png"> @@ -357,8 +436,11 @@ Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Dat <img src="/img/tutorial/security/image10.png"> -!!! note "Hinweis" - Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. +/// note | "Hinweis" + +Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. + +/// ## Fortgeschrittene Verwendung mit `scopes` diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index ed280d486..3b1c4ae28 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu * `instagram_basic` wird von Facebook / Instagram verwendet. * `https://www.googleapis.com/auth/drive` wird von Google verwendet. -!!! info - In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. +/// info - Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. +In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. - Diese Details sind implementierungsspezifisch. +Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. - Für OAuth2 sind es einfach nur Strings. +Diese Details sind implementierungsspezifisch. + +Für OAuth2 sind es einfach nur Strings. + +/// ## Code, um `username` und `password` entgegenzunehmen. @@ -49,41 +52,57 @@ Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 79" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="4 79" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// `OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: @@ -92,29 +111,38 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A * Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings. * Einem optionalen `grant_type` („Art der Anmeldung“). -!!! tip "Tipp" - Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. +/// tip | "Tipp" + +Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. - Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`. +Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`. + +/// * Eine optionale `client_id` (benötigen wir für unser Beispiel nicht). * Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht). -!!! info - `OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`. +/// info + +`OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt. - `OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt. +Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können. - Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können. +Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt. - Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt. +/// ### Die Formulardaten verwenden -!!! tip "Tipp" - Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. +/// tip | "Tipp" + +Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. + +In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen. - In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen. +/// Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld. @@ -122,41 +150,57 @@ Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect u Für den Fehler verwenden wir die Exception `HTTPException`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 80-82" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="3 80-82" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +/// + +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// ### Das Passwort überprüfen @@ -182,41 +226,57 @@ Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="83-86" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="83-86" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// #### Über `**user_dict` @@ -234,8 +294,11 @@ UserInDB( ) ``` -!!! info - Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}. +/// info + +Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}. + +/// ## Den Token zurückgeben @@ -247,55 +310,77 @@ Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffs In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück. -!!! tip "Tipp" - Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und <abbr title="JSON Web Tokens">JWT</abbr>-Tokens. +/// tip | "Tipp" + +Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und <abbr title="JSON Web Tokens">JWT</abbr>-Tokens. + +Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen. - Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen. +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="88" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +```Python hl_lines="88" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` -!!! tip "Tipp" - Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. +//// - Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden. +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` - Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten. +//// - Den Rest erledigt **FastAPI** für Sie. +/// tip | "Tipp" + +Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. + +Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden. + +Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten. + +Den Rest erledigt **FastAPI** für Sie. + +/// ## Die Abhängigkeiten aktualisieren @@ -309,56 +394,75 @@ Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="59-67 70-75 95" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="59-67 70-75 95" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="56-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="56-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// info - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation. -!!! info - Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation. +Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben. - Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben. +Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten. - Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten. +Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren. - Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren. +Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen. - Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen. +Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein. - Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein. +Das ist der Vorteil von Standards ... - Das ist der Vorteil von Standards ... +/// ## Es in Aktion sehen diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index 1e289e120..cca8cd0ea 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Technische Details" - Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. +/// note | "Technische Details" - **FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. +Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. + +**FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +/// ### Was ist „Mounten“? diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index 541cc1bf0..43ced2aae 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -8,10 +8,13 @@ Damit können Sie <a href="https://docs.pytest.org/" class="external-link" targe ## Verwendung von `TestClient` -!!! info - Um `TestClient` zu verwenden, installieren Sie zunächst <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. +/// info - Z. B. `pip install httpx`. +Um `TestClient` zu verwenden, installieren Sie zunächst <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. + +Z. B. `pip install httpx`. + +/// Importieren Sie `TestClient`. @@ -27,20 +30,29 @@ Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. +/// tip | "Tipp" + +Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. + +Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden. + +Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. + +/// + +/// note | "Technische Details" + +Sie könnten auch `from starlette.testclient import TestClient` verwenden. - Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden. +**FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. - Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. +/// -!!! note "Technische Details" - Sie könnten auch `from starlette.testclient import TestClient` verwenden. +/// tip | "Tipp" - **FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. +Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. -!!! tip "Tipp" - Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. +/// ## Tests separieren @@ -110,41 +122,57 @@ Sie verfügt über eine `POST`-Operation, die mehrere Fehler zurückgeben könnt Beide *Pfadoperationen* erfordern einen `X-Token`-Header. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### Erweiterte Testdatei @@ -168,10 +196,13 @@ Z. B.: Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX-Dokumentation</a>. -!!! info - Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle. +/// info + +Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle. + +Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird. - Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird. +/// ## Tests ausführen diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index 26963c2e3..7a70718c5 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # 🌖 📨 🗄 -!!! warning - 👉 👍 🏧 ❔. +/// warning - 🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉. +👉 👍 🏧 ❔. + +🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉. + +/// 👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️. @@ -27,20 +30,26 @@ {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note - ✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗. +/// note + +✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗. + +/// + +/// info -!!! info - `model` 🔑 🚫 🍕 🗄. +`model` 🔑 🚫 🍕 🗄. - **FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉. +**FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉. - ☑ 🥉: +☑ 🥉: - * 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌: - * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌: - * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉. - * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️. +* 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌: + * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌: + * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉. + * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️. + +/// 🏗 📨 🗄 👉 *➡ 🛠️* 🔜: @@ -172,13 +181,19 @@ {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note - 👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗. +/// note + +👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗. + +/// + +/// info + +🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`). -!!! info - 🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`). +✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷. - ✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷. +/// ## 🌀 ℹ diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 392579df6..3f3b0aea4 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning - 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗. +/// warning - ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️. +🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗. - ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`). +⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. +⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`). - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`. +/// + +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`. + +/// ## 🗄 & 🛠️ 🩺 diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index fa1554734..22044c783 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -60,11 +60,14 @@ checker(q="somequery") {!../../../docs_src/dependencies/tutorial011.py!} ``` -!!! tip - 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠. +/// tip - 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷. +🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠. - 📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌. +👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷. - 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘. +📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌. + +🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘. + +/// diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index df94c6ce7..324b4f68a 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ $ pytest {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip - 🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`. +/// tip + +🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`. + +/// ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. @@ -81,12 +84,18 @@ response = client.get('/') ...👈 👥 ⚙️ ⚒ 👆 📨 ⏮️ `TestClient`. -!!! tip - 🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁. +/// tip + +🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁. + +/// ## 🎏 🔁 🔢 🤙 🔬 🔢 🔜 🔁, 👆 💪 🔜 🤙 (& `await`) 🎏 `async` 🔢 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 👆 💯, ⚫️❔ 👆 🔜 🤙 👫 🙆 🙆 👆 📟. -!!! tip - 🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">✳ MotorClient</a>) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲. +/// tip + +🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">✳ MotorClient</a>) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲. + +/// diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index e3fd26735..bb65e1487 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -39,8 +39,11 @@ browser --> proxy proxy --> server ``` -!!! tip - 📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽. +/// tip + +📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽. + +/// 🩺 🎚 🔜 💪 🗄 🔗 📣 👈 👉 🛠️ `server` 🔎 `/api/v1` (⛅ 🗳). 🖼: @@ -77,10 +80,13 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 ⚙️ Hypercorn, ⚫️ ✔️ 🎛 `--root-path`. -!!! note "📡 ℹ" - 🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. +/// note | "📡 ℹ" + +🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. + + & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`. - & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`. +/// ### ✅ ⏮️ `root_path` @@ -168,8 +174,11 @@ Uvicorn 🔜 ⌛ 🗳 🔐 Uvicorn `http://127.0.0.1:8000/app`, & ⤴️ ⚫ 👉 💬 Traefik 👂 🔛 ⛴ 9️⃣9️⃣9️⃣9️⃣ & ⚙️ ➕1️⃣ 📁 `routes.toml`. -!!! tip - 👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌. +/// tip + +👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌. + +/// 🔜 ✍ 👈 🎏 📁 `routes.toml`: @@ -235,8 +244,11 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip - 👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`. +/// tip + +👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`. + +/// & 🔜 📂 📛 ⏮️ ⛴ Traefik, ✅ ➡ 🔡: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>. @@ -279,8 +291,11 @@ $ uvicorn main:app --root-path /api/v1 ## 🌖 💽 -!!! warning - 👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️. +/// warning + +👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️. + +/// 🔢, **FastAPI** 🔜 ✍ `server` 🗄 🔗 ⏮️ 📛 `root_path`. @@ -319,15 +334,21 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip - 👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`. +/// tip + +👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`. + +/// 🩺 🎚 <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> ⚫️ 🔜 👀 💖: <img src="/img/tutorial/behind-a-proxy/image03.png"> -!!! tip - 🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊. +/// tip + +🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊. + +/// ### ❎ 🏧 💽 ⚪️➡️ `root_path` diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index cf76c01d0..eec87b91b 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ & 🚥 👈 `Response` ✔️ 🎻 📻 🆎 (`application/json`), 💖 💼 ⏮️ `JSONResponse` & `UJSONResponse`, 💽 👆 📨 🔜 🔁 🗜 (& ⛽) ⏮️ 🙆 Pydantic `response_model` 👈 👆 📣 *➡ 🛠️ 👨🎨*. -!!! note - 🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺. +/// note + +🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺. + +/// ## ⚙️ `ORJSONResponse` @@ -31,15 +34,21 @@ {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info - 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. +/// info + +🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. + +👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`. + + & ⚫️ 🔜 📄 ✅ 🗄. + +/// - 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`. +/// tip - & ⚫️ 🔜 📄 ✅ 🗄. +`ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃. -!!! tip - `ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃. +/// ## 🕸 📨 @@ -52,12 +61,15 @@ {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info - 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. +/// info - 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`. +🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. - & ⚫️ 🔜 📄 ✅ 🗄. +👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`. + + & ⚫️ 🔜 📄 ✅ 🗄. + +/// ### 📨 `Response` @@ -69,11 +81,17 @@ {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning - `Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺. +/// warning + +`Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺. + +/// + +/// info -!!! info - ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨. +↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨. + +/// ### 📄 🗄 & 🔐 `Response` @@ -103,10 +121,13 @@ ✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ### `Response` @@ -153,15 +174,21 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎛 🎻 📨 ⚙️ <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>. -!!! warning - `ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼. +/// warning + +`ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼. + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip - ⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛. +/// tip + +⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛. + +/// ### `RedirectResponse` @@ -222,8 +249,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🔨 ⚫️ 👉 🌌, 👥 💪 🚮 ⚫️ `with` 🍫, & 👈 🌌, 🚚 👈 ⚫️ 📪 ⏮️ 🏁. -!!! tip - 👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`. +/// tip + +👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`. + +/// ### `FileResponse` @@ -292,8 +322,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip - 👆 💪 🔐 `response_class` *➡ 🛠️* ⏭. +/// tip + +👆 💪 🔐 `response_class` *➡ 🛠️* ⏭. + +/// ## 🌖 🧾 diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index e8c4b99a2..3f49ef07c 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -20,12 +20,15 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👉 👷 🎏 🌌 ⏮️ Pydantic 🏷. & ⚫️ 🤙 🏆 🎏 🌌 🔘, ⚙️ Pydantic. -!!! info - ✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪. +/// info - , 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷. +✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪. - ✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶 +, 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷. + +✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶 + +/// ## 🎻 `response_model` diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 19421ff58..12c902c18 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -38,10 +38,13 @@ & ⤴️, ▶️️ ⏮️ `yield`, 👥 🚚 🏷. 👉 📟 🔜 🛠️ **⏮️** 🈸 **🏁 🚚 📨**, ▶️️ ⏭ *🤫*. 👉 💪, 🖼, 🚀 ℹ 💖 💾 ⚖️ 💻. -!!! tip - `shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸. +/// tip - 🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷 +`shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸. + +🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷 + +/// ### 🔆 🔢 @@ -91,10 +94,13 @@ async with lifespan(app): ## 🎛 🎉 (😢) -!!! warning - 👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛. +/// warning + +👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛. - 👆 💪 🎲 🚶 👉 🍕. +👆 💪 🎲 🚶 👉 🍕. + +/// 📤 🎛 🌌 🔬 👉 ⚛ 🛠️ ⏮️ *🕴* & ⏮️ *🤫*. @@ -126,20 +132,29 @@ async with lifespan(app): 📥, `shutdown` 🎉 🐕🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. -!!! info - `open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚. +/// info + +`open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚. + +/// + +/// tip + +👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁. + +, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾. + +✋️ `open()` 🚫 ⚙️ `async` & `await`. -!!! tip - 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁. +, 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`. - , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾. +/// - ✋️ `open()` 🚫 ⚙️ `async` & `await`. +/// info - , 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`. +👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">💃 🎉' 🩺</a>. -!!! info - 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">💃 🎉' 🩺</a>. +/// ### `startup` & `shutdown` 👯♂️ diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index 261f9fb61..c8e044340 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -16,17 +16,21 @@ ➡️ ▶️ ⏮️ 🙅 FastAPI 🈸: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +//// 👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`. @@ -111,8 +115,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app <img src="/img/tutorial/generate-clients/image03.png"> -!!! tip - 👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷. +/// tip + +👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷. + +/// 👆 🔜 ✔️ ⏸ ❌ 📊 👈 👆 📨: @@ -129,17 +136,21 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩💻**, & 👫 💪 👽 🔖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` + +//// - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// ### 🏗 📕 👩💻 ⏮️ 🔖 @@ -186,17 +197,21 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👆 💪 ⤴️ 🚶♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +//// ### 🏗 📕 👩💻 ⏮️ 🛃 🛠️ 🆔 diff --git a/docs/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md index 43bada6b4..48ef8e46d 100644 --- a/docs/em/docs/advanced/index.md +++ b/docs/em/docs/advanced/index.md @@ -6,10 +6,13 @@ ⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒. -!!! tip - ⏭ 📄 **🚫 🎯 "🏧"**. +/// tip - & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. +⏭ 📄 **🚫 🎯 "🏧"**. + + & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. + +/// ## ✍ 🔰 🥇 diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index b3e722ed0..89f494aa3 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫. -!!! note "📡 ℹ" - ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. +/// note | "📡 ℹ" - **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. +⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index 3355d6071..00d54ebec 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -35,8 +35,11 @@ {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - `callback_url` 🔢 🔢 ⚙️ Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">📛</a> 🆎. +/// tip + +`callback_url` 🔢 🔢 ⚙️ Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">📛</a> 🆎. + +/// 🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭. @@ -61,10 +64,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕. -!!! tip - ☑ ⏲ 🇺🇸🔍 📨. +/// tip + +☑ ⏲ 🇺🇸🔍 📨. - 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 <a href="https://www.python-httpx.org" class="external-link" target="_blank">🇸🇲</a> ⚖️ <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">📨</a>. +🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 <a href="https://www.python-httpx.org" class="external-link" target="_blank">🇸🇲</a> ⚖️ <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">📨</a>. + +/// ## ✍ ⏲ 🧾 📟 @@ -74,10 +80,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙). -!!! tip - 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*. +/// tip + +🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*. - 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*. +🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*. + +/// ### ✍ ⏲ `APIRouter` @@ -154,8 +163,11 @@ https://www.external.org/events/invoices/2expen51ve } ``` -!!! tip - 👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`). +/// tip + +👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`). + +/// ### 🚮 ⏲ 📻 @@ -167,8 +179,11 @@ https://www.external.org/events/invoices/2expen51ve {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - 👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`. +/// tip + +👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`. + +/// ### ✅ 🩺 diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index 3dc5ac536..b684df26f 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## 🗄 { -!!! warning - 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉. +/// warning + +🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉. + +/// 👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`. @@ -23,13 +26,19 @@ {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip - 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈. +/// tip + +🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈. + +/// + +/// warning + +🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛. -!!! warning - 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛. +🚥 👫 🎏 🕹 (🐍 📁). - 🚥 👫 🎏 🕹 (🐍 📁). +/// ## 🚫 ⚪️➡️ 🗄 @@ -65,8 +74,11 @@ 🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗. -!!! note "📡 ℹ" - 🗄 🔧 ⚫️ 🤙 <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">🛠️ 🎚</a>. +/// note | "📡 ℹ" + +🗄 🔧 ⚫️ 🤙 <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">🛠️ 🎚</a>. + +/// ⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾. @@ -74,10 +86,13 @@ 👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️. -!!! tip - 👉 🔅 🎚 ↔ ☝. +/// tip + +👉 🔅 🎚 ↔ ☝. - 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. +🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. + +/// 👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`. @@ -164,7 +179,10 @@ {!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` -!!! tip - 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷. +/// tip + +📥 👥 🏤-⚙️ 🎏 Pydantic 🏷. + +✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌. - ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌. +/// diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 23fffe1dd..717fb87ce 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -30,20 +30,26 @@ {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip - ✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗. +/// tip - , 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`. +✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗. - & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`. +, 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`. + + & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`. + +/// ### 🌅 ℹ -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. - & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. +/// 👀 🌐 💪 🔢 & 🎛, ✅ <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">🧾 💃</a>. diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index ba09734fb..13ee081c2 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 👐, 👆 💪 📨 🙆 `Response` ⚖️ 🙆 🎧-🎓 ⚫️. -!!! tip - `JSONResponse` ⚫️ 🎧-🎓 `Response`. +/// tip + +`JSONResponse` ⚫️ 🎧-🎓 `Response`. + +/// & 🕐❔ 👆 📨 `Response`, **FastAPI** 🔜 🚶♀️ ⚫️ 🔗. @@ -35,10 +38,13 @@ {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ## 🛬 🛃 `Response` diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index de798982a..27e1cdbd5 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -28,12 +28,15 @@ {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. - & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + + & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. + +/// ## 🛃 🎚 diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md index 10291338e..5cdc47505 100644 --- a/docs/em/docs/advanced/security/index.md +++ b/docs/em/docs/advanced/security/index.md @@ -4,10 +4,13 @@ 📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - ⏭ 📄 **🚫 🎯 "🏧"**. +/// tip - & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. +⏭ 📄 **🚫 🎯 "🏧"**. + + & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. + +/// ## ✍ 🔰 🥇 diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index d82fe152b..73b2ec540 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Oauth2️⃣ ⏮️ ↔ 🛠️ ⚙️ 📚 🦏 🤝 🐕🦺, 💖 👱📔 👉 📄 👆 🔜 👀 ❔ 🛠️ 🤝 & ✔ ⏮️ 🎏 Oauth2️⃣ ⏮️ ↔ 👆 **FastAPI** 🈸. -!!! warning - 👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️. +/// warning - 👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚. +👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️. - ✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺. +👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚. - 👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟. +✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺. - 📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹. +👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟. - ✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂. +📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹. + +✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂. + +/// ## Oauth2️⃣ ↔ & 🗄 @@ -43,14 +46,17 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. * `instagram_basic` ⚙️ 👱📔 / 👱📔. * `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍. -!!! info - Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. +/// info + +Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. + +⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. - ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. +👈 ℹ 🛠️ 🎯. - 👈 ℹ 🛠️ 🎯. +Oauth2️⃣ 👫 🎻. - Oauth2️⃣ 👫 🎻. +/// ## 🌐 🎑 @@ -88,10 +94,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. & 👥 📨 ↔ 🍕 🥙 🤝. -!!! danger - 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝. +/// danger - ✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. +🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝. + +✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. + +/// ```Python hl_lines="155" {!../../../docs_src/security/tutorial005.py!} @@ -113,21 +122,27 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔). -!!! note - 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉. +/// note + +👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉. - 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. +👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. + +/// ```Python hl_lines="4 139 168" {!../../../docs_src/security/tutorial005.py!} ``` -!!! info "📡 ℹ" - `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. +/// info | "📡 ℹ" + +`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. - ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄. +✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄. - ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. + +/// ## ⚙️ `SecurityScopes` @@ -216,10 +231,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. * `security_scopes.scopes` 🔜 🔌 `["me"]` *➡ 🛠️* `read_users_me`, ↩️ ⚫️ 📣 🔗 `get_current_active_user`. * `security_scopes.scopes` 🔜 🔌 `[]` (🕳) *➡ 🛠️* `read_system_status`, ↩️ ⚫️ 🚫 📣 🙆 `Security` ⏮️ `scopes`, & 🚮 🔗, `get_current_user`, 🚫 📣 🙆 `scope` 👯♂️. -!!! tip - ⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*. +/// tip + +⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*. - 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*. +🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*. + +/// ## 🌖 ℹ 🔃 `SecurityScopes` @@ -257,10 +275,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 🏆 🔐 📟 💧, ✋️ 🌖 🏗 🛠️ ⚫️ 🚚 🌅 📶. ⚫️ 🌅 🏗, 📚 🐕🦺 🔚 🆙 ✔ 🔑 💧. -!!! note - ⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷. +/// note + +⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷. + +✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩. - ✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩. +/// **FastAPI** 🔌 🚙 🌐 👫 Oauth2️⃣ 🤝 💧 `fastapi.security.oauth2`. diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index c17212023..e84941b57 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -8,44 +8,51 @@ ## 🌐 🔢 -!!! tip - 🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛. +/// tip + +🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛. + +/// <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">🌐 🔢</a> (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍). 👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆♂ 🐍: -=== "💾, 🇸🇻, 🚪 🎉" +//// tab | 💾, 🇸🇻, 🚪 🎉 + +<div class="termy"> + +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" - <div class="termy"> +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" - ```console - // You could create an env var MY_NAME with - $ export MY_NAME="Wade Wilson" +Hello Wade Wilson +``` - // Then you could use it with other programs, like - $ echo "Hello $MY_NAME" +</div> - Hello Wade Wilson - ``` +//// - </div> +//// tab | 🚪 📋 -=== "🚪 📋" +<div class="termy"> - <div class="termy"> +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Create an env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" - // Use it with other programs, like - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +</div> - </div> +//// ### ✍ 🇨🇻 {🐍 @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - 🥈 ❌ <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 🔢 💲 📨. +/// tip + +🥈 ❌ <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 🔢 💲 📨. - 🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️. +🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️. + +/// ⤴️ 👆 💪 🤙 👈 🐍 📋: @@ -114,8 +124,11 @@ Hello World from Python </div> -!!! tip - 👆 💪 ✍ 🌅 🔃 ⚫️ <a href="https://12factor.net/config" class="external-link" target="_blank">1️⃣2️⃣-⚖ 📱: 📁</a>. +/// tip + +👆 💪 ✍ 🌅 🔃 ⚫️ <a href="https://12factor.net/config" class="external-link" target="_blank">1️⃣2️⃣-⚖ 📱: 📁</a>. + +/// ### 🆎 & 🔬 @@ -139,8 +152,11 @@ Hello World from Python {!../../../docs_src/settings/tutorial001.py!} ``` -!!! tip - 🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛. +/// tip + +🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛. + +/// ⤴️, 🕐❔ 👆 ✍ 👐 👈 `Settings` 🎓 (👉 💼, `settings` 🎚), Pydantic 🔜 ✍ 🌐 🔢 💼-😛 🌌,, ↖-💼 🔢 `APP_NAME` 🔜 ✍ 🔢 `app_name`. @@ -168,8 +184,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app </div> -!!! tip - ⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋. +/// tip + +⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋. + +/// & ⤴️ `admin_email` ⚒ 🔜 ⚒ `"deadpool@example.com"`. @@ -193,8 +212,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip - 👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}. +/// tip + +👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +/// ## ⚒ 🔗 @@ -220,10 +242,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app {!../../../docs_src/settings/app02/main.py!} ``` -!!! tip - 👥 🔜 🔬 `@lru_cache` 🍖. +/// tip + +👥 🔜 🔬 `@lru_cache` 🍖. - 🔜 👆 💪 🤔 `get_settings()` 😐 🔢. +🔜 👆 💪 🤔 `get_settings()` 😐 🔢. + +/// & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. @@ -249,15 +274,21 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👉 💡 ⚠ 🥃 👈 ⚫️ ✔️ 📛, 👫 🌐 🔢 🛎 🥉 📁 `.env`, & 📁 🤙 "🇨🇻". -!!! tip - 📁 ▶️ ⏮️ ❣ (`.`) 🕵♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻. +/// tip + +📁 ▶️ ⏮️ ❣ (`.`) 🕵♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻. - ✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁. +✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁. + +/// Pydantic ✔️ 🐕🦺 👂 ⚪️➡️ 👉 🆎 📁 ⚙️ 🔢 🗃. 👆 💪 ✍ 🌖 <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic ⚒: 🇨🇻 (.🇨🇻) 🐕🦺</a>. -!!! tip - 👉 👷, 👆 💪 `pip install python-dotenv`. +/// tip + +👉 👷, 👆 💪 `pip install python-dotenv`. + +/// ### `.env` 📁 @@ -278,8 +309,11 @@ APP_NAME="ChimichangApp" 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. -!!! tip - `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic 🏷 📁</a> +/// tip + +`Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic 🏷 📁</a> + +/// ### 🏗 `Settings` 🕴 🕐 ⏮️ `lru_cache` diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 0a73a4f47..c45ff47a1 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -31,16 +31,25 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note - 👀 👈 👆 ✔️ 🚶♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*. +/// note -!!! tip - 📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸. +👀 👈 👆 ✔️ 🚶♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. +/// - **FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`. +/// tip + +📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸. + +/// + +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. + +**FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`. + +/// ## ✍ 📄 diff --git a/docs/em/docs/advanced/testing-database.md b/docs/em/docs/advanced/testing-database.md index 93acd710e..825d545a9 100644 --- a/docs/em/docs/advanced/testing-database.md +++ b/docs/em/docs/advanced/testing-database.md @@ -52,10 +52,13 @@ {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - 👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯♂️ `database.py` & `tests/test_sql_app.py`. +/// tip - 🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️. +👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯♂️ `database.py` & `tests/test_sql_app.py`. + +🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️. + +/// ## ✍ 💽 @@ -81,8 +84,11 @@ Base.metadata.create_all(bind=engine) {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - 📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️. +/// tip + +📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️. + +/// ## 💯 📱 diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 104a6325e..8bcffcc29 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -32,12 +32,15 @@ {!../../../docs_src/dependency_testing/tutorial001.py!} ``` -!!! tip - 👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸. +/// tip - ⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️. +👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸. - FastAPI 🔜 💪 🔐 ⚫️. +⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️. + +FastAPI 🔜 💪 🔐 ⚫️. + +/// ⤴️ 👆 💪 ⏲ 👆 🔐 (❎ 👫) ⚒ `app.dependency_overrides` 🛁 `dict`: @@ -45,5 +48,8 @@ app.dependency_overrides = {} ``` -!!! tip - 🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢). +/// tip + +🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢). + +/// diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 3b8e7e420..5fb1e9c34 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note - 🌅 ℹ, ✅ 💃 🧾 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">🔬 *️⃣ </a>. +/// note + +🌅 ℹ, ✅ 💃 🧾 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">🔬 *️⃣ </a>. + +/// diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index faeadb1aa..edc951d96 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -35,18 +35,24 @@ 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶♀️ `Request` 👈 🔢. -!!! tip - 🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢. +/// tip - , ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄. +🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢. - 🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁♂️. +, ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄. + +🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁♂️. + +/// ## `Request` 🧾 👆 💪 ✍ 🌅 ℹ 🔃 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request` 🎚 🛂 💃 🧾 🕸</a>. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.requests import Request`. + +**FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 6ba9b999d..30dc3043e 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -50,10 +50,13 @@ $ pip install websockets {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.websockets import WebSocket`. +/// note | "📡 ℹ" - **FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.websockets import WebSocket`. + +**FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. + +/// ## ⌛ 📧 & 📨 📧 @@ -116,10 +119,13 @@ $ uvicorn main:app --reload {!../../../docs_src/websockets/tutorial002.py!} ``` -!!! info - 👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`. +/// info + +👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`. + +👆 💪 ⚙️ 📪 📟 ⚪️➡️ <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">☑ 📟 🔬 🔧</a>. - 👆 💪 ⚙️ 📪 📟 ⚪️➡️ <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">☑ 📟 🔬 🔧</a>. +/// ### 🔄 *️⃣ ⏮️ 🔗 @@ -142,8 +148,11 @@ $ uvicorn main:app --reload * "🏬 🆔", ⚙️ ➡. * "🤝" ⚙️ 🔢 🔢. -!!! tip - 👀 👈 🔢 `token` 🔜 🍵 🔗. +/// tip + +👀 👈 🔢 `token` 🔜 🍵 🔗. + +/// ⏮️ 👈 👆 💪 🔗 *️⃣ & ⤴️ 📨 & 📨 📧: @@ -169,12 +178,15 @@ $ uvicorn main:app --reload Client #1596980209979 left the chat ``` -!!! tip - 📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗. +/// tip + +📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗. + +✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️. - ✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️. +🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕🦺 ✳, ✳ ⚖️ 🎏, ✅ <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">🗜/📻</a>. - 🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕🦺 ✳, ✳ ⚖️ 🎏, ✅ <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">🗜/📻</a>. +/// ## 🌅 ℹ diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 5890b3b13..334c0de73 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -30,12 +30,17 @@ ⚫️ 🕐 🥇 🖼 **🏧 🛠️ 🧾**, & 👉 🎯 🕐 🥇 💭 👈 😮 "🔎" **FastAPI**. -!!! note - ✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️. +/// note +✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️. -!!! check "😮 **FastAPI** " - ✔️ 🏧 🛠️ 🧾 🕸 👩💻 🔢. +/// + +/// check | "😮 **FastAPI** " + +✔️ 🏧 🛠️ 🧾 🕸 👩💻 🔢. + +/// ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">🏺</a> @@ -51,11 +56,13 @@ 👐 🦁 🏺, ⚫️ 😑 💖 👍 🏏 🏗 🔗. ⏭ 👜 🔎 "✳ 🎂 🛠️" 🏺. -!!! check "😮 **FastAPI** " - ◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. +/// check | "😮 **FastAPI** " - ✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️. +◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. +✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️. + +/// ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">📨</a> @@ -91,11 +98,13 @@ def read_url(): 👀 🔀 `requests.get(...)` & `@app.get(...)`. -!!! check "😮 **FastAPI** " - * ✔️ 🙅 & 🏋️ 🛠️. - * ⚙️ 🇺🇸🔍 👩🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. - * ✔️ 🤔 🔢, ✋️ 🏋️ 🛃. +/// check | "😮 **FastAPI** " + +* ✔️ 🙅 & 🏋️ 🛠️. +* ⚙️ 🇺🇸🔍 👩🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. +* ✔️ 🤔 🔢, ✋️ 🏋️ 🛃. +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">🦁</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">🗄</a> @@ -109,15 +118,18 @@ def read_url(): 👈 ⚫️❔ 🕐❔ 💬 🔃 ⏬ 2️⃣.0️⃣ ⚫️ ⚠ 💬 "🦁", & ⏬ 3️⃣ ➕ "🗄". -!!! check "😮 **FastAPI** " - 🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. +/// check | "😮 **FastAPI** " + +🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. - & 🛠️ 🐩-⚓️ 👩💻 🔢 🧰: + & 🛠️ 🐩-⚓️ 👩💻 🔢 🧰: - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">🦁 🎚</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">📄</a> +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">🦁 🎚</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">📄</a> - 👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**). +👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**). + +/// ### 🏺 🎂 🛠️ @@ -135,8 +147,11 @@ def read_url(): ✋️ ⚫️ ✍ ⏭ 📤 🔀 🐍 🆎 🔑. , 🔬 🔠 <abbr title="the definition of how data should be formed">🔗</abbr> 👆 💪 ⚙️ 🎯 🇨🇻 & 🎓 🚚 🍭. -!!! check "😮 **FastAPI** " - ⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. +/// check | "😮 **FastAPI** " + +⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webarg</a> @@ -148,11 +163,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ 👑 🧰 & 👤 ✔️ ⚙️ ⚫️ 📚 💁♂️, ⏭ ✔️ **FastAPI**. -!!! info - Webarg ✍ 🎏 🍭 👩💻. +/// info + +Webarg ✍ 🎏 🍭 👩💻. + +/// + +/// check | "😮 **FastAPI** " -!!! check "😮 **FastAPI** " - ✔️ 🏧 🔬 📨 📨 💽. +✔️ 🏧 🔬 📨 📨 💽. + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -172,12 +193,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 👨🎨 💪 🚫 ℹ 🌅 ⏮️ 👈. & 🚥 👥 🔀 🔢 ⚖️ 🍭 🔗 & 💭 🔀 👈 📁#️⃣, 🏗 🔗 🔜 ❌. -!!! info - APISpec ✍ 🎏 🍭 👩💻. +/// info + +APISpec ✍ 🎏 🍭 👩💻. + +/// +/// check | "😮 **FastAPI** " -!!! check "😮 **FastAPI** " - 🐕🦺 📂 🐩 🛠️, 🗄. +🐕🦺 📂 🐩 🛠️, 🗄. + +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">🏺-Apispec</a> @@ -199,11 +225,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. & 👫 🎏 🌕-📚 🚂 🧢 [**FastAPI** 🏗 🚂](project-generation.md){.internal-link target=_blank}. -!!! info - 🏺-Apispec ✍ 🎏 🍭 👩💻. +/// info + +🏺-Apispec ✍ 🎏 🍭 👩💻. + +/// -!!! check "😮 **FastAPI** " - 🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. +/// check | "😮 **FastAPI** " + +🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (& <a href="https://angular.io/" class="external-link" target="_blank">📐</a>) @@ -219,24 +251,33 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ 💪 🚫 🍵 🔁 🏷 📶 👍. , 🚥 🎻 💪 📨 🎻 🎚 👈 ✔️ 🔘 🏑 👈 🔄 🐦 🎻 🎚, ⚫️ 🚫🔜 ☑ 📄 & ✔. -!!! check "😮 **FastAPI** " - ⚙️ 🐍 🆎 ✔️ 👑 👨🎨 🐕🦺. +/// check | "😮 **FastAPI** " + +⚙️ 🐍 🆎 ✔️ 👑 👨🎨 🐕🦺. - ✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁. +✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁. + +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">🤣</a> ⚫️ 🕐 🥇 📶 ⏩ 🐍 🛠️ ⚓️ 🔛 `asyncio`. ⚫️ ⚒ 📶 🎏 🏺. -!!! note "📡 ℹ" - ⚫️ ⚙️ <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. +/// note | "📡 ℹ" + +⚫️ ⚙️ <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. - ⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇. +⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇. -!!! check "😮 **FastAPI** " - 🔎 🌌 ✔️ 😜 🎭. +/// - 👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇). +/// check | "😮 **FastAPI** " + +🔎 🌌 ✔️ 😜 🎭. + +👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇). + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">🦅</a> @@ -246,12 +287,15 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. , 💽 🔬, 🛠️, & 🧾, ✔️ ⌛ 📟, 🚫 🔁. ⚖️ 👫 ✔️ 🛠️ 🛠️ 🔛 🔝 🦅, 💖 🤗. 👉 🎏 🔺 🔨 🎏 🛠️ 👈 😮 🦅 🔧, ✔️ 1️⃣ 📨 🎚 & 1️⃣ 📨 🎚 🔢. -!!! check "😮 **FastAPI** " - 🔎 🌌 🤚 👑 🎭. +/// check | "😮 **FastAPI** " - ⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢. +🔎 🌌 🤚 👑 🎭. - 👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟. +⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢. + +👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟. + +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">♨</a> @@ -269,10 +313,13 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 🛣 📣 👁 🥉, ⚙️ 🔢 📣 🎏 🥉 (↩️ ⚙️ 👨🎨 👈 💪 🥉 ▶️️ 🔛 🔝 🔢 👈 🍵 🔗). 👉 🔐 ❔ ✳ 🔨 ⚫️ 🌘 ❔ 🏺 (& 💃) 🔨 ⚫️. ⚫️ 🎏 📟 👜 👈 📶 😆 🔗. -!!! check "😮 **FastAPI** " - 🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨🎨 🐕🦺, & ⚫️ 🚫 💪 Pydantic ⏭. +/// check | "😮 **FastAPI** " + +🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨🎨 🐕🦺, & ⚫️ 🚫 💪 Pydantic ⏭. - 👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic). +👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic). + +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">🤗</a> @@ -288,15 +335,21 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ ⚓️ 🔛 ⏮️ 🐩 🔁 🐍 🕸 🛠️ (🇨🇻), ⚫️ 💪 🚫 🍵 *️⃣ & 🎏 👜, 👐 ⚫️ ✔️ ↕ 🎭 💁♂️. -!!! info - 🤗 ✍ ✡ 🗄, 🎏 👼 <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, 👑 🧰 🔁 😇 🗄 🐍 📁. +/// info + +🤗 ✍ ✡ 🗄, 🎏 👼 <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, 👑 🧰 🔁 😇 🗄 🐍 📁. + +/// -!!! check "💭 😮 **FastAPI**" - 🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. +/// check | "💭 😮 **FastAPI**" - 🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁. +🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. - 🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪. +🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁. + +🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪. + +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0️⃣.5️⃣) @@ -322,23 +375,29 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 🔜 APIStar ⚒ 🧰 ✔ 🗄 🔧, 🚫 🕸 🛠️. -!!! info - APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: +/// info + +APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: - * ✳ 🎂 🛠️ - * 💃 (❔ **FastAPI** ⚓️) - * Uvicorn (⚙️ 💃 & **FastAPI**) +* ✳ 🎂 🛠️ +* 💃 (❔ **FastAPI** ⚓️) +* Uvicorn (⚙️ 💃 & **FastAPI**) -!!! check "😮 **FastAPI** " - 🔀. +/// - 💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨🎨 🐕🦺, 🕳 👤 🤔 💎 💭. +/// check | "😮 **FastAPI** " - & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪. +🔀. - ⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**. +💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨🎨 🐕🦺, 🕳 👤 🤔 💎 💭. - 👤 🤔 **FastAPI** "🛐 👨💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰. + & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪. + +⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**. + +👤 🤔 **FastAPI** "🛐 👨💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰. + +/// ## ⚙️ **FastAPI** @@ -350,10 +409,13 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 ⚫️ ⭐ 🍭. 👐 ⚫️ ⏩ 🌘 🍭 📇. & ⚫️ ⚓️ 🔛 🎏 🐍 🆎 🔑, 👨🎨 🐕🦺 👑. -!!! check "**FastAPI** ⚙️ ⚫️" - 🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). +/// check | "**FastAPI** ⚙️ ⚫️" - **FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨. +🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). + +**FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨. + +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">💃</a> @@ -382,17 +444,23 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 👈 1️⃣ 👑 👜 👈 **FastAPI** 🚮 🔛 🔝, 🌐 ⚓️ 🔛 🐍 🆎 🔑 (⚙️ Pydantic). 👈, ➕ 🔗 💉 ⚙️, 💂♂ 🚙, 🗄 🔗 ⚡, ♒️. -!!! note "📡 ℹ" - 🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. +/// note | "📡 ℹ" + +🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. - 👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`. +👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`. -!!! check "**FastAPI** ⚙️ ⚫️" - 🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. +/// - 🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`. +/// check | "**FastAPI** ⚙️ ⚫️" - , 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊. +🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. + +🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`. + +, 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -402,12 +470,15 @@ Uvicorn 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. ⚫️ 👍 💽 💃 & **FastAPI**. -!!! check "**FastAPI** 👍 ⚫️" - 👑 🕸 💽 🏃 **FastAPI** 🈸. +/// check | "**FastAPI** 👍 ⚫️" + +👑 🕸 💽 🏃 **FastAPI** 🈸. + +👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽. - 👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽. +✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄. - ✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄. +/// ## 📇 & 🚅 diff --git a/docs/em/docs/async.md b/docs/em/docs/async.md index 0db497f40..ac9804f64 100644 --- a/docs/em/docs/async.md +++ b/docs/em/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - 👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`. +/// note + +👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`. + +/// --- @@ -136,8 +139,11 @@ def results(): <img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration"> -!!! info - 🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶 +/// info + +🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶 + +/// --- @@ -199,8 +205,11 @@ def results(): 📤 🚫 🌅 💬 ⚖️ 😏 🌅 🕰 💸 ⌛ 👶 🚪 ⏲. 👶 -!!! info - 🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶 +/// info + +🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶 + +/// --- @@ -392,12 +401,15 @@ async def read_burgers(): ## 📶 📡 ℹ -!!! warning - 👆 💪 🎲 🚶 👉. +/// warning + +👆 💪 🎲 🚶 👉. + +👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘. - 👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘. +🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️. - 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️. +/// ### ➡ 🛠️ 🔢 diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md index 08561d8f8..3ac1afda4 100644 --- a/docs/em/docs/contributing.md +++ b/docs/em/docs/contributing.md @@ -24,63 +24,73 @@ $ python -m venv env 🔓 🆕 🌐 ⏮️: -=== "💾, 🇸🇻" +//// tab | 💾, 🇸🇻 - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` - </div> +</div> -=== "🚪 📋" +//// - <div class="termy"> +//// tab | 🚪 📋 - ```console - $ .\env\Scripts\Activate.ps1 - ``` +<div class="termy"> - </div> +```console +$ .\env\Scripts\Activate.ps1 +``` -=== "🚪 🎉" +</div> - ⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ <a href="https://gitforwindows.org/" class="external-link" target="_blank">🐛 🎉</a>): +//// - <div class="termy"> +//// tab | 🚪 🎉 - ```console - $ source ./env/Scripts/activate - ``` +⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ <a href="https://gitforwindows.org/" class="external-link" target="_blank">🐛 🎉</a>): - </div> +<div class="termy"> + +```console +$ source ./env/Scripts/activate +``` + +</div> + +//// ✅ ⚫️ 👷, ⚙️: -=== "💾, 🇸🇻, 🚪 🎉" +//// tab | 💾, 🇸🇻, 🚪 🎉 - <div class="termy"> +<div class="termy"> - ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` - </div> +</div> -=== "🚪 📋" +//// - <div class="termy"> +//// tab | 🚪 📋 - ```console - $ Get-Command pip +<div class="termy"> - some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip - </div> +some/directory/fastapi/env/bin/pip +``` + +</div> + +//// 🚥 ⚫️ 🎦 `pip` 💱 `env/bin/pip` ⤴️ ⚫️ 👷. 👶 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip </div> -!!! tip - 🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄. +/// tip + +🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄. - 👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐. +👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐. + +/// ### 🐖 @@ -149,8 +162,11 @@ $ bash scripts/format.sh & 📤 ➕ 🧰/✍ 🥉 🍵 ✍ `./scripts/docs.py`. -!!! tip - 👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸. +/// tip + +👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸. + +/// 🌐 🧾 ✍ 📁 📁 `./docs/en/`. @@ -235,10 +251,13 @@ Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. * ✅ ⏳ <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">♻ 🚲 📨</a> 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫. -!!! tip - 👆 💪 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">🚮 🏤 ⏮️ 🔀 🔑</a> ♻ 🚲 📨. +/// tip + +👆 💪 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">🚮 🏤 ⏮️ 🔀 🔑</a> ♻ 🚲 📨. + +✅ 🩺 🔃 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">❎ 🚲 📨 📄</a> ✔ ⚫️ ⚖️ 📨 🔀. - ✅ 🩺 🔃 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">❎ 🚲 📨 📄</a> ✔ ⚫️ ⚖️ 📨 🔀. +/// * ✅ <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">❔</a> 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸. @@ -260,8 +279,11 @@ Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. 💼 🇪🇸, 2️⃣-🔤 📟 `es`. , 📁 🇪🇸 ✍ 🔎 `docs/es/`. -!!! tip - 👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`. +/// tip + +👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`. + +/// 🔜 🏃 🖖 💽 🩺 🇪🇸: @@ -298,8 +320,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - 👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`. +/// tip + +👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`. + +/// * 🔜 📂 ⬜ 📁 📁 🇪🇸: @@ -370,10 +395,13 @@ Updating en 🔜 👆 💪 ✅ 👆 📟 👨🎨 ⏳ ✍ 📁 `docs/ht/`. -!!! tip - ✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍. +/// tip + +✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍. + +👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶 - 👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶 +/// ▶️ ✍ 👑 📃, `docs/ht/index.md`. diff --git a/docs/em/docs/deployment/concepts.md b/docs/em/docs/deployment/concepts.md index b0f86cb5e..019703296 100644 --- a/docs/em/docs/deployment/concepts.md +++ b/docs/em/docs/deployment/concepts.md @@ -151,10 +151,13 @@ ✋️ 👈 💼 ⏮️ 🤙 👎 ❌ 👈 💥 🏃♂ **🛠️**, 👆 🔜 💚 🔢 🦲 👈 🈚 **🔁** 🛠️, 🌘 👩❤👨 🕰... -!!! tip - ...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️. +/// tip - ➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️. +...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️. + +➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️. + +/// 👆 🔜 🎲 💚 ✔️ 👜 🈚 🔁 👆 🈸 **🔢 🦲**, ↩️ 👈 ☝, 🎏 🈸 ⏮️ Uvicorn & 🐍 ⏪ 💥, 📤 🕳 🎏 📟 🎏 📱 👈 💪 🕳 🔃 ⚫️. @@ -238,10 +241,13 @@ * **☁ 🐕🦺** 👈 🍵 👉 👆 * ☁ 🐕🦺 🔜 🎲 **🍵 🧬 👆**. ⚫️ 🔜 🎲 ➡️ 👆 🔬 **🛠️ 🏃**, ⚖️ **📦 🖼** ⚙️, 🙆 💼, ⚫️ 🔜 🌅 🎲 **👁 Uvicorn 🛠️**, & ☁ 🐕🦺 🔜 🈚 🔁 ⚫️. -!!! tip - 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. +/// tip + +🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. + +👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. - 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. +/// ## ⏮️ 🔁 ⏭ ▶️ @@ -257,10 +263,13 @@ ↗️, 📤 💼 🌐❔ 📤 🙅♂ ⚠ 🏃 ⏮️ 🔁 💗 🕰, 👈 💼, ⚫️ 📚 ⏩ 🍵. -!!! tip - , ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸. +/// tip - 👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷 +, ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸. + +👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷 + +/// ### 🖼 ⏮️ 🔁 🎛 @@ -272,8 +281,11 @@ * 🎉 ✍ 👈 🏃 ⏮️ 🔁 & ⤴️ ▶️ 👆 🈸 * 👆 🔜 💪 🌌 ▶️/⏏ *👈* 🎉 ✍, 🔍 ❌, ♒️. -!!! tip - 👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. +/// tip + +👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. + +/// ## ℹ 🛠️ diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md index 091eb3bab..6540761ac 100644 --- a/docs/em/docs/deployment/docker.md +++ b/docs/em/docs/deployment/docker.md @@ -4,8 +4,11 @@ ⚙️ 💾 📦 ✔️ 📚 📈 ✅ **💂♂**, **🔬**, **🦁**, & 🎏. -!!! tip - 🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi). +/// tip + +🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi). + +/// <details> <summary>📁 🎮 👶</summary> @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn </div> -!!! info - 📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗. +/// info + +📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗. - 👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶 +👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶 + +/// ### ✍ **FastAPI** 📟 @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] ↩️ 📋 🔜 ▶️ `/code` & 🔘 ⚫️ 📁 `./app` ⏮️ 👆 📟, **Uvicorn** 🔜 💪 👀 & **🗄** `app` ⚪️➡️ `app.main`. -!!! tip - 📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶 +/// tip + +📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶 + +/// 👆 🔜 🔜 ✔️ 📁 📊 💖: @@ -293,10 +302,13 @@ $ docker build -t myimage . </div> -!!! tip - 👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼. +/// tip + +👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼. + +👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`). - 👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`). +/// ### ▶️ ☁ 📦 @@ -394,8 +406,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ⚫️ 💪 ➕1️⃣ 📦, 🖼 ⏮️ <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, 🚚 **🇺🇸🔍** & **🏧** 🛠️ **📄**. -!!! tip - Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. +/// tip + +Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. + +/// 👐, 🇺🇸🔍 💪 🍵 ☁ 🐕🦺 1️⃣ 👫 🐕🦺 (⏪ 🏃 🈸 📦). @@ -423,8 +438,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 👉 🦲 🔜 ✊ **📐** 📨 & 📎 👈 👪 👨🏭 (🤞) **⚖** 🌌, ⚫️ 🛎 🤙 **📐 ⚙**. -!!! tip - 🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**. +/// tip + +🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**. + +/// & 🕐❔ 👷 ⏮️ 📦, 🎏 ⚙️ 👆 ⚙️ ▶️ & 🛠️ 👫 🔜 ⏪ ✔️ 🔗 🧰 📶 **🕸 📻** (✅ 🇺🇸🔍 📨) ⚪️➡️ 👈 **📐 ⚙** (👈 💪 **🤝 ❎ 🗳**) 📦(Ⓜ) ⏮️ 👆 📱. @@ -503,8 +521,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 🚥 👆 ✔️ **💗 📦**, 🎲 🔠 1️⃣ 🏃 **👁 🛠️** (🖼, **Kubernetes** 🌑), ⤴️ 👆 🔜 🎲 💚 ✔️ **🎏 📦** 🔨 👷 **⏮️ 📶** 👁 📦, 🏃 👁 🛠️, **⏭** 🏃 🔁 👨🏭 📦. -!!! info - 🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">🕑 📦</a>. +/// info + +🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">🕑 📦</a>. + +/// 🚥 👆 ⚙️ 💼 📤 🙅♂ ⚠ 🏃♂ 👈 ⏮️ 📶 **💗 🕰 🔗** (🖼 🚥 👆 🚫 🏃 💽 🛠️, ✋️ ✅ 🚥 💽 🔜), ⤴️ 👆 💪 🚮 👫 🔠 📦 ▶️️ ⏭ ▶️ 👑 🛠️. @@ -520,8 +541,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-🐁-fastapi</a>. -!!! warning - 📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi). +/// warning + +📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi). + +/// 👉 🖼 ✔️ **🚘-📳** 🛠️ 🔌 ⚒ **🔢 👨🏭 🛠️** ⚓️ 🔛 💽 🐚 💪. @@ -529,8 +553,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ⚫️ 🐕🦺 🏃 <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**⏮️ 🔁 ⏭ ▶️**</a> ⏮️ ✍. -!!! tip - 👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">Tiangolo/uvicorn-🐁-fastapi</a>. +/// tip + +👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">Tiangolo/uvicorn-🐁-fastapi</a>. + +/// ### 🔢 🛠️ 🔛 🛂 ☁ 🖼 @@ -657,8 +684,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 1️⃣1️⃣. 🏃 `uvicorn` 📋, 💬 ⚫️ ⚙️ `app` 🎚 🗄 ⚪️➡️ `app.main`. -!!! tip - 🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨. +/// tip + +🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨. + +/// **☁ ▶️** 🍕 `Dockerfile` 👈 👷 **🍕 📦 🖼** 👈 🕴 ⚙️ 🏗 📁 ⚙️ ⏪. diff --git a/docs/em/docs/deployment/https.md b/docs/em/docs/deployment/https.md index 3feb3a2c2..31cf99001 100644 --- a/docs/em/docs/deployment/https.md +++ b/docs/em/docs/deployment/https.md @@ -4,8 +4,11 @@ ✋️ ⚫️ 🌌 🌖 🏗 🌘 👈. -!!! tip - 🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒. +/// tip + +🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒. + +/// **💡 🔰 🇺🇸🔍**, ⚪️➡️ 🏬 🤔, ✅ <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>. @@ -68,8 +71,11 @@ 👆 🔜 🎲 👉 🕐, 🥇 🕰, 🕐❔ ⚒ 🌐 🆙. -!!! tip - 👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥. +/// tip + +👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥. + +/// ### 🏓 @@ -115,8 +121,11 @@ & 👈 ⚫️❔ **🇺🇸🔍** , ⚫️ ✅ **🇺🇸🔍** 🔘 **🔐 🤝 🔗** ↩️ 😁 (💽) 🕸 🔗. -!!! tip - 👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚. +/// tip + +👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚. + +/// ### 🇺🇸🔍 📨 diff --git a/docs/em/docs/deployment/manually.md b/docs/em/docs/deployment/manually.md index 43cbc9409..8ebe00c7c 100644 --- a/docs/em/docs/deployment/manually.md +++ b/docs/em/docs/deployment/manually.md @@ -22,75 +22,89 @@ 👆 💪 ❎ 🔫 🔗 💽 ⏮️: -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. - <div class="termy"> +<div class="termy"> + +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +</div> - ---> 100% - ``` +/// tip - </div> +❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗. - !!! tip - ❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗. +👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈. - 👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈. +/// -=== "Hypercorn" +//// - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. +//// tab | Hypercorn - <div class="termy"> +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. - ```console - $ pip install hypercorn +<div class="termy"> + +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +</div> - </div> +...⚖️ 🙆 🎏 🔫 💽. - ...⚖️ 🙆 🎏 🔫 💽. +//// ## 🏃 💽 📋 👆 💪 ⤴️ 🏃 👆 🈸 🎏 🌌 👆 ✔️ ⌛ 🔰, ✋️ 🍵 `--reload` 🎛, ✅: -=== "Uvicorn" +//// tab | Uvicorn - <div class="termy"> +<div class="termy"> - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - </div> +</div> + +//// -=== "Hypercorn" +//// tab | Hypercorn - <div class="termy"> +<div class="termy"> + +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +</div> - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning - </div> +💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️. -!!! warning - 💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️. + `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️. - `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️. +⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**. - ⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**. +/// ## Hypercorn ⏮️ 🎻 diff --git a/docs/em/docs/deployment/server-workers.md b/docs/em/docs/deployment/server-workers.md index 43998bc49..eb29b2376 100644 --- a/docs/em/docs/deployment/server-workers.md +++ b/docs/em/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ 📥 👤 🔜 🎦 👆 ❔ ⚙️ <a href="https://gunicorn.org/" class="external-link" target="_blank">**🐁**</a> ⏮️ **Uvicorn 👨🏭 🛠️**. -!!! info - 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. +/// info - 🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. +🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. + +🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. + +/// ## 🐁 ⏮️ Uvicorn 👨🏭 diff --git a/docs/em/docs/deployment/versions.md b/docs/em/docs/deployment/versions.md index 8bfdf9731..6c9b8f9bb 100644 --- a/docs/em/docs/deployment/versions.md +++ b/docs/em/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI ⏩ 🏛 👈 🙆 "🐛" ⏬ 🔀 🐛 🔧 & 🚫-💔 🔀. -!!! tip - "🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`. +/// tip + +"🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`. + +/// , 👆 🔜 💪 📌 ⏬ 💖: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 💔 🔀 & 🆕 ⚒ 🚮 "🇺🇲" ⏬. -!!! tip - "🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`. +/// tip + +"🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`. + +/// ## ♻ FastAPI ⏬ diff --git a/docs/em/docs/external-links.md b/docs/em/docs/external-links.md index 08db2d4c1..486b134d4 100644 --- a/docs/em/docs/external-links.md +++ b/docs/em/docs/external-links.md @@ -6,8 +6,11 @@ 📥 ❌ 📇 👫. -!!! tip - 🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>. +/// tip + +🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>. + +/// ## 📄 diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index 3693f4c54..13cafa72f 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` ⛓: +/// info - 🚶♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` ⛓: + +🚶♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 👨🎨 🐕🦺 diff --git a/docs/em/docs/help-fastapi.md b/docs/em/docs/help-fastapi.md index 4a285062d..099485222 100644 --- a/docs/em/docs/help-fastapi.md +++ b/docs/em/docs/help-fastapi.md @@ -170,12 +170,15 @@ * ⤴️ **🏤** 💬 👈 👆 👈, 👈 ❔ 👤 🔜 💭 👆 🤙 ✅ ⚫️. -!!! info - 👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔. +/// info - 📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶 +👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔. - , ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶 +📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶 + +, ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶 + +/// * 🚥 🇵🇷 💪 📉 🌌, 👆 💪 💭 👈, ✋️ 📤 🙅♂ 💪 💁♂️ 😟, 📤 5️⃣📆 📚 🤔 ☝ 🎑 (& 👤 🔜 ✔️ 👇 👍 👍 👶), ⚫️ 👻 🚥 👆 💪 🎯 🔛 ⚛ 👜. @@ -226,10 +229,13 @@ 🛑 👶 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">😧 💬 💽</a> 👶 & 🤙 👅 ⏮️ 🎏 FastAPI 👪. -!!! tip - ❔, 💭 👫 <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. +/// tip + +❔, 💭 👫 <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. + +⚙️ 💬 🕴 🎏 🏢 💬. - ⚙️ 💬 🕴 🎏 🏢 💬. +/// ### 🚫 ⚙️ 💬 ❔ diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index 2d33d4feb..1f66c6eda 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ 🖼, 🚥 👆 💚 ✍ ⚖️ 🔬 📨 💪 ⏭ ⚫️ 🛠️ 👆 🈸. -!!! danger - 👉 "🏧" ⚒. +/// danger - 🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄. +👉 "🏧" ⚒. + +🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄. + +/// ## ⚙️ 💼 @@ -27,8 +30,11 @@ ### ✍ 🛃 `GzipRequest` 🎓 -!!! tip - 👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. +/// tip + +👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. + +/// 🥇, 👥 ✍ `GzipRequest` 🎓, ❔ 🔜 📁 `Request.body()` 👩🔬 🗜 💪 🔍 ☑ 🎚. @@ -54,16 +60,19 @@ {!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` -!!! note "📡 ℹ" - `Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. +/// note | "📡 ℹ" - `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨. +`Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. - `scope` `dict` & `receive` 🔢 👯♂️ 🍕 🔫 🔧. + `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨. - & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐. + `scope` `dict` & `receive` 🔢 👯♂️ 🍕 🔫 🔧. - 💡 🌅 🔃 `Request` ✅ <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">💃 🩺 🔃 📨</a>. + & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐. + +💡 🌅 🔃 `Request` ✅ <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">💃 🩺 🔃 📨</a>. + +/// 🕴 👜 🔢 📨 `GzipRequest.get_route_handler` 🔨 🎏 🗜 `Request` `GzipRequest`. @@ -75,10 +84,13 @@ ## 🔐 📨 💪 ⚠ 🐕🦺 -!!! tip - ❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}). +/// tip + +❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}). + +✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲. - ✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲. +/// 👥 💪 ⚙️ 👉 🎏 🎯 🔐 📨 💪 ⚠ 🐕🦺. diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index 6b3bc0075..dc9adf80e 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -1,11 +1,14 @@ # ↔ 🗄 -!!! warning - 👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. +/// warning - 🚥 👆 📄 🔰 - 👩💻 🦮, 👆 💪 🎲 🚶 👉 📄. +👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. - 🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. +🚥 👆 📄 🔰 - 👩💻 🦮, 👆 💪 🎲 🚶 👉 📄. + +🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. + +/// 📤 💼 🌐❔ 👆 💪 💪 🔀 🏗 🗄 🔗. diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 686a77949..b8610b767 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -4,12 +4,15 @@ 👆 💪 🌀 😐 FastAPI *➡ 🛠️* ⏮️ 🕹 🔛 🎏 🈸. -!!! tip - **🕹** ❎ 📶 🎯 ⚙️ 💼. +/// tip - ⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**. +**🕹** ❎ 📶 🎯 ⚙️ 💼. - ⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶 +⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**. + +⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶 + +/// ## 🕹 🗃 @@ -46,8 +49,11 @@ ⚫️ 😢 ⚪️➡️ 💃, ✋️ 🚥 👆 ✔️ 📟 👈 ⚙️ ⚫️, 👆 💪 💪 **↔** <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">💃-Graphene3️⃣</a>, 👈 📔 🎏 ⚙️ 💼 & ✔️ **🌖 🌓 🔢**. -!!! tip - 🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 <a href="https://strawberry.rocks/" class="external-link" target="_blank">🍓</a>, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎. +/// tip + +🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 <a href="https://strawberry.rocks/" class="external-link" target="_blank">🍓</a>, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎. + +/// ## 💡 🌅 diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md index 8d633d7f6..88b827c24 100644 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ b/docs/em/docs/how-to/sql-databases-peewee.md @@ -1,16 +1,22 @@ # 🗄 (🔗) 💽 ⏮️ 🏒 -!!! warning - 🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃. +/// warning - 💭 🆓 🚶 👉. +🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃. + +💭 🆓 🚶 👉. + +/// 🚥 👆 ▶️ 🏗 ⚪️➡️ 🖌, 👆 🎲 👻 📆 ⏮️ 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), ⚖️ 🙆 🎏 🔁 🐜. 🚥 👆 ⏪ ✔️ 📟 🧢 👈 ⚙️ <a href="https://docs.peewee-orm.com/en/latest/" class="external-link" target="_blank">🏒 🐜</a>, 👆 💪 ✅ 📥 ❔ ⚙️ ⚫️ ⏮️ **FastAPI**. -!!! warning "🐍 3️⃣.7️⃣ ➕ ✔" - 👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI. +/// warning | "🐍 3️⃣.7️⃣ ➕ ✔" + +👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI. + +/// ## 🏒 🔁 @@ -24,8 +30,11 @@ 👐, ⚫️ 💪 ⚫️, & 📥 👆 🔜 👀 ⚫️❔ ⚫️❔ 📟 👆 ✔️ 🚮 💪 ⚙️ 🏒 ⏮️ FastAPI. -!!! note "📡 ℹ" - 👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">🩺</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">❔</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">🇵🇷</a>. +/// note | "📡 ℹ" + +👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">🩺</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">❔</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">🇵🇷</a>. + +/// ## 🎏 📱 @@ -65,8 +74,11 @@ {!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` -!!! tip - ✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓. +/// tip + +✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓. + +/// #### 🗒 @@ -84,9 +96,11 @@ connect_args={"check_same_thread": False} ...⚫️ 💪 🕴 `SQLite`. -!!! info "📡 ℹ" +/// info | "📡 ℹ" - ⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔. +⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔. + +/// ### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState` @@ -94,14 +108,17 @@ connect_args={"check_same_thread": False} & `threading.local` 🚫 🔗 ⏮️ 🆕 🔁 ⚒ 🏛 🐍. -!!! note "📡 ℹ" - `threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵. +/// note | "📡 ℹ" + +`threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵. - 👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅♂ 🌖, 🙅♂ 🌘. +👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅♂ 🌖, 🙅♂ 🌘. - ⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅. +⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅. - ✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI. +✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI. + +/// ✋️ 🐍 3️⃣.7️⃣ & 🔛 🚚 🌖 🏧 🎛 `threading.local`, 👈 💪 ⚙️ 🥉 🌐❔ `threading.local` 🔜 ⚙️, ✋️ 🔗 ⏮️ 🆕 🔁 ⚒. @@ -125,10 +142,13 @@ connect_args={"check_same_thread": False} , 👥 💪 ➕ 🎱 ⚒ ⚫️ 👷 🚥 ⚫️ ⚙️ `threading.local`. `__init__`, `__setattr__`, & `__getattr__` 🛠️ 🌐 ✔ 🎱 👉 ⚙️ 🏒 🍵 🤔 👈 ⚫️ 🔜 🔗 ⏮️ FastAPI. -!!! tip - 👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️. +/// tip + +👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️. - ✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`. +✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`. + +/// ### ⚙️ 🛃 `PeeweeConnectionState` 🎓 @@ -138,11 +158,17 @@ connect_args={"check_same_thread": False} {!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` -!!! tip - ⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`. +/// tip + +⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`. + +/// + +/// tip -!!! tip - 👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️. +👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️. + +/// ## ✍ 💽 🏷 @@ -154,10 +180,13 @@ connect_args={"check_same_thread": False} 👉 🎏 👆 🔜 🚥 👆 ⏩ 🏒 🔰 & ℹ 🏷 ✔️ 🎏 💽 🇸🇲 🔰. -!!! tip - 🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. +/// tip + +🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. +✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. + +/// 🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥. @@ -165,25 +194,31 @@ connect_args={"check_same_thread": False} {!../../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` -!!! tip - 🏒 ✍ 📚 🎱 🔢. +/// tip + +🏒 ✍ 📚 🎱 🔢. - ⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑. +⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑. - ⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛. +⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛. - `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆. + `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆. + +/// ## ✍ Pydantic 🏷 🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. -!!! tip - ❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. +/// tip + +❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). +👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️. +👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️. + +/// ### ✍ Pydantic *🏷* / 🔗 @@ -193,12 +228,15 @@ connect_args={"check_same_thread": False} {!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` -!!! tip - 📥 👥 🏗 🏷 ⏮️ `id`. +/// tip + +📥 👥 🏗 🏷 ⏮️ `id`. - 👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁. +👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁. - 👥 ❎ 🎱 `owner_id` 🔢 `Item`. +👥 ❎ 🎱 `owner_id` 🔢 `Item`. + +/// ### ✍ `PeeweeGetterDict` Pydantic *🏷* / 🔗 @@ -224,8 +262,11 @@ connect_args={"check_same_thread": False} & ⤴️ 👥 ⚙️ ⚫️ Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode = True`, ⏮️ 📳 🔢 `getter_dict = PeeweeGetterDict`. -!!! tip - 👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗. +/// tip + +👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗. + +/// ## 💩 🇨🇻 @@ -297,12 +338,15 @@ list(models.User.select()) **⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️). -!!! tip - FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵. +/// tip + +FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵. - ✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨. +✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨. - & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨. + & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨. + +/// #### 🏒 🗳 @@ -467,8 +511,11 @@ async def reset_db_state(): ## 📡 ℹ -!!! warning - 👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪. +/// warning + +👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪. + +/// ### ⚠ diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index b3026917a..202c90f94 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -12,8 +12,11 @@ ✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫. -!!! note - 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. +/// note + +🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. + +/// ## 🎯 @@ -164,45 +167,55 @@ John Doe 🖼, ➡️ 🔬 🔢 `list` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): +⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. - 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 🆎, 🚮 `list`. +🆎, 🚮 `list`. - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -!!! info - 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". +//// - 👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). +/// info + +👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". + +👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). + +/// 👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`". -!!! tip - 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. +/// tip + +🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. + +/// 🔨 👈, 👆 👨🎨 💪 🚚 🐕🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇: @@ -218,17 +231,21 @@ John Doe 👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// 👉 ⛓: @@ -243,17 +260,21 @@ John Doe 🥈 🆎 🔢 💲 `dict`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// 👉 ⛓: @@ -269,17 +290,21 @@ John Doe 🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>⏸ ⏸ (`|`)</abbr>. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// 👯♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`. @@ -299,23 +324,29 @@ John Doe 👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### ⚙️ `Union` ⚖️ `Optional` @@ -360,47 +391,53 @@ say_hi(name=None) # This works, None is valid 🎉 👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...& 🎏. - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...& 🎏. +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - * `Union` - * `Optional` - * ...& 🎏. +* `Union` +* `Optional` +* ...& 🎏. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - * `list` - * `tuple` - * `set` - * `dict` +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: +* `list` +* `tuple` +* `set` +* `dict` - * `Union` - * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) - * ...& 🎏. + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>⏸ ⏸ (`|`)</abbr> 📣 🇪🇺 🆎. +* `Union` +* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) +* ...& 🎏. + +🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>⏸ ⏸ (`|`)</abbr> 📣 🇪🇺 🆎. + +//// ### 🎓 🆎 @@ -436,33 +473,45 @@ say_hi(name=None) # This works, None is valid 🎉 🖼 ⚪️➡️ 🛂 Pydantic 🩺: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +/// info -!!! info - 💡 🌖 🔃 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, ✅ 🚮 🩺</a>. +💡 🌖 🔃 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, ✅ 🚮 🩺</a>. + +/// **FastAPI** 🌐 ⚓️ 🔛 Pydantic. 👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. +/// tip + +Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. + +/// ## 🆎 🔑 **FastAPI** @@ -486,5 +535,8 @@ say_hi(name=None) # This works, None is valid 🎉 ⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨🎨, ♒️), **FastAPI** 🔜 📚 👷 👆. -!!! info - 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> "🎮 🎼" ⚪️➡️ `mypy`</a>. +/// info + +🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> "🎮 🎼" ⚪️➡️ `mypy`</a>. + +/// diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index e28ead415..1d17a0e4e 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -57,17 +57,21 @@ **FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯♂️ & 🏃 🖥 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// 👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨. diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index fc9076aa8..693a75d28 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪. -!!! info - 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. +/// info + +🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. + +/// ## 🖼 📁 📊 @@ -26,16 +29,19 @@ │ └── admin.py ``` -!!! tip - 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. +/// tip + +📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. - 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. +👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. - 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: +🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`. * ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`. @@ -99,8 +105,11 @@ 🌐 🎏 `parameters`, `responses`, `dependencies`, `tags`, ♒️. -!!! tip - 👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. +/// tip + +👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. + +/// 👥 🔜 🔌 👉 `APIRouter` 👑 `FastAPI` 📱, ✋️ 🥇, ➡️ ✅ 🔗 & ➕1️⃣ `APIRouter`. @@ -116,10 +125,13 @@ {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 👥 ⚙️ 💭 🎚 📉 👉 🖼. +/// tip + +👥 ⚙️ 💭 🎚 📉 👉 🖼. + +✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}. - ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}. +/// ## ➕1️⃣ 🕹 ⏮️ `APIRouter` @@ -163,8 +175,11 @@ async def read_item(item_id: str): & 👥 💪 🚮 📇 `dependencies` 👈 🔜 🚮 🌐 *➡ 🛠️* 📻 & 🔜 🛠️/❎ 🔠 📨 ⚒ 👫. -!!! tip - 🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*. +/// tip + +🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*. + +/// 🔚 🏁 👈 🏬 ➡ 🔜: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 📻 🔗 🛠️ 🥇, ⤴️ [`dependencies` 👨🎨](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, & ⤴️ 😐 🔢 🔗. * 👆 💪 🚮 [`Security` 🔗 ⏮️ `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -!!! tip - ✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. +/// tip + +✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. + +/// + +/// check -!!! check - `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. +`prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. + +/// ### 🗄 🔗 @@ -201,8 +222,11 @@ async def read_item(item_id: str): #### ❔ ⚖ 🗄 👷 -!!! tip - 🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. +/// tip + +🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. + +/// 👁 ❣ `.`, 💖: @@ -269,10 +293,13 @@ that 🔜 ⛓: {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. +/// tip + +👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. - & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + +/// ## 👑 `FastAPI` @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 🥇 ⏬ "⚖ 🗄": +/// info + +🥇 ⏬ "⚖ 🗄": - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 🥈 ⏬ "🎆 🗄": +🥈 ⏬ "🎆 🗄": + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +💡 🌅 🔃 🐍 📦 & 🕹, ✍ <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">🛂 🐍 🧾 🔃 🕹</a>. - 💡 🌅 🔃 🐍 📦 & 🕹, ✍ <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">🛂 🐍 🧾 🔃 🕹</a>. +/// ### ❎ 📛 💥 @@ -372,26 +402,35 @@ from .routers.users import router {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. +/// info - & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. +`users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. + + & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. + +/// ⏮️ `app.include_router()` 👥 💪 🚮 🔠 `APIRouter` 👑 `FastAPI` 🈸. ⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️. -!!! note "📡 ℹ" - ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. +/// note | "📡 ℹ" + +⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. + +, ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. + +/// - , ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. +/// check -!!! check - 👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. +👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. - 👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. +👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. - ⚫️ 🏆 🚫 📉 🎭. 👶 +⚫️ 🏆 🚫 📉 🎭. 👶 + +/// ### 🔌 `APIRouter` ⏮️ 🛃 `prefix`, `tags`, `responses`, & `dependencies` @@ -438,16 +477,19 @@ from .routers.users import router & ⚫️ 🔜 👷 ☑, 👯♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. -!!! info "📶 📡 ℹ" - **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. +/// info | "📶 📡 ℹ" + +**🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. + +--- - --- + `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. - `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. +👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢. - 👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢. +👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. - 👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. +/// ## ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index 9f2c914f4..c5a04daeb 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -6,50 +6,67 @@ 🥇, 👆 ✔️ 🗄 ⚫️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -!!! warning - 👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +/// warning + +👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). + +/// ## 📣 🏷 🔢 👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// `Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. -!!! note "📡 ℹ" - 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. +/// note | "📡 ℹ" - & Pydantic `Field` 📨 👐 `FieldInfo` 👍. +🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. - `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. + & Pydantic `Field` 📨 👐 `FieldInfo` 👍. - 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +`Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. -!!! tip - 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. +💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. + +/// + +/// tip + +👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. + +/// ## 🚮 ➕ ℹ @@ -57,9 +74,12 @@ 👆 🔜 💡 🌅 🔃 ❎ ➕ ℹ ⏪ 🩺, 🕐❔ 🏫 📣 🖼. -!!! warning - ➕ 🔑 🚶♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. - 👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. +/// warning + +➕ 🔑 🚶♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. +👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. + +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index 9ada7dee1..c2a9a224d 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -8,20 +8,27 @@ & 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +//// -!!! note - 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. +/// note + +👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. + +/// ## 💗 💪 🔢 @@ -38,17 +45,21 @@ ✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` + +//// 👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷). @@ -69,9 +80,11 @@ } ``` -!!! note - 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. +/// note +👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. + +/// **FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`. @@ -87,17 +100,21 @@ ✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// 👉 💼, **FastAPI** 🔜 ⌛ 💪 💖: @@ -137,20 +154,27 @@ q: str | None = None 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +```Python hl_lines="26" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +`Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. -!!! info - `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. +/// ## ⏯ 👁 💪 🔢 @@ -166,17 +190,21 @@ item: Item = Body(embed=True) : -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +//// 👉 💼 **FastAPI** 🔜 ⌛ 💪 💖: diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index c941fa08a..23114540a 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ 👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +//// 👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇. @@ -61,23 +65,29 @@ my_list: List[str] , 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻": -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +//// ## ⚒ 🆎 @@ -87,23 +97,29 @@ my_list: List[str] ⤴️ 👥 💪 📣 `tags` ⚒ 🎻: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// ⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬. @@ -125,45 +141,57 @@ my_list: List[str] 🖼, 👥 💪 🔬 `Image` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// ### ⚙️ 📊 🆎 & ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// 👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏: @@ -196,23 +224,29 @@ my_list: List[str] 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` + +//// 🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅. @@ -220,23 +254,29 @@ my_list: List[str] 👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// 👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖: @@ -264,33 +304,45 @@ my_list: List[str] } ``` -!!! info - 👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. +/// info + +👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. + +/// ## 🙇 🐦 🏷 👆 💪 🔬 🎲 🙇 🐦 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` + +//// - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ -!!! info - 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ +/// ## 💪 😁 📇 @@ -308,17 +360,21 @@ images: list[Image] : -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` + +//// ## 👨🎨 🐕🦺 🌐 @@ -348,26 +404,33 @@ images: list[Image] 👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑. -!!! tip - ✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑. +✋️ Pydantic ✔️ 🏧 💽 🛠️. - ✋️ Pydantic ✔️ 🏧 💽 🛠️. +👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. - 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. + & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. - & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 89bb615f6..97501eb6d 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ 👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +//// `PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽. @@ -48,14 +54,17 @@ 👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣. -!!! note - `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. +/// note + +`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. + + & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. - & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. +👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. - 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. +✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. - ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. +/// ### ⚙️ Pydantic `exclude_unset` 🔢 @@ -67,23 +76,29 @@ ⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// ### ⚙️ Pydantic `update` 🔢 @@ -91,23 +106,29 @@ 💖 `stored_item_model.copy(update=update_data)`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// ### 🍕 ℹ 🌃 @@ -124,32 +145,44 @@ * 🖊 💽 👆 💽. * 📨 ℹ 🏷. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +/// -!!! tip - 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. +/// note - ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. +👀 👈 🔢 🏷 ✔. -!!! note - 👀 👈 🔢 🏷 ✔. +, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). - , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). +🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. - 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index 12f5a6315..79d8e716f 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -8,28 +8,35 @@ 📣 **📨** 💪, 👆 ⚙️ <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 🏷 ⏮️ 🌐 👫 🏋️ & 💰. -!!! info - 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. +/// info - 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. +📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. - ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️. +📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. + +⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️. + +/// ## 🗄 Pydantic `BaseModel` 🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// ## ✍ 👆 💽 🏷 @@ -37,17 +44,21 @@ ⚙️ 🐩 🐍 🆎 🌐 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// 🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦. @@ -75,17 +86,21 @@ 🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// ...& 📣 🚮 🆎 🏷 👆 ✍, `Item`. @@ -134,32 +149,39 @@ <img src="/img/tutorial/body/image05.png"> -!!! tip - 🚥 👆 ⚙️ <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">🗒</a> 👆 👨🎨, 👆 💪 ⚙️ <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic 🗒 📁</a>. +/// tip + +🚥 👆 ⚙️ <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">🗒</a> 👆 👨🎨, 👆 💪 ⚙️ <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic 🗒 📁</a>. - ⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️: +⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️: - * 🚘-🛠️ - * 🆎 ✅ - * 🛠️ - * 🔎 - * 🔬 +* 🚘-🛠️ +* 🆎 ✅ +* 🛠️ +* 🔎 +* 🔬 + +/// ## ⚙️ 🏷 🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` + +//// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// ## 📨 💪 ➕ ➡ 🔢 @@ -167,17 +189,21 @@ **FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` + +//// ## 📨 💪 ➕ ➡ ➕ 🔢 🔢 @@ -185,17 +211,21 @@ **FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` + +//// 🔢 🔢 🔜 🤔 ⏩: @@ -203,10 +233,13 @@ * 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢. * 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. +/// note + +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. + + `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌. - `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌. +/// ## 🍵 Pydantic diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 47f4a62f5..891999028 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -6,17 +6,21 @@ 🥇 🗄 `Cookie`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// ## 📣 `Cookie` 🔢 @@ -24,25 +28,35 @@ 🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +/// note | "📡 ℹ" - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// -!!! note "📡 ℹ" - `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// info - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. -!!! info - 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 8c5e33ed7..690b8973a 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -78,7 +78,10 @@ 🌖 ℹ 🔃 <abbr title="Cross-Origin Resource Sharing">⚜</abbr>, ✅ <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">🦎 ⚜ 🧾</a>. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. +/// note | "📡 ℹ" - **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. + +/// diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index c7c11b5ce..abef2a50c 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app 🔜 🚫 🛠️. -!!! info - 🌅 ℹ, ✅ <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">🛂 🐍 🩺</a>. +/// info + +🌅 ℹ, ✅ <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">🛂 🐍 🩺</a>. + +/// ## 🏃 👆 📟 ⏮️ 👆 🕹 diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index e2d2686d3..f14239b0f 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ ⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// ✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*. @@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy") ⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// 💸 🙋 `__init__` 👩🔬 ⚙️ ✍ 👐 🎓: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// ...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗. @@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy") 🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// **FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶♀️ 🔢 `commons` 👆 🔢. @@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams) ...: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` + +//// ✋️ 📣 🆎 💡 👈 🌌 👆 👨🎨 🔜 💭 ⚫️❔ 🔜 🚶♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️: @@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends() 🎏 🖼 🔜 ⤴️ 👀 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` + +//// ...& **FastAPI** 🔜 💭 ⚫️❔. -!!! tip - 🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️. +/// tip + +🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️. + +⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. - ⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. +/// diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4d54b91c7..bf267e056 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,17 +20,23 @@ 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶♀️ 👆 *➡ 🛠️ 🔢*. -!!! tip - 👨🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. +/// tip - ⚙️ 👉 `dependencies` *➡ 🛠️ 👨🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨🎨/🏭 ❌. +👨🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. - ⚫️ 💪 ℹ ❎ 😨 🆕 👩💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. +⚙️ 👉 `dependencies` *➡ 🛠️ 👨🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨🎨/🏭 ❌. -!!! info - 👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. +⚫️ 💪 ℹ ❎ 😨 🆕 👩💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. - ✋️ 🎰 💼, 🕐❔ 🛠️ 💂♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. +/// + +/// info + +👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. + +✋️ 🎰 💼, 🕐❔ 🛠️ 💂♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. + +/// ## 🔗 ❌ & 📨 💲 diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 3ed5aeba5..5998d06df 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI 🐕🦺 🔗 👈 <abbr title='sometimes also called "exit", "cleanu 👉, ⚙️ `yield` ↩️ `return`, & ✍ ➕ 🔁 ⏮️. -!!! tip - ⚒ 💭 ⚙️ `yield` 1️⃣ 👁 🕰. +/// tip -!!! note "📡 ℹ" - 🙆 🔢 👈 ☑ ⚙️ ⏮️: +⚒ 💭 ⚙️ `yield` 1️⃣ 👁 🕰. - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️ - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +/// - 🔜 ☑ ⚙️ **FastAPI** 🔗. +/// note | "📡 ℹ" - 👐, FastAPI ⚙️ 📚 2️⃣ 👨🎨 🔘. +🙆 🔢 👈 ☑ ⚙️ ⏮️: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️ +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + +🔜 ☑ ⚙️ **FastAPI** 🔗. + +👐, FastAPI ⚙️ 📚 2️⃣ 👨🎨 🔘. + +/// ## 💽 🔗 ⏮️ `yield` @@ -39,10 +45,13 @@ FastAPI 🐕🦺 🔗 👈 <abbr title='sometimes also called "exit", "cleanu {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip - 👆 💪 ⚙️ `async` ⚖️ 😐 🔢. +/// tip + +👆 💪 ⚙️ `async` ⚖️ 😐 🔢. - **FastAPI** 🔜 ▶️️ 👜 ⏮️ 🔠, 🎏 ⏮️ 😐 🔗. +**FastAPI** 🔜 ▶️️ 👜 ⏮️ 🔠, 🎏 ⏮️ 😐 🔗. + +/// ## 🔗 ⏮️ `yield` & `try` @@ -88,10 +97,13 @@ FastAPI 🐕🦺 🔗 👈 <abbr title='sometimes also called "exit", "cleanu **FastAPI** 🔜 ⚒ 💭 🌐 🏃 ☑ ✔. -!!! note "📡 ℹ" - 👉 👷 👏 🐍 <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">🔑 👨💼</a>. +/// note | "📡 ℹ" + +👉 👷 👏 🐍 <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">🔑 👨💼</a>. - **FastAPI** ⚙️ 👫 🔘 🏆 👉. +**FastAPI** ⚙️ 👫 🔘 🏆 👉. + +/// ## 🔗 ⏮️ `yield` & `HTTPException` @@ -113,8 +125,11 @@ FastAPI 🐕🦺 🔗 👈 <abbr title='sometimes also called "exit", "cleanu 🚥 👆 ✔️ 🛃 ⚠ 👈 👆 🔜 💖 🍵 *⏭* 🛬 📨 & 🎲 ❎ 📨, 🎲 🙋♀ `HTTPException`, ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}. -!!! tip - 👆 💪 🤚 ⚠ 🔌 `HTTPException` *⏭* `yield`. ✋️ 🚫 ⏮️. +/// tip + +👆 💪 🤚 ⚠ 🔌 `HTTPException` *⏭* `yield`. ✋️ 🚫 ⏮️. + +/// 🔁 🛠️ 🌅 ⚖️ 🌘 💖 👉 📊. 🕰 💧 ⚪️➡️ 🔝 🔝. & 🔠 🏓 1️⃣ 🍕 🔗 ⚖️ 🛠️ 📟. @@ -158,15 +173,21 @@ participant tasks as Background tasks end ``` -!!! info - 🕴 **1️⃣ 📨** 🔜 📨 👩💻. ⚫️ 💪 1️⃣ ❌ 📨 ⚖️ ⚫️ 🔜 📨 ⚪️➡️ *➡ 🛠️*. +/// info + +🕴 **1️⃣ 📨** 🔜 📨 👩💻. ⚫️ 💪 1️⃣ ❌ 📨 ⚖️ ⚫️ 🔜 📨 ⚪️➡️ *➡ 🛠️*. + +⏮️ 1️⃣ 📚 📨 📨, 🙅♂ 🎏 📨 💪 📨. + +/// + +/// tip - ⏮️ 1️⃣ 📚 📨 📨, 🙅♂ 🎏 📨 💪 📨. +👉 📊 🎦 `HTTPException`, ✋️ 👆 💪 🤚 🙆 🎏 ⚠ ❔ 👆 ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}. -!!! tip - 👉 📊 🎦 `HTTPException`, ✋️ 👆 💪 🤚 🙆 🎏 ⚠ ❔ 👆 ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}. +🚥 👆 🤚 🙆 ⚠, ⚫️ 🔜 🚶♀️ 🔗 ⏮️ 🌾, 🔌 `HTTPException`, & ⤴️ **🔄** ⚠ 🐕🦺. 🚥 📤 🙅♂ ⚠ 🐕🦺 👈 ⚠, ⚫️ 🔜 ⤴️ 🍵 🔢 🔗 `ServerErrorMiddleware`, 🛬 5️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟, ➡️ 👩💻 💭 👈 📤 ❌ 💽. - 🚥 👆 🤚 🙆 ⚠, ⚫️ 🔜 🚶♀️ 🔗 ⏮️ 🌾, 🔌 `HTTPException`, & ⤴️ **🔄** ⚠ 🐕🦺. 🚥 📤 🙅♂ ⚠ 🐕🦺 👈 ⚠, ⚫️ 🔜 ⤴️ 🍵 🔢 🔗 `ServerErrorMiddleware`, 🛬 5️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟, ➡️ 👩💻 💭 👈 📤 ❌ 💽. +/// ## 🔑 👨💼 @@ -190,10 +211,13 @@ with open("./somefile.txt") as f: ### ⚙️ 🔑 👨💼 🔗 ⏮️ `yield` -!!! warning - 👉, 🌅 ⚖️ 🌘, "🏧" 💭. +/// warning - 🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 ⚫️ 🔜. +👉, 🌅 ⚖️ 🌘, "🏧" 💭. + +🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 ⚫️ 🔜. + +/// 🐍, 👆 💪 ✍ 🔑 👨💼 <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">🏗 🎓 ⏮️ 2️⃣ 👩🔬: `__enter__()` & `__exit__()`</a>. @@ -204,16 +228,19 @@ with open("./somefile.txt") as f: {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - ➕1️⃣ 🌌 ✍ 🔑 👨💼 ⏮️: +/// tip + +➕1️⃣ 🌌 ✍ 🔑 👨💼 ⏮️: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️ +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️ - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. - ⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. +👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. - 👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. +✋️ 👆 🚫 ✔️ ⚙️ 👨🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). - ✋️ 👆 🚫 ✔️ ⚙️ 👨🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). +FastAPI 🔜 ⚫️ 👆 🔘. - FastAPI 🔜 ⚫️ 👆 🔘. +/// diff --git a/docs/em/docs/tutorial/dependencies/index.md b/docs/em/docs/tutorial/dependencies/index.md index ffd38d716..efb4ee672 100644 --- a/docs/em/docs/tutorial/dependencies/index.md +++ b/docs/em/docs/tutorial/dependencies/index.md @@ -31,17 +31,21 @@ ⚫️ 🔢 👈 💪 ✊ 🌐 🎏 🔢 👈 *➡ 🛠️ 🔢* 💪 ✊: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// 👈 ⚫️. @@ -63,33 +67,41 @@ ### 🗄 `Depends` -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// ### 📣 🔗, "⚓️" 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏. @@ -99,8 +111,11 @@ & 👈 🔢 ✊ 🔢 🎏 🌌 👈 *➡ 🛠️ 🔢* . -!!! tip - 👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. +/// tip + +👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. + +/// 🕐❔ 🆕 📨 🛬, **FastAPI** 🔜 ✊ 💅: @@ -121,10 +136,13 @@ common_parameters --> read_users 👉 🌌 👆 ✍ 🔗 📟 🕐 & **FastAPI** ✊ 💅 🤙 ⚫️ 👆 *➡ 🛠️*. -!!! check - 👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. +/// check - 👆 🚶♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. +👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. + +👆 🚶♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. + +/// ## `async` ⚖️ 🚫 `async` @@ -136,8 +154,11 @@ common_parameters --> read_users ⚫️ 🚫 🤔. **FastAPI** 🔜 💭 ⚫️❔. -!!! note - 🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. +/// note + +🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. + +/// ## 🛠️ ⏮️ 🗄 diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index 454ff5129..02b33ccd7 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -10,17 +10,21 @@ 👆 💪 ✍ 🥇 🔗 ("☑") 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +//// ⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️. @@ -30,17 +34,21 @@ ⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁♂️): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +//// ➡️ 🎯 🔛 🔢 📣: @@ -53,22 +61,29 @@ ⤴️ 👥 💪 ⚙️ 🔗 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. -!!! info - 👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. +✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. - ✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. +/// ```mermaid graph TB @@ -102,9 +117,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False ✋️, ⚫️ 📶 🏋️, & ✔ 👆 📣 🎲 🙇 🐦 🔗 "📊" (🌲). -!!! tip - 🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. +/// tip + +🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. + +✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂♂**. - ✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂♂**. + & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. - & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. +/// diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 75ca3824d..314f5b324 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ ⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` + +//// 👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`. @@ -38,5 +42,8 @@ ⚫️ 🚫 📨 ⭕ `str` ⚗ 💽 🎻 📁 (🎻). ⚫️ 📨 🐍 🐩 💽 📊 (✅ `dict`) ⏮️ 💲 & 🎧-💲 👈 🌐 🔗 ⏮️ 🎻. -!!! note - `jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. +/// note + +`jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. + +/// diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index 54a186f12..cbe111079 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -55,28 +55,36 @@ 📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// 🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 82f974d9f..4703c7123 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ * **🔢 🏷** 🔜 🚫 ✔️ 🔐. * **💽 🏷** 🔜 🎲 💪 ✔️ #️⃣ 🔐. -!!! danger - 🙅 🏪 👩💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. +/// danger - 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}. +🙅 🏪 👩💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. + +🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}. + +/// ## 💗 🏷 📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// ### 🔃 `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning - 🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂♂. +/// warning + +🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂♂. + +/// ## 📉 ❎ @@ -158,17 +168,21 @@ UserInDB( 👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` + +//// - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// ## `Union` ⚖️ `anyOf` @@ -178,20 +192,27 @@ UserInDB( 👈, ⚙️ 🐩 🐍 🆎 🔑 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: -!!! note - 🕐❔ ⚖ <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. +/// note + +🕐❔ ⚖ <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.6️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// ### `Union` 🐍 3️⃣.1️⃣0️⃣ @@ -213,17 +234,21 @@ some_variable: PlaneItem | CarItem 👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// ## 📨 ⏮️ ❌ `dict` @@ -233,17 +258,21 @@ some_variable: PlaneItem | CarItem 👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` + +//// - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index b8d3f6b56..158189e6e 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note - 📋 `uvicorn main:app` 🔗: +/// note - * `main`: 📁 `main.py` (🐍 "🕹"). - * `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. - * `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. +📋 `uvicorn main:app` 🔗: + +* `main`: 📁 `main.py` (🐍 "🕹"). +* `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. +* `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. + +/// 🔢, 📤 ⏸ ⏮️ 🕳 💖: @@ -136,10 +139,13 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. -!!! note "📡 ℹ" - `FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. +/// note | "📡 ℹ" + +`FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. - 👆 💪 ⚙️ 🌐 <a href="https://www.starlette.io/" class="external-link" target="_blank">💃</a> 🛠️ ⏮️ `FastAPI` 💁♂️. +👆 💪 ⚙️ 🌐 <a href="https://www.starlette.io/" class="external-link" target="_blank">💃</a> 🛠️ ⏮️ `FastAPI` 💁♂️. + +/// ### 🔁 2️⃣: ✍ `FastAPI` "👐" @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "➡" 🛎 🤙 "🔗" ⚖️ "🛣". +/// info + +"➡" 🛎 🤙 "🔗" ⚖️ "🛣". + +/// ⏪ 🏗 🛠️, "➡" 👑 🌌 🎏 "⚠" & "ℹ". @@ -250,16 +259,19 @@ https://example.com/items/foo * ➡ `/` * ⚙️ <abbr title="an HTTP GET method"><code>get</code> 🛠️</abbr> -!!! info "`@decorator` ℹ" - 👈 `@something` ❕ 🐍 🤙 "👨🎨". +/// info | "`@decorator` ℹ" - 👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). +👈 `@something` ❕ 🐍 🤙 "👨🎨". - "👨🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. +👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). - 👆 💼, 👉 👨🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. + "👨🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. - ⚫️ "**➡ 🛠️ 👨🎨**". +👆 💼, 👉 👨🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. + +⚫️ "**➡ 🛠️ 👨🎨**". + +/// 👆 💪 ⚙️ 🎏 🛠️: @@ -274,14 +286,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩🔬) 👆 🎋. +/// tip + +👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩🔬) 👆 🎋. - **FastAPI** 🚫 🛠️ 🙆 🎯 🔑. +**FastAPI** 🚫 🛠️ 🙆 🎯 🔑. - ℹ 📥 🎁 📄, 🚫 📄. +ℹ 📥 🎁 📄, 🚫 📄. - 🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. +🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. + +/// ### 🔁 4️⃣: 🔬 **➡ 🛠️ 🔢** @@ -309,8 +324,11 @@ https://example.com/items/foo {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}. +/// note + +🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}. + +/// ### 🔁 5️⃣: 📨 🎚 diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index 36d58e2af..ed32ab53a 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ } ``` -!!! tip - 🕐❔ 🙋♀ `HTTPException`, 👆 💪 🚶♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. +/// tip - 👆 💪 🚶♀️ `dict`, `list`, ♒️. +🕐❔ 🙋♀ `HTTPException`, 👆 💪 🚶♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. - 👫 🍵 🔁 **FastAPI** & 🗜 🎻. +👆 💪 🚶♀️ `dict`, `list`, ♒️. + +👫 🍵 🔁 **FastAPI** & 🗜 🎻. + +/// ## 🚮 🛃 🎚 @@ -106,10 +109,13 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. +/// ## 🔐 🔢 ⚠ 🐕🦺 @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` 🆚 `ValidationError` -!!! warning - 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. +/// warning + +👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. + +/// `RequestValidationError` 🎧-🎓 Pydantic <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. @@ -183,10 +192,13 @@ path -> item_id {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ### ⚙️ `RequestValidationError` 💪 diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 0f33a1774..82583c7c3 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -6,17 +6,21 @@ 🥇 🗄 `Header`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// ## 📣 `Header` 🔢 @@ -24,25 +28,35 @@ 🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +/// note | "📡 ℹ" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +`Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// -!!! note "📡 ℹ" - `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// info - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. -!!! info - 📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +/// ## 🏧 🛠️ @@ -60,20 +74,27 @@ 🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// warning - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. -!!! warning - ⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. +/// ## ❎ 🎚 @@ -85,23 +106,29 @@ 🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// 🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖: diff --git a/docs/em/docs/tutorial/index.md b/docs/em/docs/tutorial/index.md index fd6900db0..5f7532341 100644 --- a/docs/em/docs/tutorial/index.md +++ b/docs/em/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...👈 🔌 `uvicorn`, 👈 👆 💪 ⚙️ 💽 👈 🏃 👆 📟. -!!! note - 👆 💪 ❎ ⚫️ 🍕 🍕. +/// note - 👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: +👆 💪 ❎ ⚫️ 🍕 🍕. - ``` - pip install "fastapi[standard]" - ``` +👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: - ❎ `uvicorn` 👷 💽: +``` +pip install "fastapi[standard]" +``` + +❎ `uvicorn` 👷 💽: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` + & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. - & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. +/// ## 🏧 👩💻 🦮 diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 97d345fa2..6caeed4cd 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -21,8 +21,11 @@ {!../../../docs_src/metadata/tutorial001.py!} ``` -!!! tip - 👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. +/// tip + +👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. + +/// ⏮️ 👉 📳, 🏧 🛠️ 🩺 🔜 👀 💖: @@ -54,8 +57,11 @@ 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). -!!! tip - 👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. +/// tip + +👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. + +/// ### ⚙️ 👆 🔖 @@ -65,8 +71,11 @@ {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info - ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}. +/// info + +✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}. + +/// ### ✅ 🩺 diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index 644b4690c..b9bb12e00 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟. * ⤴️ ⚫️ 📨 **📨**. -!!! note "📡 ℹ" - 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. +/// note | "📡 ℹ" - 🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. +🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. + +🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. + +/// ## ✍ 🛠️ @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">⚙️ '✖-' 🔡</a>. +/// tip + +✔️ 🤯 👈 🛃 © 🎚 💪 🚮 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">⚙️ '✖-' 🔡</a>. + +✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">💃 ⚜ 🩺</a>. + +/// + +/// note | "📡 ℹ" - ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">💃 ⚜ 🩺</a>. +👆 💪 ⚙️ `from starlette.requests import Request`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request`. +**FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ### ⏭ & ⏮️ `response` diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 916529258..1979bed2b 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ 📤 📚 🔢 👈 👆 💪 🚶♀️ 👆 *➡ 🛠️ 👨🎨* 🔗 ⚫️. -!!! warning - 👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*. +/// warning + +👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*. + +/// ## 📨 👔 📟 @@ -13,52 +16,67 @@ ✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// 👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette import status`. + +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔖 👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// 👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢: @@ -80,23 +98,29 @@ 👆 💪 🚮 `summary` & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// ## 📛 ⚪️➡️ #️⃣ @@ -104,23 +128,29 @@ 👆 💪 ✍ <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">✍</a> #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// ⚫️ 🔜 ⚙️ 🎓 🩺: @@ -130,31 +160,43 @@ 👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info - 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. +🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. -!!! check - 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. +, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". - , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". +/// <img src="/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index b1ba2670b..a7952984c 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,21 @@ 🥇, 🗄 `Path` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// ## 📣 🗃 @@ -24,24 +28,31 @@ 🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -!!! note - ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. +//// - , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. +/// note - 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. +➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. + +, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. + +👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. + +/// ## ✔ 🔢 👆 💪 @@ -121,18 +132,24 @@ * `lt`: `l`👭 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -!!! info - `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. +/// info + +`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. + +🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. + +/// + +/// note | "📡 ℹ" - 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. +🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. -!!! note "📡 ℹ" - 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. +👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. - 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. +, 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. - , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. +👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎. - 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎. +👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌. - 👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌. +/// diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index ac64d2ebb..e0d51a1df 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ 👉 💼, `item_id` 📣 `int`. -!!! check - 👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. +/// check + +👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. + +/// ## 💽 <abbr title="also known as: serialization, parsing, marshalling">🛠️</abbr> @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check - 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. +/// check + +👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. + +, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>. - , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>. +/// ## 💽 🔬 @@ -63,12 +69,15 @@ 🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! check - , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. +/// check - 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️. +, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. - 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. +👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️. + +👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. + +/// ## 🧾 @@ -76,10 +85,13 @@ <img src="/img/tutorial/path-params/image01.png"> -!!! check - 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). +/// check + +🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). + +👀 👈 ➡ 🔢 📣 🔢. - 👀 👈 ➡ 🔢 📣 🔢. +/// ## 🐩-⚓️ 💰, 🎛 🧾 @@ -139,11 +151,17 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">🔢 (⚖️ 🔢) 💪 🐍</a> ↩️ ⏬ 3️⃣.4️⃣. +/// info -!!! tip - 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 <abbr title="Technically, Deep Learning model architectures">🏷</abbr>. +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">🔢 (⚖️ 🔢) 💪 🐍</a> ↩️ ⏬ 3️⃣.4️⃣. + +/// + +/// tip + +🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 <abbr title="Technically, Deep Learning model architectures">🏷</abbr>. + +/// ### 📣 *➡ 🔢* @@ -179,8 +197,11 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip - 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. +/// tip + +👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. + +/// #### 📨 *🔢 👨🎓* @@ -233,10 +254,13 @@ {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip - 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). +/// tip + +👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). + +👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. - 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index 1268c0d6e..23873155e 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ ➡️ ✊ 👉 🈸 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +//// 🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. +/// note + +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. - `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌. + `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌. + +/// ## 🌖 🔬 @@ -31,33 +38,41 @@ 🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="3" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// ## ⚙️ `Query` 🔢 💲 & 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// 👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲. @@ -87,22 +102,25 @@ q: str | None = None ✋️ ⚫️ 📣 ⚫️ 🎯 💆♂ 🔢 🔢. -!!! info - ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: +/// info - ```Python - = None - ``` +✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: - ⚖️: +```Python += None +``` + +⚖️: + +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. - ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. + `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. - `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. +/// ⤴️, 👥 💪 🚶♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻: @@ -116,33 +134,41 @@ q: Union[str, None] = Query(default=None, max_length=50) 👆 💪 🚮 🔢 `min_length`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +//// ## 🚮 🥔 🧬 👆 💪 🔬 <abbr title="A regular expression, regex or regexp is a sequence of characters that define a search pattern for strings.">🥔 🧬</abbr> 👈 🔢 🔜 🏏: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// 👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲: @@ -164,8 +190,11 @@ q: Union[str, None] = Query(default=None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note - ✔️ 🔢 💲 ⚒ 🔢 📦. +/// note + +✔️ 🔢 💲 ⚒ 🔢 📦. + +/// ## ⚒ ⚫️ ✔ @@ -201,10 +230,13 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006b.py!} ``` -!!! info - 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">🍕 🐍 & 🤙 "❕"</a>. +/// info + +🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">🍕 🐍 & 🤙 "❕"</a>. + +⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. - ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. +/// 👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔. @@ -214,20 +246,27 @@ q: Union[str, None] = Query(default=None, min_length=3) 👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. -!!! tip - Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>. +/// ### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) @@ -237,8 +276,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006d.py!} ``` -!!! tip - 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. +/// tip + +💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. + +/// ## 🔢 🔢 📇 / 💗 💲 @@ -246,23 +288,29 @@ q: Union[str, None] = Query(default=None, min_length=3) 🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` + +//// ⤴️, ⏮️ 📛 💖: @@ -283,8 +331,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. +/// tip + +📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. + +/// 🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲: @@ -294,17 +345,21 @@ http://localhost:8000/items/?q=foo&q=bar & 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +//// 🚥 👆 🚶: @@ -331,10 +386,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. +/// note - 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. +✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. + +🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. + +/// ## 📣 🌅 🗃 @@ -342,38 +400,49 @@ http://localhost:8000/items/ 👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩💻 🔢 & 🔢 🧰. -!!! note - ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺. +/// note + +✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺. - 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. +👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. + +/// 👆 💪 🚮 `title`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` + +//// & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +//// ## 📛 🔢 @@ -393,17 +462,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +//// ## 😛 🔢 @@ -413,17 +486,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 🚶♀️ 🔢 `deprecated=True` `Query`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +//// 🩺 🔜 🎦 ⚫️ 💖 👉: @@ -433,17 +510,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index 746b0af9e..9bdab9e3c 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20 🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// 👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. -!!! check - 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. +/// check + +👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. + +/// ## 🔢 🔢 🆎 🛠️ 👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// 👉 💼, 🚥 👆 🚶: @@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes 👫 🔜 🔬 📛: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` + +//// - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// ## ✔ 🔢 🔢 @@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy & ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` + +//// 👉 💼, 📤 3️⃣ 🔢 🔢: @@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, `int` ⏮️ 🔢 💲 `0`. * `limit`, 📦 `int`. -!!! tip - 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}. +/// tip + +👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index be2218f89..010aa76bf 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -2,12 +2,15 @@ 👆 💪 🔬 📁 📂 👩💻 ⚙️ `File`. -!!! info - 📨 📂 📁, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. - 👉 ↩️ 📂 📁 📨 "📨 💽". +🤶 Ⓜ. `pip install python-multipart`. + +👉 ↩️ 📂 📁 📨 "📨 💽". + +/// ## 🗄 `File` @@ -25,13 +28,19 @@ {!../../../docs_src/request_files/tutorial001.py!} ``` -!!! info - `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. +/// info + +`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. + +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +/// -!!! tip - 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +/// tip + +📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// 📁 🔜 📂 "📨 💽". @@ -90,11 +99,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 📡 ℹ" - 🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫. +/// note | "`async` 📡 ℹ" + +🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫. -!!! note "💃 📡 ℹ" - **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. +/// + +/// note | "💃 📡 ℹ" + +**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. + +/// ## ⚫️❔ "📨 💽" @@ -102,33 +117,43 @@ contents = myfile.file.read() **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. +/// note | "📡 ℹ" + +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. + +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. + +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>. + +/// - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. +/// warning - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>. +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 📦 📁 📂 👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 14" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// ## `UploadFile` ⏮️ 🌖 🗃 @@ -146,40 +171,51 @@ contents = myfile.file.read() ⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +//// 👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + +/// ### 💗 📁 📂 ⏮️ 🌖 🗃 & 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 0415dbf01..ab39d1b94 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -2,10 +2,13 @@ 👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`. -!!! info - 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `File` & `Form` @@ -25,10 +28,13 @@ & 👆 💪 📣 📁 `bytes` & `UploadFile`. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +/// warning + +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. + +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index f12d6e650..74117c47d 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -2,10 +2,13 @@ 🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`. -!!! info - ⚙️ 📨, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +⚙️ 📨, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `Form` @@ -29,11 +32,17 @@ ⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️. -!!! info - `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. +/// info + +`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. + +/// + +/// tip -!!! tip - 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// ## 🔃 "📨 🏑" @@ -41,17 +50,23 @@ **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. +/// note | "📡 ℹ" + +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. + +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. + +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>. + +/// - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. +/// warning - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>. +👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. -!!! warning - 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 7103e9176..caae47d14 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ 👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +//// FastAPI 🔜 ⚙️ 👉 📨 🆎: @@ -53,35 +59,47 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: * `@app.delete()` * ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` -!!! note - 👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +//// + +/// note + +👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. + +/// `response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`. FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄. -!!! tip - 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. +/// tip + +🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. + +👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. - 👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. +/// ### `response_model` 📫 @@ -95,37 +113,48 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +/// info -!!! info - ⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. - 🤶 Ⓜ. `pip install email-validator` - ⚖️ `pip install pydantic[email]`. +🤶 Ⓜ. `pip install email-validator` +⚖️ `pip install pydantic[email]`. + +/// & 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// 🔜, 🕐❔ 🖥 🏗 👩💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨. @@ -133,52 +162,67 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** ✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩💻 🔐 🔠 👩💻. -!!! danger - 🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. +/// danger + +🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. + +/// ## 🚮 🔢 🏷 👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// 📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩💻 👈 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// ...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// , **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic). @@ -202,17 +246,21 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕🦺 👨🎨 & 🧰, & 🤚 FastAPI **💽 🖥**. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` + +//// - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// ⏮️ 👉, 👥 🤚 🏭 🐕🦺, ⚪️➡️ 👨🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI. @@ -278,17 +326,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 <abbr title='A union between multiple types means "any of these types".'>🇪🇺</abbr> 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// ...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`. @@ -300,17 +352,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +//// 👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶 @@ -318,23 +374,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 📨 🏷 💪 ✔️ 🔢 💲, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +//// * `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`. * `tax: float = 10.5` ✔️ 🔢 `10.5`. @@ -348,23 +410,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚒ *➡ 🛠️ 👨🎨* 🔢 `response_model_exclude_unset=True`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// & 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒. @@ -377,16 +445,22 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 } ``` -!!! info - FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">🚮 `exclude_unset` 🔢</a> 🏆 👉. +/// info + +FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">🚮 `exclude_unset` 🔢</a> 🏆 👉. + +/// + +/// info -!!! info - 👆 💪 ⚙️: +👆 💪 ⚙️: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - 🔬 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 🩺</a> `exclude_defaults` & `exclude_none`. +🔬 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 🩺</a> `exclude_defaults` & `exclude_none`. + +/// #### 📊 ⏮️ 💲 🏑 ⏮️ 🔢 @@ -421,10 +495,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t , 👫 🔜 🔌 🎻 📨. -!!! tip - 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. +/// tip + +👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. + +👫 💪 📇 (`[]`), `float` `10.5`, ♒️. - 👫 💪 📇 (`[]`), `float` `10.5`, ♒️. +/// ### `response_model_include` & `response_model_exclude` @@ -434,45 +511,59 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t 👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢. -!!! tip - ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. +/// tip + +✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. + +👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. - 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. +👉 ✔ `response_model_by_alias` 👈 👷 ➡. - 👉 ✔ `response_model_by_alias` 👈 👷 ➡. +/// -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +/// tip -!!! tip - ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. +❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. - ⚫️ 🌓 `set(["name", "description"])`. +⚫️ 🌓 `set(["name", "description"])`. + +/// #### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ 🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index e5149de7d..57c44777a 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note - 👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +/// note + +👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. + +/// `status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟. -!!! info - `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. +/// info + +`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. + +/// ⚫️ 🔜: @@ -27,15 +33,21 @@ <img src="/img/tutorial/response-status-code/image01.png"> -!!! note - 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. +/// note + +📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. + +FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪. - FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪. +/// ## 🔃 🇺🇸🔍 👔 📟 -!!! note - 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. +/// note + +🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. + +/// 🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨. @@ -54,8 +66,11 @@ * 💊 ❌ ⚪️➡️ 👩💻, 👆 💪 ⚙️ `400`. * `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟. -!!! tip - 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🧾 🔃 🇺🇸🔍 👔 📟</a>. +/// tip + +💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🧾 🔃 🇺🇸🔍 👔 📟</a>. + +/// ## ⌨ 💭 📛 @@ -79,10 +94,13 @@ <img src="/img/tutorial/response-status-code/image02.png"> -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette import status`. + +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔀 🔢 diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index 114d5a84a..8562de09c 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -8,24 +8,31 @@ 👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 <a href="https://docs.pydantic.dev/latest/concepts/json_schema/#customizing-json-schema" class="external-link" target="_blank">Pydantic 🩺: 🔗 🛃</a>: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +```Python hl_lines="15-23" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="13-21" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` + +//// 👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. -!!! tip - 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. +/// tip + +👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. + +🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️. - 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️. +/// ## `Field` 🌖 ❌ @@ -33,20 +40,27 @@ 👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +/// warning -!!! warning - 🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. +🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. + +/// ## `example` & `examples` 🗄 @@ -66,17 +80,21 @@ 📥 👥 🚶♀️ `example` 📊 ⌛ `Body()`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="20-25" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +```Python hl_lines="18-23" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// ### 🖼 🩺 🎚 @@ -97,17 +115,21 @@ * `value`: 👉 ☑ 🖼 🎦, ✅ `dict`. * `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕🦺 📚 🧰 `value`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` + +//// ### 🖼 🩺 🎚 @@ -117,10 +139,13 @@ ## 📡 ℹ -!!! warning - 👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. +/// warning + +👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. + +🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. - 🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. +/// 🕐❔ 👆 🚮 🖼 🔘 Pydantic 🏷, ⚙️ `schema_extra` ⚖️ `Field(example="something")` 👈 🖼 🚮 **🎻 🔗** 👈 Pydantic 🏷. diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 8c2c95cfd..538ea7b0a 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -26,12 +26,15 @@ ## 🏃 ⚫️ -!!! info - 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. - 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. +🤶 Ⓜ. `pip install python-multipart`. + +👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. + +/// 🏃 🖼 ⏮️: @@ -53,17 +56,23 @@ $ uvicorn main:app --reload <img src="/img/tutorial/security/image01.png"> -!!! check "✔ 🔼 ❗" - 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. +/// check | "✔ 🔼 ❗" + +👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. + + & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. - & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. +/// & 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑): <img src="/img/tutorial/security/image02.png"> -!!! note - ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. +/// note + +⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. + +/// 👉 ↗️ 🚫 🕸 🏁 👩💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️. @@ -105,14 +114,17 @@ Oauth2️⃣ 🔧 👈 👩💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓. -!!! info - "📨" 🤝 🚫 🕴 🎛. +/// info + +"📨" 🤝 🚫 🕴 🎛. - ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. +✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. - & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. + & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. - 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. +👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. + +/// 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩💻 (🕸 🏃 👩💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. @@ -120,21 +132,27 @@ Oauth2️⃣ 🔧 👈 👩💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip - 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. +/// tip + +📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. - ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. +↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. - ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +/// 👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️. 👥 🔜 🔜 ✍ ☑ ➡ 🛠️. -!!! info - 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. +/// info + +🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. - 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. +👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. + +/// `oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲". @@ -158,10 +176,13 @@ oauth2_scheme(some, parameters) **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺). -!!! info "📡 ℹ" - **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. +/// info | "📡 ℹ" + +**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. + +🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. - 🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. +/// ## ⚫️❔ ⚫️ 🔨 diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 455cb4f46..15545f427 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -16,17 +16,21 @@ 🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## ✍ `get_current_user` 🔗 @@ -38,63 +42,81 @@ 🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 🤚 👩💻 `get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 💉 ⏮️ 👩💻 🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// 👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. 👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅. -!!! tip - 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. +/// tip + +👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. + +📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. - 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. +/// -!!! check - 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. +/// check - 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. +🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. + +👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. + +/// ## 🎏 🏷 @@ -128,17 +150,21 @@ & 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/security/index.md b/docs/em/docs/tutorial/security/index.md index d76f7203f..1a47e5510 100644 --- a/docs/em/docs/tutorial/security/index.md +++ b/docs/em/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Oauth2️⃣ 🔧 👈 🔬 📚 🌌 🍵 🤝 & ✔. Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮️ 🇺🇸🔍. -!!! tip - 📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. +/// tip +📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. + +/// ## 👩💻 🔗 @@ -87,10 +89,13 @@ Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮ * 👉 🏧 🔍 ⚫️❔ 🔬 👩💻 🔗 🔧. -!!! tip - 🛠️ 🎏 🤝/✔ 🐕🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. +/// tip + +🛠️ 🎏 🤝/✔ 🐕🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. + +🌅 🏗 ⚠ 🏗 🤝/✔ 🐕🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋♂ 👆. - 🌅 🏗 ⚠ 🏗 🤝/✔ 🐕🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋♂ 👆. +/// ## **FastAPI** 🚙 diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc3c943f8..3ab8cc986 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]" 📥 👥 ⚙️ 👍 1️⃣: <a href="https://cryptography.io/" class="external-link" target="_blank">)/⚛</a>. -!!! tip - 👉 🔰 ⏪ ⚙️ <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>. +/// tip - ✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. +👉 🔰 ⏪ ⚙️ <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>. + +✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. + +/// ## 🔐 🔁 @@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]" </div> -!!! tip - ⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂♂ 🔌-⚖️ 📚 🎏. +/// tip + +⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂♂ 🔌-⚖️ 📚 🎏. + +, 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. - , 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. + & 👆 👩💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. - & 👆 👩💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. +/// ## #️⃣ & ✔ 🔐 @@ -96,12 +102,15 @@ $ pip install "passlib[bcrypt]" ✍ 🇸🇲 "🔑". 👉 ⚫️❔ 🔜 ⚙️ #️⃣ & ✔ 🔐. -!!! tip - 🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. +/// tip - 🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. +🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. - & 🔗 ⏮️ 🌐 👫 🎏 🕰. +🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. + + & 🔗 ⏮️ 🌐 👫 🎏 🕰. + +/// ✍ 🚙 🔢 #️⃣ 🔐 👟 ⚪️➡️ 👩💻. @@ -109,20 +118,27 @@ $ pip install "passlib[bcrypt]" & ➕1️⃣ 1️⃣ 🔓 & 📨 👩💻. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="6 47 54-55 58-59 68-74" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="6 47 54-55 58-59 68-74" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// note -!!! note - 🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// ## 🍵 🥙 🤝 @@ -152,17 +168,21 @@ $ openssl rand -hex 32 ✍ 🚙 🔢 🏗 🆕 🔐 🤝. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="5 11-13 27-29 77-85" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="5 11-13 27-29 77-85" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// ## ℹ 🔗 @@ -172,17 +192,21 @@ $ openssl rand -hex 32 🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="88-105" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="88-105" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// ## ℹ `/token` *➡ 🛠️* @@ -190,17 +214,21 @@ $ openssl rand -hex 32 ✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="114-129" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="114-129" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// ### 📡 ℹ 🔃 🥙 "📄" `sub` @@ -239,8 +267,11 @@ $ openssl rand -hex 32 🆔: `johndoe` 🔐: `secret` -!!! check - 👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. +/// check + +👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. + +/// <img src="/img/tutorial/security/image08.png"> @@ -261,8 +292,11 @@ $ openssl rand -hex 32 <img src="/img/tutorial/security/image10.png"> -!!! note - 👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. +/// note + +👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. + +/// ## 🏧 ⚙️ ⏮️ `scopes` diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index b9e3deb3c..937546be8 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/ * `instagram_basic` ⚙️ 👱📔 / 👱📔. * `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍. -!!! info - Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. +/// info - ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. +Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. - 👈 ℹ 🛠️ 🎯. +⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. - Oauth2️⃣ 👫 🎻. +👈 ℹ 🛠️ 🎯. + +Oauth2️⃣ 👫 🎻. + +/// ## 📟 🤚 `username` & `password` @@ -49,17 +52,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/ 🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// `OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️: @@ -68,29 +75,38 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/ * 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀. * 📦 `grant_type`. -!!! tip - Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. +/// tip + +Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. - 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. +🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. + +/// * 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼). * 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼). -!!! info - `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. +/// info + +`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. - `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. +`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. - ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. +✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. - ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. +✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. + +/// ### ⚙️ 📨 💽 -!!! tip - 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. +/// tip + +👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. + +👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. - 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. +/// 🔜, 🤚 👩💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑. @@ -98,17 +114,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/ ❌, 👥 ⚙️ ⚠ `HTTPException`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// ### ✅ 🔐 @@ -134,17 +154,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/ , 🧙♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// #### 🔃 `**user_dict` @@ -162,8 +186,11 @@ UserInDB( ) ``` -!!! info - 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}. +/// info + +🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}. + +/// ## 📨 🤝 @@ -175,31 +202,41 @@ UserInDB( 👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝. -!!! tip - ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & <abbr title="JSON Web Tokens">🥙</abbr> 🤝. +/// tip + +⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & <abbr title="JSON Web Tokens">🥙</abbr> 🤝. + +✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. + +/// + +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.6️⃣ & 🔛" +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. -!!! tip - 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. +👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. - 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. +⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. - ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. +🎂, **FastAPI** 🍵 ⚫️ 👆. - 🎂, **FastAPI** 🍵 ⚫️ 👆. +/// ## ℹ 🔗 @@ -213,32 +250,39 @@ UserInDB( , 👆 🔗, 👥 🔜 🕴 🤚 👩💻 🚥 👩💻 🔀, ☑ 🔓, & 🦁: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="55-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="55-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. -!!! info - 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. +🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. - 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. +💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. - 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. +👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. - 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. +✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. - ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. +, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮. - , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮. +👈 💰 🐩... - 👈 💰 🐩... +/// ## 👀 ⚫️ 🎯 diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 5a5227352..2492c8708 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -18,13 +18,19 @@ ⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. -!!! tip - 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> +/// tip -!!! note - 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. +📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> - **FastAPI** 🎯 📟 🤪 🕧. +/// + +/// note + +👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. + + **FastAPI** 🎯 📟 🤪 🕧. + +/// ## 🐜 @@ -58,8 +64,11 @@ 🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜. -!!! tip - 📤 🌓 📄 ⚙️ 🏒 📥 🩺. +/// tip + +📤 🌓 📄 ⚙️ 🏒 📥 🩺. + +/// ## 📁 📊 @@ -124,9 +133,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏). -!!! tip +/// tip - 👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. +👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. + +/// ### ✍ 🇸🇲 `engine` @@ -148,15 +159,17 @@ connect_args={"check_same_thread": False} ...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. -!!! info "📡 ℹ" +/// info | "📡 ℹ" + +🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. - 🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. +👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). - 👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). +✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. - ✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. +, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅♂ 💪 👈 🔢 🛠️. - , 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅♂ 💪 👈 🔢 🛠️. +/// ### ✍ `SessionLocal` 🎓 @@ -192,10 +205,13 @@ connect_args={"check_same_thread": False} 👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷. -!!! tip - 🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. +/// tip + +🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. +✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. + +/// 🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛). @@ -245,12 +261,15 @@ connect_args={"check_same_thread": False} 🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. -!!! tip - ❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. +/// tip + +❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. + +👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). +👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️. - 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️. +/// ### ✍ ▶️ Pydantic *🏷* / 🔗 @@ -262,23 +281,29 @@ connect_args={"check_same_thread": False} ✋️ 💂♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩💻. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// #### 🇸🇲 👗 & Pydantic 👗 @@ -306,26 +331,35 @@ name: str 🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="13-15 29-32" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. -!!! tip - 👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. +/// ### ⚙️ Pydantic `orm_mode` @@ -335,32 +369,41 @@ name: str `Config` 🎓, ⚒ 🔢 `orm_mode = True`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="13 17-18 29 34-35" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: -!!! tip - 👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: +`orm_mode = True` - `orm_mode = True` +⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. - ⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. +👉 ⚒ 📁 💲, 🚫 📣 🆎. - 👉 ⚒ 📁 💲, 🚫 📣 🆎. +/// Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢). @@ -426,8 +469,11 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">⚒ 💯</abbr> 👫. +/// tip + +🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">⚒ 💯</abbr> 👫. + +/// ### ✍ 💽 @@ -444,34 +490,43 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. +/// tip - ✋️ ⚫️❔ 🛠️ 👩💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. +🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. - & ⤴️ 🚶♀️ `hashed_password` ❌ ⏮️ 💲 🖊. +✋️ ⚫️❔ 🛠️ 👩💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. -!!! warning - 👉 🖼 🚫 🔐, 🔐 🚫#️⃣. + & ⤴️ 🚶♀️ `hashed_password` ❌ ⏮️ 💲 🖊. - 🎰 👨❤👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. +/// - 🌅 ℹ, 🚶 🔙 💂♂ 📄 🔰. +/// warning - 📥 👥 🎯 🕴 🔛 🧰 & 👨🔧 💽. +👉 🖼 🚫 🔐, 🔐 🚫#️⃣. -!!! tip - ↩️ 🚶♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: +🎰 👨❤👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. - `item.dict()` +🌅 ℹ, 🚶 🔙 💂♂ 📄 🔰. - & ⤴️ 👥 🚶♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: +📥 👥 🎯 🕴 🔛 🧰 & 👨🔧 💽. - `Item(**item.dict())` +/// - & ⤴️ 👥 🚶♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: +/// tip - `Item(**item.dict(), owner_id=user_id)` +↩️ 🚶♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: + +`item.dict()` + + & ⤴️ 👥 🚶♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: + +`Item(**item.dict())` + + & ⤴️ 👥 🚶♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: + +`Item(**item.dict(), owner_id=user_id)` + +/// ## 👑 **FastAPI** 📱 @@ -481,17 +536,21 @@ current_user.items 📶 🙃 🌌 ✍ 💽 🏓: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// #### ⚗ 🗒 @@ -515,63 +574,81 @@ current_user.items 👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15-20" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="13-18" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. + & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. +👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. +✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} - ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} +/// & ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. 👉 🔜 ⤴️ 🤝 👥 👍 👨🎨 🐕🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="24 32 38 47 53" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="22 30 36 45 51" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info | "📡 ℹ" - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚. -!!! info "📡 ℹ" - 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚. +✋️ 📣 🆎 `Session`, 👨🎨 🔜 💪 💭 💪 👩🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. - ✋️ 📣 🆎 `Session`, 👨🎨 🔜 💪 💭 💪 👩🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. +/// ### ✍ 👆 **FastAPI** *➡ 🛠️* 🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// 👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️. @@ -579,15 +656,21 @@ current_user.items ⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉. -!!! tip - 👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. +/// tip + +👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. + +✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬. + +/// + +/// tip - ✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬. +👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. -!!! tip - 👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. +✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩💻 🛎, 🍵 ⚠. - ✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩💻 🛎, 🍵 ⚠. +/// ### 🔃 `def` 🆚 `async def` @@ -616,11 +699,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - 🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. +/// info -!!! note "📶 📡 ℹ" - 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. +🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. + +/// + +/// note | "📶 📡 ℹ" + +🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. + +/// ## 🛠️ @@ -654,23 +743,29 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/schemas.py`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// * `sql_app/crud.py`: @@ -680,25 +775,31 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/main.py`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// ## ✅ ⚫️ 👆 💪 📁 👉 📟 & ⚙️ ⚫️. -!!! info +/// info + +👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. - 👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. +/// ⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn: @@ -739,24 +840,31 @@ $ uvicorn sql_app.main:app --reload 🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="14-22" +{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +```Python hl_lines="12-20" +{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. + & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. +👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. +/// ### 🔃 `request.state` @@ -777,10 +885,16 @@ $ uvicorn sql_app.main:app --reload * , 🔗 🔜 ✍ 🔠 📨. * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽. -!!! tip - ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. +/// tip + +⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. + +/// + +/// info + +🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. -!!! info - 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. +⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. - ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. +/// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 6090c5338..3305746c2 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. +/// note | "📡 ℹ" - **FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. + +**FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. + +/// ### ⚫️❔ "🗜" diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 3ae51e298..75dd2d295 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## ⚙️ `TestClient` -!!! info - ⚙️ `TestClient`, 🥇 ❎ <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. +/// info - 🤶 Ⓜ. `pip install httpx`. +⚙️ `TestClient`, 🥇 ❎ <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. + +🤶 Ⓜ. `pip install httpx`. + +/// 🗄 `TestClient`. @@ -27,20 +30,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip - 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. +/// tip + +👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. + + & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`. + +👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. + +/// + +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.testclient import TestClient`. - & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`. +**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. +/// -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.testclient import TestClient`. +/// tip - **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. -!!! tip - 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. +/// ## 🎏 💯 @@ -110,17 +122,21 @@ 👯♂️ *➡ 🛠️* 🚚 `X-Token` 🎚. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// ### ↔ 🔬 📁 @@ -144,10 +160,13 @@ 🌖 ℹ 🔃 ❔ 🚶♀️ 💽 👩💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ <a href="https://www.python-httpx.org" class="external-link" target="_blank">🇸🇲 🧾</a>. -!!! info - 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. +/// info + +🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. + +🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. - 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. +/// ## 🏃 ⚫️ diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 88d27018c..95ca90f6b 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Additional Responses in OpenAPI -!!! warning - This is a rather advanced topic. +/// warning - If you are starting with **FastAPI**, you might not need this. +This is a rather advanced topic. + +If you are starting with **FastAPI**, you might not need this. + +/// You can declare additional responses, with additional status codes, media types, descriptions, etc. @@ -27,20 +30,26 @@ For example, to declare another response with a status code `404` and a Pydantic {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note - Keep in mind that you have to return the `JSONResponse` directly. +/// note + +Keep in mind that you have to return the `JSONResponse` directly. + +/// + +/// info -!!! info - The `model` key is not part of OpenAPI. +The `model` key is not part of OpenAPI. - **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. +**FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. - The correct place is: +The correct place is: - * In the key `content`, that has as value another JSON object (`dict`) that contains: - * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: - * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. - * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. +* In the key `content`, that has as value another JSON object (`dict`) that contains: + * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: + * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. + * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. + +/// The generated responses in the OpenAPI for this *path operation* will be: @@ -172,13 +181,19 @@ For example, you can add an additional media type of `image/png`, declaring that {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note - Notice that you have to return the image using a `FileResponse` directly. +/// note + +Notice that you have to return the image using a `FileResponse` directly. + +/// + +/// info + +Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). -!!! info - Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). +But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. - But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. +/// ## Combining information diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 0ce275343..99ad72b53 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -14,53 +14,75 @@ But you also want it to accept new items. And when the items didn't exist before To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 26" +{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +``` - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! warning - When you return a `Response` directly, like in the example above, it will be returned directly. +/// - It won't be serialized with a model, etc. +```Python hl_lines="2 23" +{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` - Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). +//// -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. +//// tab | Python 3.8+ non-Annotated - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning + +When you return a `Response` directly, like in the example above, it will be returned directly. + +It won't be serialized with a model, etc. + +Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). + +/// + +/// note | "Technical Details" + +You could also use `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. + +/// ## OpenAPI and API docs diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index 0cffab56d..f65e1b180 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -18,26 +18,35 @@ Not the class itself (which is already a callable), but an instance of that clas To do that, we declare a method `__call__`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later. @@ -45,26 +54,35 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code. @@ -72,26 +90,35 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use We could create an instance of this class with: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`. @@ -107,32 +134,44 @@ checker(q="somequery") ...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +All this might seem contrived. And it might not be very clear how is it useful yet. -!!! tip - All this might seem contrived. And it might not be very clear how is it useful yet. +These examples are intentionally simple, but show how it all works. - These examples are intentionally simple, but show how it all works. +In the chapters about security, there are utility functions that are implemented in this same way. - In the chapters about security, there are utility functions that are implemented in this same way. +If you understood all this, you already know how those utility tools for security work underneath. - If you understood all this, you already know how those utility tools for security work underneath. +/// diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index f9c82e6ab..ac459ff0c 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ The marker `@pytest.mark.anyio` tells pytest that this test function should be c {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip - Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. +/// tip + +Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. + +/// Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. @@ -81,15 +84,24 @@ response = client.get('/') ...that we used to make our requests with the `TestClient`. -!!! tip - Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. +/// tip + +Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. + +/// -!!! warning - If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. +/// warning + +If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. + +/// ## Other Asynchronous Function Calls As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code. -!!! tip - If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDB's MotorClient</a>) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. +/// tip + +If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDB's MotorClient</a>) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. + +/// diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index c17b024f9..0447a7220 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -43,8 +43,11 @@ browser --> proxy proxy --> server ``` -!!! tip - The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. +/// tip + +The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. + +/// The docs UI would also need the OpenAPI schema to declare that this API `server` is located at `/api/v1` (behind the proxy). For example: @@ -81,10 +84,13 @@ $ fastapi run main.py --root-path /api/v1 If you use Hypercorn, it also has the option `--root-path`. -!!! note "Technical Details" - The ASGI specification defines a `root_path` for this use case. +/// note | "Technical Details" + +The ASGI specification defines a `root_path` for this use case. + +And the `--root-path` command line option provides that `root_path`. - And the `--root-path` command line option provides that `root_path`. +/// ### Checking the current `root_path` @@ -172,8 +178,11 @@ Then create a file `traefik.toml` with: This tells Traefik to listen on port 9999 and to use another file `routes.toml`. -!!! tip - We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. +/// tip + +We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. + +/// Now create that other file `routes.toml`: @@ -239,8 +248,11 @@ Now, if you go to the URL with the port for Uvicorn: <a href="http://127.0.0.1:8 } ``` -!!! tip - Notice that even though you are accessing it at `http://127.0.0.1:8000/app` it shows the `root_path` of `/api/v1`, taken from the option `--root-path`. +/// tip + +Notice that even though you are accessing it at `http://127.0.0.1:8000/app` it shows the `root_path` of `/api/v1`, taken from the option `--root-path`. + +/// And now open the URL with the port for Traefik, including the path prefix: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>. @@ -283,8 +295,11 @@ This is because FastAPI uses this `root_path` to create the default `server` in ## Additional servers -!!! warning - This is a more advanced use case. Feel free to skip it. +/// warning + +This is a more advanced use case. Feel free to skip it. + +/// By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`. @@ -323,15 +338,21 @@ Will generate an OpenAPI schema like: } ``` -!!! tip - Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. +/// tip + +Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. + +/// In the docs UI at <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> it would look like: <img src="/img/tutorial/behind-a-proxy/image03.png"> -!!! tip - The docs UI will interact with the server that you select. +/// tip + +The docs UI will interact with the server that you select. + +/// ### Disable automatic server from `root_path` diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 1d12173a1..f31127efe 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ The contents that you return from your *path operation function* will be put ins And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*. -!!! note - If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. +/// note + +If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. + +/// ## Use `ORJSONResponse` @@ -31,15 +34,21 @@ But if you are certain that the content that you are returning is **serializable {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +/// info + +The parameter `response_class` will also be used to define the "media type" of the response. + +In this case, the HTTP header `Content-Type` will be set to `application/json`. - In this case, the HTTP header `Content-Type` will be set to `application/json`. +And it will be documented as such in OpenAPI. - And it will be documented as such in OpenAPI. +/// -!!! tip - The `ORJSONResponse` is only available in FastAPI, not in Starlette. +/// tip + +The `ORJSONResponse` is only available in FastAPI, not in Starlette. + +/// ## HTML Response @@ -52,12 +61,15 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +/// info + +The parameter `response_class` will also be used to define the "media type" of the response. - In this case, the HTTP header `Content-Type` will be set to `text/html`. +In this case, the HTTP header `Content-Type` will be set to `text/html`. - And it will be documented as such in OpenAPI. +And it will be documented as such in OpenAPI. + +/// ### Return a `Response` @@ -69,11 +81,17 @@ The same example from above, returning an `HTMLResponse`, could look like: {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning - A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. +/// warning + +A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. + +/// -!!! info - Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned. +/// info + +Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned. + +/// ### Document in OpenAPI and override `Response` @@ -103,10 +121,13 @@ Here are some of the available responses. Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. -!!! note "Technical Details" - You could also use `from starlette.responses import HTMLResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import HTMLResponse`. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +/// ### `Response` @@ -149,25 +170,37 @@ This is the default response used in **FastAPI**, as you read above. A fast alternative JSON response using <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>, as you read above. -!!! info - This requires installing `orjson` for example with `pip install orjson`. +/// info + +This requires installing `orjson` for example with `pip install orjson`. + +/// ### `UJSONResponse` An alternative JSON response using <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>. -!!! info - This requires installing `ujson` for example with `pip install ujson`. +/// info + +This requires installing `ujson` for example with `pip install ujson`. + +/// + +/// warning + +`ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. -!!! warning - `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip - It's possible that `ORJSONResponse` might be a faster alternative. +/// tip + +It's possible that `ORJSONResponse` might be a faster alternative. + +/// ### `RedirectResponse` @@ -228,8 +261,11 @@ This includes many libraries to interact with cloud storage, video processing, a By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing. -!!! tip - Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. +/// tip + +Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. + +/// ### `FileResponse` @@ -298,8 +334,11 @@ In the example below, **FastAPI** will use `ORJSONResponse` by default, in all * {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip - You can still override `response_class` in *path operations* as before. +/// tip + +You can still override `response_class` in *path operations* as before. + +/// ## Additional documentation diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 286e8f93f..252ab6fa5 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -20,12 +20,15 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. -!!! info - Keep in mind that dataclasses can't do everything Pydantic models can do. +/// info - So, you might still need to use Pydantic models. +Keep in mind that dataclasses can't do everything Pydantic models can do. - But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 +So, you might still need to use Pydantic models. + +But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 + +/// ## Dataclasses in `response_model` diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 703fcb7ae..7fd934344 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -38,10 +38,13 @@ Here we are simulating the expensive *startup* operation of loading the model by And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU. -!!! tip - The `shutdown` would happen when you are **stopping** the application. +/// tip - Maybe you need to start a new version, or you just got tired of running it. 🤷 +The `shutdown` would happen when you are **stopping** the application. + +Maybe you need to start a new version, or you just got tired of running it. 🤷 + +/// ### Lifespan function @@ -91,10 +94,13 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager** ## Alternative Events (deprecated) -!!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. +/// warning + +The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. - You can probably skip this part. +You can probably skip this part. + +/// There's an alternative way to define this logic to be executed during *startup* and during *shutdown*. @@ -126,17 +132,23 @@ To add a function that should be run when the application is shutting down, decl Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. -!!! info - In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. +/// info + +In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. -!!! tip - Notice that in this case we are using a standard Python `open()` function that interacts with a file. +/// - So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. +/// tip - But `open()` doesn't use `async` and `await`. +Notice that in this case we are using a standard Python `open()` function that interacts with a file. - So, we declare the event handler function with standard `def` instead of `async def`. +So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. + +But `open()` doesn't use `async` and `await`. + +So, we declare the event handler function with standard `def` instead of `async def`. + +/// ### `startup` and `shutdown` together @@ -152,10 +164,13 @@ Just a technical detail for the curious nerds. 🤓 Underneath, in the ASGI technical specification, this is part of the <a href="https://asgi.readthedocs.io/en/latest/specs/lifespan.html" class="external-link" target="_blank">Lifespan Protocol</a>, and it defines events called `startup` and `shutdown`. -!!! info - You can read more about the Starlette `lifespan` handlers in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlette's Lifespan' docs</a>. +/// info + +You can read more about the Starlette `lifespan` handlers in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlette's Lifespan' docs</a>. + +Including how to handle lifespan state that can be used in other areas of your code. - Including how to handle lifespan state that can be used in other areas of your code. +/// ## Sub Applications diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 0053ac9bb..faa7c323f 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -32,17 +32,21 @@ There are also several other companies offering similar services that you can se Let's start with a simple FastAPI application: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` + +//// Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`. @@ -127,8 +131,11 @@ You will also get autocompletion for the payload to send: <img src="/img/tutorial/generate-clients/image03.png"> -!!! tip - Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. +/// tip + +Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. + +/// You will have inline errors for the data that you send: @@ -144,17 +151,21 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to For example, you could have a section for **items** and another section for **users**, and they could be separated by tags: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### Generate a TypeScript Client with Tags @@ -201,17 +212,21 @@ For example, here it is using the first tag (you will probably have only one tag You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### Generate a TypeScript Client with Custom Operation IDs @@ -233,17 +248,21 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -=== "Python" +//// tab | Python - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.py!} - ``` +```Python +{!> ../../../docs_src/generate_clients/tutorial004.py!} +``` + +//// -=== "Node.js" +//// tab | Node.js + +```Javascript +{!> ../../../docs_src/generate_clients/tutorial004.js!} +``` - ```Javascript - {!> ../../../docs_src/generate_clients/tutorial004.js!} - ``` +//// With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names. diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index 86e42fba0..36f0720c0 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -6,10 +6,13 @@ The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_bl In the next sections you will see other options, configurations, and additional features. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 9219f1d2c..4b273fd89 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** includes several middlewares for common use cases, we'll see next how to use them. -!!! note "Technical Details" - For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. +/// note | "Technical Details" - **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. +For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 1ff51f077..e74af3d3e 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -35,8 +35,11 @@ This part is pretty normal, most of the code is probably already familiar to you {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">URL</a> type. +/// tip + +The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">URL</a> type. + +/// The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. @@ -61,10 +64,13 @@ That documentation will show up in the Swagger UI at `/docs` in your API, and it This example doesn't implement the callback itself (that could be just a line of code), only the documentation part. -!!! tip - The actual callback is just an HTTP request. +/// tip + +The actual callback is just an HTTP request. - When implementing the callback yourself, you could use something like <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> or <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>. +When implementing the callback yourself, you could use something like <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> or <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>. + +/// ## Write the callback documentation code @@ -74,10 +80,13 @@ But, you already know how to easily create automatic documentation for an API wi So we are going to use that same knowledge to document how the *external API* should look like... by creating the *path operation(s)* that the external API should implement (the ones your API will call). -!!! tip - When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. +/// tip + +When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. - Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. +Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. + +/// ### Create a callback `APIRouter` @@ -154,8 +163,11 @@ and it would expect a response from that *external API* with a JSON body like: } ``` -!!! tip - Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). +/// tip + +Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). + +/// ### Add the callback router @@ -167,8 +179,11 @@ Now use the parameter `callbacks` in *your API's path operation decorator* to pa {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. +/// tip + +Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. + +/// ### Check the docs diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index f7f43b357..5ee321e2a 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -22,8 +22,11 @@ With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code. -!!! info - Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. +/// info + +Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. + +/// ## An app with webhooks @@ -35,8 +38,11 @@ When you create a **FastAPI** application, there is a `webhooks` attribute that The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. -!!! info - The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. +/// info + +The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. + +/// Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`. diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 35f7d1b8d..c8874bad9 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning - If you are not an "expert" in OpenAPI, you probably don't need this. +/// warning + +If you are not an "expert" in OpenAPI, you probably don't need this. + +/// You can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`. @@ -23,13 +26,19 @@ You should do it after adding all your *path operations*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip - If you manually call `app.openapi()`, you should update the `operationId`s before that. +/// tip + +If you manually call `app.openapi()`, you should update the `operationId`s before that. + +/// + +/// warning + +If you do this, you have to make sure each one of your *path operation functions* has a unique name. -!!! warning - If you do this, you have to make sure each one of your *path operation functions* has a unique name. +Even if they are in different modules (Python files). - Even if they are in different modules (Python files). +/// ## Exclude from OpenAPI @@ -65,8 +74,11 @@ There's a whole chapter here in the documentation about it, you can read it at [ When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema. -!!! note "Technical details" - In the OpenAPI specification it is called the <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operation Object</a>. +/// note | "Technical details" + +In the OpenAPI specification it is called the <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operation Object</a>. + +/// It has all the information about the *path operation* and is used to generate the automatic documentation. @@ -74,10 +86,13 @@ It includes the `tags`, `parameters`, `requestBody`, `responses`, etc. This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it. -!!! tip - This is a low level extension point. +/// tip + +This is a low level extension point. - If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. +If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`. @@ -150,20 +165,27 @@ And you could do this even if the data type in the request is not JSON. For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +//// -=== "Pydantic v1" +/// info - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. -!!! info - In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. +/// Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. @@ -171,22 +193,32 @@ Then we use the request directly, and extract the body as `bytes`. This means th And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. -=== "Pydantic v1" +/// - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +/// tip -!!! info - In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. +Here we reuse the same Pydantic model. -!!! tip - Here we reuse the same Pydantic model. +But the same way, we could have validated it in some other way. - But the same way, we could have validated it in some other way. +/// diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index d53985dbb..85e423f42 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -30,20 +30,26 @@ Then set Cookies in it, and then return it: {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip - Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. +/// tip - So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. +Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. - And also that you are not sending any data that should have been filtered by a `response_model`. +So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. + +And also that you are not sending any data that should have been filtered by a `response_model`. + +/// ### More info -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +/// To see all the available parameters and options, check the <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">documentation in Starlette</a>. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 8836140ec..33e10d091 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ It might be useful, for example, to return custom headers or cookies. In fact, you can return any `Response` or any sub-class of it. -!!! tip - `JSONResponse` itself is a sub-class of `Response`. +/// tip + +`JSONResponse` itself is a sub-class of `Response`. + +/// And when you return a `Response`, **FastAPI** will pass it directly. @@ -35,10 +38,13 @@ For those cases, you can use the `jsonable_encoder` to convert your data before {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ## Returning a custom `Response` diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index 49b5fe476..acbb6d7e5 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -28,12 +28,15 @@ Create a response as described in [Return a Response Directly](response-directly {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | "Technical Details" - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. + +/// ## Custom Headers diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 680f4dff5..c302bf8dc 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,35 @@ Then, when you type that username and password, the browser sends them in the he * It returns an object of type `HTTPBasicCredentials`: * It contains the `username` and `password` sent. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` +```Python hl_lines="4 8 12" +{!> ../../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../../docs_src/security/tutorial006_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +```Python hl_lines="2 6 10" +{!> ../../../docs_src/security/tutorial006.py!} +``` + +//// When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password: @@ -59,26 +68,35 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1 11-21" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// This would be similar to: @@ -142,23 +160,32 @@ That way, using `secrets.compare_digest()` in your application code, it will be After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="23-27" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md index c9ede4231..edb42132e 100644 --- a/docs/en/docs/advanced/security/index.md +++ b/docs/en/docs/advanced/security/index.md @@ -4,10 +4,13 @@ There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 9a9c0dff9..69b8fa7d2 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application. -!!! warning - This is a more or less advanced section. If you are just starting, you can skip it. +/// warning - You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. +This is a more or less advanced section. If you are just starting, you can skip it. - But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. +You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. - Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. +But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. - In many cases, OAuth2 with scopes can be an overkill. +Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. - But if you know you need it, or you are curious, keep reading. +In many cases, OAuth2 with scopes can be an overkill. + +But if you know you need it, or you are curious, keep reading. + +/// ## OAuth2 scopes and OpenAPI @@ -43,63 +46,87 @@ They are normally used to declare specific security permissions, for example: * `instagram_basic` is used by Facebook / Instagram. * `https://www.googleapis.com/auth/drive` is used by Google. -!!! info - In OAuth2 a "scope" is just a string that declares a specific permission required. +/// info + +In OAuth2 a "scope" is just a string that declares a specific permission required. + +It doesn't matter if it has other characters like `:` or if it is a URL. - It doesn't matter if it has other characters like `:` or if it is a URL. +Those details are implementation specific. - Those details are implementation specific. +For OAuth2 they are just strings. - For OAuth2 they are just strings. +/// ## Global view First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.9+" +/// - ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +/// -=== "Python 3.9+ non-Annotated" +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Now let's review those changes step by step. @@ -109,51 +136,71 @@ The first change is that now we are declaring the OAuth2 security scheme with tw The `scopes` parameter receives a `dict` with each scope as a key and the description as the value: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="64-67" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="64-67" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.9+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize. @@ -171,55 +218,79 @@ We are still using the same `OAuth2PasswordRequestForm`. It includes a property And we return the scopes as part of the JWT token. -!!! danger - For simplicity, here we are just adding the scopes received directly to the token. +/// danger + +For simplicity, here we are just adding the scopes received directly to the token. - But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. +But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. -=== "Python 3.10+" +/// - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.9+" +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.9+ - ```Python hl_lines="157" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` -=== "Python 3.9+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Declare scopes in *path operations* and dependencies @@ -237,62 +308,89 @@ And the dependency function `get_current_active_user` can also declare sub-depen In this case, it requires the scope `me` (it could require more than one scope). -!!! note - You don't necessarily need to add different scopes in different places. +/// note + +You don't necessarily need to add different scopes in different places. + +We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 141 172" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+" +/// - ```Python hl_lines="5 140 171" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="5 140 171" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="5 141 172" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="5 140 169" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="5 140 169" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// -!!! info "Technical Details" - `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. +/// info | "Technical Details" - But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. +`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. - But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. +But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. + +But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. + +/// ## Use `SecurityScopes` @@ -308,50 +406,71 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 107" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="9 107" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// ## Use the `scopes` @@ -365,50 +484,71 @@ We create an `HTTPException` that we can reuse (`raise`) later at several points In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` - ```Python hl_lines="107 109-117" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="107 109-117" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Verify the `username` and data shape @@ -424,50 +564,71 @@ Instead of, for example, a `dict`, or something else, as it could break the appl We also verify that we have a user with that username, and if not, we raise that same exception we created before. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="48 118-129" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="48 118-129" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Verify the `scopes` @@ -475,50 +636,71 @@ We now verify that all the scopes required, by this dependency and all the depen For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="130-136" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="130-136" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.9+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.9+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Dependency tree and scopes @@ -545,10 +727,13 @@ Here's how the hierarchy of dependencies and scopes looks like: * `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`. * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either. -!!! tip - The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. +/// tip + +The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. - All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. +All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. + +/// ## More details about `SecurityScopes` @@ -586,10 +771,13 @@ The most common is the implicit flow. The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. -!!! note - It's common that each authentication provider names their flows in a different way, to make it part of their brand. +/// note + +It's common that each authentication provider names their flows in a different way, to make it part of their brand. + +But in the end, they are implementing the same OAuth2 standard. - But in the end, they are implementing the same OAuth2 standard. +/// **FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`. diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 56af4f441..b77557361 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -8,44 +8,51 @@ For this reason it's common to provide them in environment variables that are re ## Environment Variables -!!! tip - If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. +/// tip + +If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. + +/// An <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">environment variable</a> (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). You can create and use environment variables in the shell, without needing Python: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - // You could create an env var MY_NAME with - $ export MY_NAME="Wade Wilson" +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" - // Then you could use it with other programs, like - $ echo "Hello $MY_NAME" +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +</div> - Hello Wade Wilson - ``` +//// - </div> +//// tab | Windows PowerShell -=== "Windows PowerShell" +<div class="termy"> - <div class="termy"> +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Create an env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" - // Use it with other programs, like - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +</div> - </div> +//// ### Read env vars in Python @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return. +/// tip + +The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return. - If not provided, it's `None` by default, here we provide `"World"` as the default value to use. +If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +/// Then you could call that Python program: @@ -114,8 +124,11 @@ Hello World from Python </div> -!!! tip - You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>. +/// tip + +You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>. + +/// ### Types and validation @@ -151,8 +164,11 @@ $ pip install "fastapi[all]" </div> -!!! info - In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. +/// info + +In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. + +/// ### Create the `Settings` object @@ -162,23 +178,33 @@ The same way as with Pydantic models, you declare class attributes with type ann You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +/// info + +In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001_pv1.py!} +``` -=== "Pydantic v1" +//// - !!! info - In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. +/// tip - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +If you want something quick to copy and paste, don't use this example, use the last one below. -!!! tip - If you want something quick to copy and paste, don't use this example, use the last one below. +/// Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`. @@ -206,8 +232,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p </div> -!!! tip - To set multiple env vars for a single command just separate them with a space, and put them all before the command. +/// tip + +To set multiple env vars for a single command just separate them with a space, and put them all before the command. + +/// And then the `admin_email` setting would be set to `"deadpool@example.com"`. @@ -231,8 +260,11 @@ And then use it in a file `main.py`: {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip - You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. +/// tip + +You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +/// ## Settings in a dependency @@ -254,54 +286,75 @@ Notice that now we don't create a default instance `settings = Settings()`. Now we create a dependency that returns a new `config.Settings()`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +/// tip -!!! tip - We'll discuss the `@lru_cache` in a bit. +Prefer to use the `Annotated` version if possible. - For now you can assume `get_settings()` is a normal function. +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// + +/// tip + +We'll discuss the `@lru_cache` in a bit. + +For now you can assume `get_settings()` is a normal function. + +/// And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// ### Settings and testing @@ -321,15 +374,21 @@ If you have many settings that possibly change a lot, maybe in different environ This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv". -!!! tip - A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. +/// tip + +A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. - But a dotenv file doesn't really have to have that exact filename. +But a dotenv file doesn't really have to have that exact filename. + +/// Pydantic has support for reading from these types of files using an external library. You can read more at <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>. -!!! tip - For this to work, you need to `pip install python-dotenv`. +/// tip + +For this to work, you need to `pip install python-dotenv`. + +/// ### The `.env` file @@ -344,26 +403,39 @@ APP_NAME="ChimichangApp" And then update your `config.py` with: -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/settings/app03_an/config.py!} +``` - !!! tip - The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. +/// tip -=== "Pydantic v1" +The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +/// - !!! tip - The `Config` class is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. +//// -!!! info - In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// tip + +The `Config` class is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. + +/// + +//// + +/// info + +In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. + +/// Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use. @@ -390,26 +462,35 @@ we would create that object for each request, and we would be reading the `.env` But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 4a577215a..43731ec36 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -31,18 +31,27 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note - Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. +/// note - Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. +Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. -!!! tip - By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. +Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. -!!! note "Technical Details" - You could also use `from starlette.templating import Jinja2Templates`. +/// - **FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. +/// tip + +By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. + +/// + +/// note | "Technical Details" + +You could also use `from starlette.templating import Jinja2Templates`. + +**FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. + +/// ## Writing templates diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md index 1c0669b9c..974cf4caa 100644 --- a/docs/en/docs/advanced/testing-database.md +++ b/docs/en/docs/advanced/testing-database.md @@ -1,11 +1,14 @@ # Testing a Database -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. +These docs are about to be updated. 🎉 - The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. +The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. + +The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. + +/// You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. @@ -59,10 +62,13 @@ But the rest of the session code is more or less the same, we just copy it. {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. +/// tip + +You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. - For simplicity and to focus on the specific testing code, we are just copying it. +For simplicity and to focus on the specific testing code, we are just copying it. + +/// ## Create the database @@ -88,8 +94,11 @@ Now we create the dependency override and add it to the overrides for our app. {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. +/// tip + +The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. + +/// ## Test the app diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 57dd87f56..92e25f88d 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -28,48 +28,67 @@ To override a dependency for testing, you put as a key the original dependency ( And then **FastAPI** will call that override instead of the original dependency. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="26-27 30" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} - ``` +```Python hl_lines="26-27 30" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="29-30 33" - {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="24-25 28" +{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="24-25 28" - {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001.py!} +``` - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001.py!} - ``` +//// -!!! tip - You can set a dependency override for a dependency used anywhere in your **FastAPI** application. +/// tip - The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. +You can set a dependency override for a dependency used anywhere in your **FastAPI** application. - FastAPI will still be able to override it. +The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. + +FastAPI will still be able to override it. + +/// Then you can reset your overrides (remove them) by setting `app.dependency_overrides` to be an empty `dict`: @@ -77,5 +96,8 @@ Then you can reset your overrides (remove them) by setting `app.dependency_overr app.dependency_overrides = {} ``` -!!! tip - If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). +/// tip + +If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). + +/// diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index 4101e5a16..6c071bc19 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ For this, you use the `TestClient` in a `with` statement, connecting to the WebS {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note - For more details, check Starlette's documentation for <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">testing WebSockets</a>. +/// note + +For more details, check Starlette's documentation for <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">testing WebSockets</a>. + +/// diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 500afa34b..5473db5cb 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -35,18 +35,24 @@ For that you need to access the request directly. By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. -!!! tip - Note that in this case, we are declaring a path parameter beside the request parameter. +/// tip - So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. +Note that in this case, we are declaring a path parameter beside the request parameter. - The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. +So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. + +The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. + +/// ## `Request` documentation You can read more details about the <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request` object in the official Starlette documentation site</a>. -!!! note "Technical Details" - You could also use `from starlette.requests import Request`. +/// note | "Technical Details" + +You could also use `from starlette.requests import Request`. + +**FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. +/// diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 3b6471dd5..9655714b0 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -50,10 +50,13 @@ In your **FastAPI** application, create a `websocket`: {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.websockets import WebSocket`. +/// note | "Technical Details" - **FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. +You could also use `from starlette.websockets import WebSocket`. + +**FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. + +/// ## Await for messages and send messages @@ -112,46 +115,65 @@ In WebSocket endpoints you can import from `fastapi` and use: They work the same way as for other FastAPI endpoints/*path operations*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// + +```Python hl_lines="68-69 81" +{!> ../../../docs_src/websockets/tutorial002.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. +As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. - You can use a closing code from the <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">valid codes defined in the specification</a>. +You can use a closing code from the <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">valid codes defined in the specification</a>. + +/// ### Try the WebSockets with dependencies @@ -174,8 +196,11 @@ There you can set: * The "Item ID", used in the path. * The "Token" used as a query parameter. -!!! tip - Notice that the query `token` will be handled by a dependency. +/// tip + +Notice that the query `token` will be handled by a dependency. + +/// With that you can connect the WebSocket and then send and receive messages: @@ -185,17 +210,21 @@ With that you can connect the WebSocket and then send and receive messages: When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// To try it out: @@ -209,12 +238,15 @@ That will raise the `WebSocketDisconnect` exception, and all the other clients w Client #1596980209979 left the chat ``` -!!! tip - The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. +/// tip + +The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. + +But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. - But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. +If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a>. - If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a>. +/// ## More info diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 9a101a8a1..2ad584c95 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -30,12 +30,17 @@ It is used by many companies including Mozilla, Red Hat and Eventbrite. It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**. -!!! note - Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. +/// note +Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. -!!! check "Inspired **FastAPI** to" - Have an automatic API documentation web user interface. +/// + +/// check | "Inspired **FastAPI** to" + +Have an automatic API documentation web user interface. + +/// ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> @@ -51,11 +56,13 @@ This decoupling of parts, and being a "microframework" that could be extended to Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask. -!!! check "Inspired **FastAPI** to" - Be a micro-framework. Making it easy to mix and match the tools and parts needed. +/// check | "Inspired **FastAPI** to" - Have a simple and easy to use routing system. +Be a micro-framework. Making it easy to mix and match the tools and parts needed. +Have a simple and easy to use routing system. + +/// ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> @@ -91,11 +98,13 @@ def read_url(): See the similarities in `requests.get(...)` and `@app.get(...)`. -!!! check "Inspired **FastAPI** to" - * Have a simple and intuitive API. - * Use HTTP method names (operations) directly, in a straightforward and intuitive way. - * Have sensible defaults, but powerful customizations. +/// check | "Inspired **FastAPI** to" + +* Have a simple and intuitive API. +* Use HTTP method names (operations) directly, in a straightforward and intuitive way. +* Have sensible defaults, but powerful customizations. +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -109,15 +118,18 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI. That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI". -!!! check "Inspired **FastAPI** to" - Adopt and use an open standard for API specifications, instead of a custom schema. +/// check | "Inspired **FastAPI** to" + +Adopt and use an open standard for API specifications, instead of a custom schema. - And integrate standards-based user interface tools: +And integrate standards-based user interface tools: - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> - These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**). +These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**). + +/// ### Flask REST frameworks @@ -135,8 +147,11 @@ These features are what Marshmallow was built to provide. It is a great library, But it was created before there existed Python type hints. So, to define every <abbr title="the definition of how data should be formed">schema</abbr> you need to use specific utils and classes provided by Marshmallow. -!!! check "Inspired **FastAPI** to" - Use code to define "schemas" that provide data types and validation, automatically. +/// check | "Inspired **FastAPI** to" + +Use code to define "schemas" that provide data types and validation, automatically. + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -148,11 +163,17 @@ It uses Marshmallow underneath to do the data validation. And it was created by It's a great tool and I have used it a lot too, before having **FastAPI**. -!!! info - Webargs was created by the same Marshmallow developers. +/// info + +Webargs was created by the same Marshmallow developers. + +/// + +/// check | "Inspired **FastAPI** to" -!!! check "Inspired **FastAPI** to" - Have automatic validation of incoming request data. +Have automatic validation of incoming request data. + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -172,12 +193,17 @@ But then, we have again the problem of having a micro-syntax, inside of a Python The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete. -!!! info - APISpec was created by the same Marshmallow developers. +/// info + +APISpec was created by the same Marshmallow developers. + +/// +/// check | "Inspired **FastAPI** to" -!!! check "Inspired **FastAPI** to" - Support the open standard for APIs, OpenAPI. +Support the open standard for APIs, OpenAPI. + +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -199,11 +225,17 @@ Using it led to the creation of several Flask full-stack generators. These are t And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec was created by the same Marshmallow developers. +/// info + +Flask-apispec was created by the same Marshmallow developers. + +/// -!!! check "Inspired **FastAPI** to" - Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. +/// check | "Inspired **FastAPI** to" + +Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (and <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) @@ -219,24 +251,33 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated. -!!! check "Inspired **FastAPI** to" - Use Python types to have great editor support. +/// check | "Inspired **FastAPI** to" + +Use Python types to have great editor support. - Have a powerful dependency injection system. Find a way to minimize code repetition. +Have a powerful dependency injection system. Find a way to minimize code repetition. + +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask. -!!! note "Technical Details" - It used <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> instead of the default Python `asyncio` loop. That's what made it so fast. +/// note | "Technical Details" + +It used <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> instead of the default Python `asyncio` loop. That's what made it so fast. - It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. +It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. -!!! check "Inspired **FastAPI** to" - Find a way to have a crazy performance. +/// - That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). +/// check | "Inspired **FastAPI** to" + +Find a way to have a crazy performance. + +That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -246,12 +287,15 @@ It is designed to have functions that receive two parameters, one "request" and So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters. -!!! check "Inspired **FastAPI** to" - Find ways to get great performance. +/// check | "Inspired **FastAPI** to" - Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. +Find ways to get great performance. - Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. +Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. + +Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. + +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -269,10 +313,13 @@ The dependency injection system requires pre-registration of the dependencies an Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled. -!!! check "Inspired **FastAPI** to" - Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. +/// check | "Inspired **FastAPI** to" + +Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. - This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). +This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). + +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -288,15 +335,21 @@ It has an interesting, uncommon feature: using the same framework, it's possible As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too. -!!! info - Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files. +/// info + +Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files. + +/// -!!! check "Ideas inspiring **FastAPI**" - Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. +/// check | "Ideas inspiring **FastAPI**" - Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. +Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. - Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. +Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. + +Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. + +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5) @@ -322,23 +375,29 @@ It was no longer an API web framework, as the creator needed to focus on Starlet Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework. -!!! info - APIStar was created by Tom Christie. The same guy that created: +/// info + +APIStar was created by Tom Christie. The same guy that created: - * Django REST Framework - * Starlette (in which **FastAPI** is based) - * Uvicorn (used by Starlette and **FastAPI**) +* Django REST Framework +* Starlette (in which **FastAPI** is based) +* Uvicorn (used by Starlette and **FastAPI**) -!!! check "Inspired **FastAPI** to" - Exist. +/// - The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. +/// check | "Inspired **FastAPI** to" - And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. +Exist. - Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. +The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. - I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. +And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. + +Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. + +I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. + +/// ## Used by **FastAPI** @@ -350,10 +409,13 @@ That makes it extremely intuitive. It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great. -!!! check "**FastAPI** uses it to" - Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). +/// check | "**FastAPI** uses it to" - **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. +Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). + +**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. + +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -382,17 +444,23 @@ But it doesn't provide automatic data validation, serialization or documentation That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc. -!!! note "Technical Details" - ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. +/// note | "Technical Details" + +ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. - Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. +Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. -!!! check "**FastAPI** uses it to" - Handle all the core web parts. Adding features on top. +/// - The class `FastAPI` itself inherits directly from the class `Starlette`. +/// check | "**FastAPI** uses it to" - So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. +Handle all the core web parts. Adding features on top. + +The class `FastAPI` itself inherits directly from the class `Starlette`. + +So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -402,12 +470,15 @@ It is not a web framework, but a server. For example, it doesn't provide tools f It is the recommended server for Starlette and **FastAPI**. -!!! check "**FastAPI** recommends it as" - The main web server to run **FastAPI** applications. +/// check | "**FastAPI** recommends it as" + +The main web server to run **FastAPI** applications. + +You can combine it with Gunicorn, to have an asynchronous multi-process server. - You can combine it with Gunicorn, to have an asynchronous multi-process server. +Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. - Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. +/// ## Benchmarks and speed diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 793d691e3..43fd8e70d 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - You can only use `await` inside of functions created with `async def`. +/// note + +You can only use `await` inside of functions created with `async def`. + +/// --- @@ -136,8 +139,11 @@ You and your crush eat the burgers and have a nice time. ✨ <img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration"> -!!! info - Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -199,8 +205,11 @@ You just eat them, and you are done. ⏹ There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞 -!!! info - Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -392,12 +401,15 @@ All that is what powers FastAPI (through Starlette) and what makes it have such ## Very Technical Details -!!! warning - You can probably skip this. +/// warning + +You can probably skip this. + +These are very technical details of how **FastAPI** works underneath. - These are very technical details of how **FastAPI** works underneath. +If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. - If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. +/// ### Path operation functions diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index d7ec25dea..e86c34e48 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -24,63 +24,73 @@ That will create a directory `./env/` with the Python binaries, and then you wil Activate the new environment with: -=== "Linux, macOS" +//// tab | Linux, macOS - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +<div class="termy"> - </div> +```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +</div> + +//// + +//// tab | Windows Bash - Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): +Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): - <div class="termy"> +<div class="termy"> + +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +</div> - </div> +//// To check it worked, use: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ Get-Command pip +<div class="termy"> - some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` - </div> +</div> + +//// If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip </div> -!!! tip - Every time you install a new package with `pip` under that environment, activate the environment again. +/// tip + +Every time you install a new package with `pip` under that environment, activate the environment again. - This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. +This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. + +/// ### Install requirements using pip @@ -125,10 +138,13 @@ And if you update that local FastAPI source code when you run that Python file a That way, you don't have to "install" your local version to be able to test every change. -!!! note "Technical Details" - This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. +/// note | "Technical Details" + +This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. +That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + +/// ### Format the code @@ -170,20 +186,23 @@ It will serve the documentation on `http://127.0.0.1:8008`. That way, you can edit the documentation/source files and see the changes live. -!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip - Go into the language directory, for the main docs in English it's at `docs/en/`: +Alternatively, you can perform the same steps that scripts does manually. - ```console - $ cd docs/en/ - ``` +Go into the language directory, for the main docs in English it's at `docs/en/`: - Then run `mkdocs` in that directory: +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +Then run `mkdocs` in that directory: + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer CLI (optional) @@ -210,8 +229,11 @@ The documentation uses <a href="https://www.mkdocs.org/" class="external-link" t And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. -!!! tip - You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. +/// tip + +You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. + +/// All the documentation is in Markdown format in the directory `./docs/en/`. @@ -261,10 +283,13 @@ Here are the steps to help with translations. * Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. -!!! tip - You can <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">add comments with change suggestions</a> to existing pull requests. +/// tip + +You can <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">add comments with change suggestions</a> to existing pull requests. + +Check the docs about <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adding a pull request review</a> to approve it or request changes. - Check the docs about <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adding a pull request review</a> to approve it or request changes. +/// * Check if there's a <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. @@ -278,8 +303,11 @@ Let's say you want to translate a page for a language that already has translati In the case of Spanish, the 2-letter code is `es`. So, the directory for Spanish translations is located at `docs/es/`. -!!! tip - The main ("official") language is English, located at `docs/en/`. +/// tip + +The main ("official") language is English, located at `docs/en/`. + +/// Now run the live server for the docs in Spanish: @@ -296,20 +324,23 @@ $ python ./scripts/docs.py live es </div> -!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip + +Alternatively, you can perform the same steps that scripts does manually. - Go into the language directory, for the Spanish translations it's at `docs/es/`: +Go into the language directory, for the Spanish translations it's at `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +Then run `mkdocs` in that directory: - Then run `mkdocs` in that directory: +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// Now you can go to <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> and see your changes live. @@ -329,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Notice that the only change in the path and file name is the language code, from `en` to `es`. +/// tip + +Notice that the only change in the path and file name is the language code, from `en` to `es`. + +/// If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 @@ -365,8 +399,11 @@ That command created a file `docs/ht/mkdocs.yml` with a simple config that inher INHERIT: ../en/mkdocs.yml ``` -!!! tip - You could also simply create that file with those contents manually. +/// tip + +You could also simply create that file with those contents manually. + +/// That command also created a dummy file `docs/ht/index.md` for the main page, you can start by translating that one. diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index 9701c67d8..f917d18b3 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -151,10 +151,13 @@ And still, you would probably not want the application to stay dead because ther But in those cases with really bad errors that crash the running **process**, you would want an external component that is in charge of **restarting** the process, at least a couple of times... -!!! tip - ...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. +/// tip - So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. +...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. + +So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. + +/// You would probably want to have the thing in charge of restarting your application as an **external component**, because by that point, the same application with Uvicorn and Python already crashed, so there's nothing in the same code of the same app that could do anything about it. @@ -238,10 +241,13 @@ Here are some possible combinations and strategies: * **Cloud services** that handle this for you * The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it. -!!! tip - Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. +/// tip + +Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. + +I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. - I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. +/// ## Previous Steps Before Starting @@ -257,10 +263,13 @@ And you will have to make sure that it's a single process running those previous Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. -!!! tip - Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. +/// tip - In that case, you wouldn't have to worry about any of this. 🤷 +Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + +In that case, you wouldn't have to worry about any of this. 🤷 + +/// ### Examples of Previous Steps Strategies @@ -272,8 +281,11 @@ Here are some possible ideas: * A bash script that runs the previous steps and then starts your application * You would still need a way to start/restart *that* bash script, detect errors, etc. -!!! tip - I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. +/// tip + +I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. + +/// ## Resource Utilization diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 157a3c003..6140b1c42 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -4,8 +4,11 @@ When deploying FastAPI applications a common approach is to build a **Linux cont Using Linux containers has several advantages including **security**, **replicability**, **simplicity**, and others. -!!! tip - In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). +/// tip + +In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). + +/// <details> <summary>Dockerfile Preview 👀</summary> @@ -129,8 +132,11 @@ Successfully installed fastapi pydantic </div> -!!! info - There are other formats and tools to define and install package dependencies. +/// info + +There are other formats and tools to define and install package dependencies. + +/// ### Create the **FastAPI** Code @@ -217,8 +223,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`. -!!! tip - Review what each line does by clicking each number bubble in the code. 👆 +/// tip + +Review what each line does by clicking each number bubble in the code. 👆 + +/// You should now have a directory structure like: @@ -288,10 +297,13 @@ $ docker build -t myimage . </div> -!!! tip - Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. +/// tip + +Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. + +In this case, it's the same current directory (`.`). - In this case, it's the same current directory (`.`). +/// ### Start the Docker Container @@ -389,8 +401,11 @@ If we focus just on the **container image** for a FastAPI application (and later It could be another container, for example with <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, handling **HTTPS** and **automatic** acquisition of **certificates**. -!!! tip - Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. +/// tip + +Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. + +/// Alternatively, HTTPS could be handled by a cloud provider as one of their services (while still running the application in a container). @@ -418,8 +433,11 @@ When using containers, you would normally have some component **listening on the As this component would take the **load** of requests and distribute that among the workers in a (hopefully) **balanced** way, it is also commonly called a **Load Balancer**. -!!! tip - The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. +/// tip + +The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. + +/// And when working with containers, the same system you use to start and manage them would already have internal tools to transmit the **network communication** (e.g. HTTP requests) from that **load balancer** (that could also be a **TLS Termination Proxy**) to the container(s) with your app. @@ -498,8 +516,11 @@ If you are using containers (e.g. Docker, Kubernetes), then there are two main a If you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers. -!!! info - If you are using Kubernetes, this would probably be an <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>. +/// info + +If you are using Kubernetes, this would probably be an <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>. + +/// If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process. @@ -515,8 +536,11 @@ This image would be useful mainly in the situations described above in: [Contain * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. -!!! warning - There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). +/// warning + +There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). + +/// This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available. @@ -524,8 +548,11 @@ It has **sensible defaults**, but you can still change and update all the config It also supports running <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**previous steps before starting**</a> with a script. -!!! tip - To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +/// tip + +To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +/// ### Number of Processes on the Official Docker Image @@ -652,8 +679,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] 11. Use the `fastapi run` command to run your app. -!!! tip - Click the bubble numbers to see what each line does. +/// tip + +Click the bubble numbers to see what each line does. + +/// A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later. diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 5cf76c111..46eda791e 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -4,8 +4,11 @@ It is easy to assume that HTTPS is something that is just "enabled" or not. But it is way more complex than that. -!!! tip - If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. +/// tip + +If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. + +/// To **learn the basics of HTTPS**, from a consumer perspective, check <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>. @@ -68,8 +71,11 @@ In the DNS server(s) you would configure a record (an "`A record`") to point **y You would probably do this just once, the first time, when setting everything up. -!!! tip - This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. +/// tip + +This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. + +/// ### DNS @@ -115,8 +121,11 @@ After this, the client and the server have an **encrypted TCP connection**, this And that's what **HTTPS** is, it's just plain **HTTP** inside a **secure TLS connection** instead of a pure (unencrypted) TCP connection. -!!! tip - Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. +/// tip + +Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. + +/// ### HTTPS Request diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index ad9f62f91..d70c5e48b 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -84,89 +84,106 @@ When you install FastAPI, it comes with a production server, Uvicorn, and you ca But you can also install an ASGI server manually: -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools. +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools. - <div class="termy"> +<div class="termy"> - ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` - </div> +</div> - !!! tip - By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. +/// tip - That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. +By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. - When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well. +That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. -=== "Hypercorn" +When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well. - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2. +/// - <div class="termy"> +//// - ```console - $ pip install hypercorn +//// tab | Hypercorn - ---> 100% - ``` +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2. - </div> +<div class="termy"> - ...or any other ASGI server. +```console +$ pip install hypercorn + +---> 100% +``` + +</div> + +...or any other ASGI server. + +//// ## Run the Server Program If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application: -=== "Uvicorn" +//// tab | Uvicorn - <div class="termy"> +<div class="termy"> - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` + +</div> + +//// + +//// tab | Hypercorn - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +<div class="termy"> - </div> +```console +$ hypercorn main:app --bind 0.0.0.0:80 -=== "Hypercorn" +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - <div class="termy"> +</div> - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// note - </div> +The command `uvicorn main:app` refers to: -!!! note - The command `uvicorn main:app` refers to: +* `main`: the file `main.py` (the Python "module"). +* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. + +It is equivalent to: + +```Python +from main import app +``` - * `main`: the file `main.py` (the Python "module"). - * `app`: the object created inside of `main.py` with the line `app = FastAPI()`. +/// - It is equivalent to: +/// warning - ```Python - from main import app - ``` +Uvicorn and others support a `--reload` option that is useful during development. -!!! warning - Uvicorn and others support a `--reload` option that is useful during development. +The `--reload` option consumes much more resources, is more unstable, etc. - The `--reload` option consumes much more resources, is more unstable, etc. +It helps a lot during **development**, but you **shouldn't** use it in **production**. - It helps a lot during **development**, but you **shouldn't** use it in **production**. +/// ## Hypercorn with Trio diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 5fe2309a9..433371b9d 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ As you saw in the previous chapter about [Deployment Concepts](concepts.md){.int Here I'll show you how to use <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> with **Uvicorn worker processes**. -!!! info - If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. +/// info - In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. +If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. + +In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. + +/// ## Gunicorn with Uvicorn Workers diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index 24430b0cf..e387d5712 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -42,8 +42,11 @@ Following the Semantic Versioning conventions, any version below `1.0.0` could p FastAPI also follows the convention that any "PATCH" version change is for bug fixes and non-breaking changes. -!!! tip - The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. +/// tip + +The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. + +/// So, you should be able to pin to a version like: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Breaking changes and new features are added in "MINOR" versions. -!!! tip - The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. +/// tip + +The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. + +/// ## Upgrading the FastAPI versions diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index 1a36390f5..5a3b8ee33 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -6,8 +6,11 @@ There are many posts, articles, tools, and projects, related to **FastAPI**. Here's an incomplete list of some of them. -!!! tip - If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request adding it</a>. +/// tip + +If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request adding it</a>. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md index 0fc072ed2..e27bebcb4 100644 --- a/docs/en/docs/fastapi-cli.md +++ b/docs/en/docs/fastapi-cli.md @@ -76,5 +76,8 @@ By default, **auto-reload** is disabled. It also listens on the IP address `0.0. In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. -!!! tip - You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}. +/// tip + +You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index c9fcc3866..bf7954449 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -64,10 +64,13 @@ These are the users that have been [helping others the most with questions in Gi They have proven to be **FastAPI Experts** by helping many others. ✨ -!!! tip - You could become an official FastAPI Expert too! +/// tip - Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 +You could become an official FastAPI Expert too! + +Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 + +/// You can see the **FastAPI Experts** for: diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index f8954c0fc..1a871a22b 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` means: +/// info - Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` means: + +Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Editor support diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index ab2dff39b..cd367dd6b 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -170,12 +170,15 @@ And if there's any other style or consistency need, I'll ask directly for that, * Then **comment** saying that you did that, that's how I will know you really checked it. -!!! info - Unfortunately, I can't simply trust PRs that just have several approvals. +/// info - Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 +Unfortunately, I can't simply trust PRs that just have several approvals. - So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 +Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 + +So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 + +/// * If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things. @@ -226,10 +229,13 @@ If you can help me with that, **you are helping me maintain FastAPI** and making Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord chat server</a> 👥 and hang out with others in the FastAPI community. -!!! tip - For questions, ask them in <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. +/// tip + +For questions, ask them in <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Use the chat only for other general conversations. - Use the chat only for other general conversations. +/// ### Don't use the chat for questions diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md index 4d53f53a7..a75f8ef58 100644 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -1,14 +1,20 @@ # ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated) -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1. +These docs are about to be updated. 🎉 - The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> once it is updated to use Pydantic v2 as well. +The current version assumes Pydantic v1. -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. +The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> once it is updated to use Pydantic v2 as well. + +/// + +/// warning | "Deprecated" + +This tutorial is deprecated and will be removed in a future version. + +/// You can also use <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases`</a> with **FastAPI** to connect to databases using `async` and `await`. @@ -22,10 +28,13 @@ In this example, we'll use **SQLite**, because it uses a single file and Python Later, for your production application, you might want to use a database server like **PostgreSQL**. -!!! tip - You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. +/// tip - This section doesn't apply those ideas, to be equivalent to the counterpart in <a href="https://www.starlette.io/database/" class="external-link" target="_blank">Starlette</a>. +You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. + +This section doesn't apply those ideas, to be equivalent to the counterpart in <a href="https://www.starlette.io/database/" class="external-link" target="_blank">Starlette</a>. + +/// ## Import and set up `SQLAlchemy` @@ -37,10 +46,13 @@ Later, for your production application, you might want to use a database server {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! tip - Notice that all this code is pure SQLAlchemy Core. +/// tip + +Notice that all this code is pure SQLAlchemy Core. + +`databases` is not doing anything here yet. - `databases` is not doing anything here yet. +/// ## Import and set up `databases` @@ -52,8 +64,11 @@ Later, for your production application, you might want to use a database server {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! tip - If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. +/// tip + +If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. + +/// ## Create the tables @@ -100,8 +115,11 @@ Create the *path operation function* to read notes: {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. +/// note + +Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. + +/// ### Notice the `response_model=List[Note]` @@ -117,13 +135,19 @@ Create the *path operation function* to create notes: {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +/// info + +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + +/// + +/// note - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. -!!! note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. +/// ### About `{**note.dict(), "id": last_record_id}` diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 053e5eacd..0c766d3e4 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -40,12 +40,15 @@ And similarly for ReDoc... {!../../../docs_src/custom_docs_ui/tutorial001.py!} ``` -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +/// tip - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. + +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +/// ### Create a *path operation* to test it @@ -177,12 +180,15 @@ And similarly for ReDoc... {!../../../docs_src/custom_docs_ui/tutorial002.py!} ``` -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +/// tip + +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. + +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +/// ### Create a *path operation* to test static files diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md index 3b9435004..20e1904f1 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ In particular, this may be a good alternative to logic in a middleware. For example, if you want to read or manipulate the request body before it is processed by your application. -!!! danger - This is an "advanced" feature. +/// danger - If you are just starting with **FastAPI** you might want to skip this section. +This is an "advanced" feature. + +If you are just starting with **FastAPI** you might want to skip this section. + +/// ## Use cases @@ -27,8 +30,11 @@ And an `APIRoute` subclass to use that custom request class. ### Create a custom `GzipRequest` class -!!! tip - This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. +/// tip + +This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. + +/// First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header. @@ -54,16 +60,19 @@ Here we use it to create a `GzipRequest` from the original request. {!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` -!!! note "Technical Details" - A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. +/// note | "Technical Details" - A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. +A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. - The `scope` `dict` and `receive` function are both part of the ASGI specification. +A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. - And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. +The `scope` `dict` and `receive` function are both part of the ASGI specification. - To learn more about the `Request` check <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette's docs about Requests</a>. +And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. + +To learn more about the `Request` check <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette's docs about Requests</a>. + +/// The only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`. @@ -75,10 +84,13 @@ But because of our changes in `GzipRequest.body`, the request body will be autom ## Accessing the request body in an exception handler -!!! tip - To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). +/// tip + +To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +But this example is still valid and it shows how to interact with the internal components. - But this example is still valid and it shows how to interact with the internal components. +/// We can also use this same approach to access the request body in an exception handler. diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index a18fd737e..9909f778c 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -27,8 +27,11 @@ And that function `get_openapi()` receives as parameters: * `description`: The description of your API, this can include markdown and will be shown in the docs. * `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`. -!!! info - The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. +/// info + +The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. + +/// ## Overriding the defaults diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index d5a5826f1..d4b7cfdaa 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -4,12 +4,15 @@ As **FastAPI** is based on the **ASGI** standard, it's very easy to integrate an You can combine normal FastAPI *path operations* with GraphQL on the same application. -!!! tip - **GraphQL** solves some very specific use cases. +/// tip - It has **advantages** and **disadvantages** when compared to common **web APIs**. +**GraphQL** solves some very specific use cases. - Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓 +It has **advantages** and **disadvantages** when compared to common **web APIs**. + +Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓 + +/// ## GraphQL Libraries @@ -46,8 +49,11 @@ Previous versions of Starlette included a `GraphQLApp` class to integrate with < It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>, that covers the same use case and has an **almost identical interface**. -!!! tip - If you need GraphQL, I still would recommend you check out <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, as it's based on type annotations instead of custom classes and types. +/// tip + +If you need GraphQL, I still would recommend you check out <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, as it's based on type annotations instead of custom classes and types. + +/// ## Learn More diff --git a/docs/en/docs/how-to/index.md b/docs/en/docs/how-to/index.md index ec7fd38f8..730dce5d5 100644 --- a/docs/en/docs/how-to/index.md +++ b/docs/en/docs/how-to/index.md @@ -6,6 +6,8 @@ Most of these ideas would be more or less **independent**, and in most cases you If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them. -!!! tip +/// tip - If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. +If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. + +/// diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md index 18e3f4b7e..a0abfe21d 100644 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -1,14 +1,20 @@ # ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated) -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1. +These docs are about to be updated. 🎉 - The new docs will hopefully use Pydantic v2 and will use <a href="https://art049.github.io/odmantic/" class="external-link" target="_blank">ODMantic</a> with MongoDB. +The current version assumes Pydantic v1. -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. +The new docs will hopefully use Pydantic v2 and will use <a href="https://art049.github.io/odmantic/" class="external-link" target="_blank">ODMantic</a> with MongoDB. + +/// + +/// warning | "Deprecated" + +This tutorial is deprecated and will be removed in a future version. + +/// **FastAPI** can also be integrated with any <abbr title="Distributed database (Big Data), also 'Not Only SQL'">NoSQL</abbr>. @@ -22,8 +28,11 @@ You can adapt it to any other NoSQL database like: * **ArangoDB** * **ElasticSearch**, etc. -!!! tip - There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a> +/// tip + +There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a> + +/// ## Import Couchbase components @@ -94,10 +103,13 @@ We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of {!../../../docs_src/nosql_databases/tutorial001.py!} ``` -!!! note - Notice that we have a `hashed_password` and a `type` field that will be stored in the database. +/// note + +Notice that we have a `hashed_password` and a `type` field that will be stored in the database. + +But it is not part of the general `User` model (the one we will return in the *path operation*). - But it is not part of the general `User` model (the one we will return in the *path operation*). +/// ## Get the user diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md index 10be1071a..0ab5b1337 100644 --- a/docs/en/docs/how-to/separate-openapi-schemas.md +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -10,111 +10,123 @@ Let's see how that works and how to change it if you need to do that. Let's say you have a Pydantic model with default values, like this one: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +```Python hl_lines="7" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - # Code below omitted 👇 - ``` +# Code below omitted 👇 +``` - <details> - <summary>👀 Full file preview</summary> +<details> +<summary>👀 Full file preview</summary> - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - </details> +</details> -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +//// tab | Python 3.9+ - # Code below omitted 👇 - ``` +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - <details> - <summary>👀 Full file preview</summary> +# Code below omitted 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +<details> +<summary>👀 Full file preview</summary> - </details> +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +</details> - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +//// - # Code below omitted 👇 - ``` +//// tab | Python 3.8+ - <details> - <summary>👀 Full file preview</summary> +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +# Code below omitted 👇 +``` - </details> +<details> +<summary>👀 Full file preview</summary> + +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +</details> + +//// ### Model for Input If you use this model as an input like here: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - ```Python hl_lines="14" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +# Code below omitted 👇 +``` - # Code below omitted 👇 - ``` +<details> +<summary>👀 Full file preview</summary> - <details> - <summary>👀 Full file preview</summary> +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +</details> - </details> +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - # Code below omitted 👇 - ``` +# Code below omitted 👇 +``` - <details> - <summary>👀 Full file preview</summary> +<details> +<summary>👀 Full file preview</summary> - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` - </details> +</details> -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +//// tab | Python 3.8+ - # Code below omitted 👇 - ``` +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - <details> - <summary>👀 Full file preview</summary> +# Code below omitted 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +<details> +<summary>👀 Full file preview</summary> - </details> +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +</details> + +//// ...then the `description` field will **not be required**. Because it has a default value of `None`. @@ -130,23 +142,29 @@ You can confirm that in the docs, the `description` field doesn't have a **red a But if you use the same model as an output, like here: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +//// ...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**. @@ -199,26 +217,35 @@ Probably the main use case for this is if you already have some autogenerated cl In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`. -!!! info - Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 +/// info + +Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} - ``` +//// ### Same Schema for Input and Output Models in Docs diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md index 7211f7ed3..e411c200c 100644 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ b/docs/en/docs/how-to/sql-databases-peewee.md @@ -1,28 +1,40 @@ # ~~SQL (Relational) Databases with Peewee~~ (deprecated) -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. +/// warning | "Deprecated" -!!! warning - If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. +This tutorial is deprecated and will be removed in a future version. - Feel free to skip this. +/// - Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. +/// warning -!!! info - These docs assume Pydantic v1. +If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. - Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. +Feel free to skip this. - The examples here are no longer tested in CI (as they were before). +Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. + +/// + +/// info + +These docs assume Pydantic v1. + +Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. + +The examples here are no longer tested in CI (as they were before). + +/// If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM. If you already have a code base that uses <a href="https://docs.peewee-orm.com/en/latest/" class="external-link" target="_blank">Peewee ORM</a>, you can check here how to use it with **FastAPI**. -!!! warning "Python 3.7+ required" - You will need Python 3.7 or above to safely use Peewee with FastAPI. +/// warning | "Python 3.7+ required" + +You will need Python 3.7 or above to safely use Peewee with FastAPI. + +/// ## Peewee for async @@ -36,8 +48,11 @@ But if you need to change some of the defaults, support more than one predefined Nevertheless, it's possible to do it, and here you'll see exactly what code you have to add to be able to use Peewee with FastAPI. -!!! note "Technical Details" - You can read more about Peewee's stand about async in Python <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">in the docs</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">an issue</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">a PR</a>. +/// note | "Technical Details" + +You can read more about Peewee's stand about async in Python <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">in the docs</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">an issue</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">a PR</a>. + +/// ## The same app @@ -77,8 +92,11 @@ Let's first check all the normal Peewee code, create a Peewee database: {!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` -!!! tip - Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. +/// tip + +Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. + +/// #### Note @@ -96,9 +114,11 @@ connect_args={"check_same_thread": False} ...it is needed only for `SQLite`. -!!! info "Technical Details" +/// info | "Technical Details" - Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. +Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. + +/// ### Make Peewee async-compatible `PeeweeConnectionState` @@ -106,14 +126,17 @@ The main issue with Peewee and FastAPI is that Peewee relies heavily on <a href= And `threading.local` is not compatible with the new async features of modern Python. -!!! note "Technical Details" - `threading.local` is used to have a "magic" variable that has a different value for each thread. +/// note | "Technical Details" + +`threading.local` is used to have a "magic" variable that has a different value for each thread. - This was useful in older frameworks designed to have one single thread per request, no more, no less. +This was useful in older frameworks designed to have one single thread per request, no more, no less. - Using this, each request would have its own database connection/session, which is the actual final goal. +Using this, each request would have its own database connection/session, which is the actual final goal. - But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI. +But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI. + +/// But Python 3.7 and above provide a more advanced alternative to `threading.local`, that can also be used in the places where `threading.local` would be used, but is compatible with the new async features. @@ -137,10 +160,13 @@ It has all the logic to make Peewee use `contextvars` instead of `threading.loca So, we need to do some extra tricks to make it work as if it was just using `threading.local`. The `__init__`, `__setattr__`, and `__getattr__` implement all the required tricks for this to be used by Peewee without knowing that it is now compatible with FastAPI. -!!! tip - This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc. +/// tip + +This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc. - But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`. +But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`. + +/// ### Use the custom `PeeweeConnectionState` class @@ -150,11 +176,17 @@ Now, overwrite the `._state` internal attribute in the Peewee database `db` obje {!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` -!!! tip - Make sure you overwrite `db._state` *after* creating `db`. +/// tip + +Make sure you overwrite `db._state` *after* creating `db`. -!!! tip - You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc. +/// + +/// tip + +You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc. + +/// ## Create the database models @@ -166,10 +198,13 @@ Now create the Peewee models (classes) for `User` and `Item`. This is the same you would do if you followed the Peewee tutorial and updated the models to have the same data as in the SQLAlchemy tutorial. -!!! tip - Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database. +/// tip + +Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database. + +But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. - But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. +/// Import `db` from `database` (the file `database.py` from above) and use it here. @@ -177,25 +212,31 @@ Import `db` from `database` (the file `database.py` from above) and use it here. {!../../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` -!!! tip - Peewee creates several magic attributes. +/// tip - It will automatically add an `id` attribute as an integer to be the primary key. +Peewee creates several magic attributes. - It will chose the name of the tables based on the class names. +It will automatically add an `id` attribute as an integer to be the primary key. - For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere. +It will chose the name of the tables based on the class names. + +For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere. + +/// ## Create the Pydantic models Now let's check the file `sql_app/schemas.py`. -!!! tip - To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models. +/// tip + +To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models. + +These Pydantic models define more or less a "schema" (a valid data shape). - These Pydantic models define more or less a "schema" (a valid data shape). +So this will help us avoiding confusion while using both. - So this will help us avoiding confusion while using both. +/// ### Create the Pydantic *models* / schemas @@ -205,12 +246,15 @@ Create all the same Pydantic models as in the SQLAlchemy tutorial: {!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` -!!! tip - Here we are creating the models with an `id`. +/// tip - We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically. +Here we are creating the models with an `id`. - We are also adding the magic `owner_id` attribute to `Item`. +We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically. + +We are also adding the magic `owner_id` attribute to `Item`. + +/// ### Create a `PeeweeGetterDict` for the Pydantic *models* / schemas @@ -236,8 +280,11 @@ And if that's the case, just return a `list` with it. And then we use it in the Pydantic *models* / schemas that use `orm_mode = True`, with the configuration variable `getter_dict = PeeweeGetterDict`. -!!! tip - We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas. +/// tip + +We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas. + +/// ## CRUD utils @@ -309,12 +356,15 @@ For that, we need to create another `async` dependency `reset_db_state()` that i For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). -!!! tip - As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread. +/// tip - But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request. +As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread. - And at the same time, the other concurrent request will have its own database state that will be independent for the whole request. +But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request. + +And at the same time, the other concurrent request will have its own database state that will be independent for the whole request. + +/// #### Peewee Proxy @@ -479,8 +529,11 @@ Repeat the same process with the 10 tabs. This time all of them will wait and yo ## Technical Details -!!! warning - These are very technical details that you probably don't need. +/// warning + +These are very technical details that you probably don't need. + +/// ### The problem diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js index b7e5236f3..ff17710e2 100644 --- a/docs/en/docs/js/custom.js +++ b/docs/en/docs/js/custom.js @@ -147,7 +147,7 @@ async function showRandomAnnouncement(groupId, timeInterval) { children = shuffle(children) let index = 0 const announceRandom = () => { - children.forEach((el, i) => {el.style.display = "none"}); + children.forEach((el, i) => { el.style.display = "none" }); children[index].style.display = "block" index = (index + 1) % children.length } @@ -176,5 +176,6 @@ async function main() { showRandomAnnouncement('announce-left', 5000) showRandomAnnouncement('announce-right', 10000) } - -main() +document$.subscribe(() => { + main() +}) diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index efda1a703..2c91cab72 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -2,8 +2,11 @@ These are the tasks that can be performed to manage the FastAPI repository by [team members](./fastapi-people.md#team){.internal-link target=_blank}. -!!! tip - This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉 +/// tip + +This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉 + +/// ...so, you are a [team member of FastAPI](./fastapi-people.md#team){.internal-link target=_blank}? Wow, you are so cool! 😎 @@ -80,8 +83,11 @@ Make sure you use a supported label from the <a href="https://github.com/tiangol * `internal`: Internal * Use this for changes that only affect how the repo is managed. For example upgrades to internal dependencies, changes in GitHub Actions or scripts, etc. -!!! tip - Some tools like Dependabot, will add some labels, like `dependencies`, but have in mind that this label is not used by the `latest-changes` GitHub Action, so it won't be used in the release notes. Please make sure one of the labels above is added. +/// tip + +Some tools like Dependabot, will add some labels, like `dependencies`, but have in mind that this label is not used by the `latest-changes` GitHub Action, so it won't be used in the release notes. Please make sure one of the labels above is added. + +/// ## Add Labels to Translation PRs @@ -116,45 +122,70 @@ For the other languages, confirm that: * The "admonition" sections, like `tip`, `info`, etc. are not changed or translated. For example: ``` -!!! tip - This is a tip. +/// tip + +This is a tip. + +/// + ``` looks like this: -!!! tip - This is a tip. +/// tip + +This is a tip. + +/// ...it could be translated as: ``` -!!! tip - Esto es un consejo. +/// tip + +Esto es un consejo. + +/// + ``` ...but needs to keep the exact `tip` keyword. If it was translated to `consejo`, like: ``` -!!! consejo - Esto es un consejo. +/// consejo + +Esto es un consejo. + +/// + ``` it would change the style to the default one, it would look like: -!!! consejo - Esto es un consejo. +/// consejo + +Esto es un consejo. + +/// Those don't have to be translated, but if they are, they need to be written as: ``` -!!! tip "consejo" - Esto es un consejo. +/// tip | "consejo" + +Esto es un consejo. + +/// + ``` Which looks like: -!!! tip "consejo" - Esto es un consejo. +/// tip | "consejo" + +Esto es un consejo. + +/// ## First Translation PR diff --git a/docs/en/docs/newsletter.md b/docs/en/docs/newsletter.md index 782db1353..29b777a67 100644 --- a/docs/en/docs/newsletter.md +++ b/docs/en/docs/newsletter.md @@ -1,5 +1,5 @@ # FastAPI and friends newsletter -<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 0;"></iframe> +<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 800px;"></iframe> <script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script> diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 20ffcdccc..900ede22c 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -12,8 +12,11 @@ This is just a **quick tutorial / refresher** about Python type hints. It covers But even if you never use **FastAPI**, you would benefit from learning a bit about them. -!!! note - If you are a Python expert, and you already know everything about type hints, skip to the next chapter. +/// note + +If you are a Python expert, and you already know everything about type hints, skip to the next chapter. + +/// ## Motivation @@ -170,45 +173,55 @@ If you can use the **latest versions of Python**, use the examples for the lates For example, let's define a variable to be a `list` of `str`. -=== "Python 3.9+" +//// tab | Python 3.9+ - Declare the variable, with the same colon (`:`) syntax. +Declare the variable, with the same colon (`:`) syntax. - As the type, put `list`. +As the type, put `list`. - As the list is a type that contains some internal types, you put them in square brackets: +As the list is a type that contains some internal types, you put them in square brackets: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - From `typing`, import `List` (with a capital `L`): +//// tab | Python 3.8+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +From `typing`, import `List` (with a capital `L`): - Declare the variable, with the same colon (`:`) syntax. +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Declare the variable, with the same colon (`:`) syntax. - As the type, put the `List` that you imported from `typing`. +As the type, put the `List` that you imported from `typing`. - As the list is a type that contains some internal types, you put them in square brackets: +As the list is a type that contains some internal types, you put them in square brackets: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -!!! info - Those internal types in the square brackets are called "type parameters". +/// info - In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above). +Those internal types in the square brackets are called "type parameters". + +In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above). + +/// That means: "the variable `items` is a `list`, and each of the items in this list is a `str`". -!!! tip - If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead. +/// tip + +If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead. + +/// By doing that, your editor can provide support even while processing items from the list: @@ -224,17 +237,21 @@ And still, the editor knows it is a `str`, and provides support for that. You would do the same to declare `tuple`s and `set`s: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// This means: @@ -249,17 +266,21 @@ The first type parameter is for the keys of the `dict`. The second type parameter is for the values of the `dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// This means: @@ -275,17 +296,21 @@ In Python 3.6 and above (including Python 3.10) you can use the `Union` type fro In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr>. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// In both cases this means that `item` could be an `int` or a `str`. @@ -305,23 +330,29 @@ Using `Optional[str]` instead of just `str` will let the editor help you detecti This also means that in Python 3.10, you can use `Something | None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "Python 3.8+ alternative" +//// tab | Python 3.8+ alternative - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### Using `Union` or `Optional` @@ -366,47 +397,53 @@ And then you won't have to worry about names like `Optional` and `Union`. 😎 These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example: -=== "Python 3.10+" +//// tab | Python 3.10+ + +You can use the same builtin types as generics (with square brackets and types inside): + +* `list` +* `tuple` +* `set` +* `dict` - You can use the same builtin types as generics (with square brackets and types inside): +And the same as with Python 3.8, from the `typing` module: - * `list` - * `tuple` - * `set` - * `dict` +* `Union` +* `Optional` (the same as with Python 3.8) +* ...and others. - And the same as with Python 3.8, from the `typing` module: +In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr> to declare unions of types, that's a lot better and simpler. - * `Union` - * `Optional` (the same as with Python 3.8) - * ...and others. +//// - In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr> to declare unions of types, that's a lot better and simpler. +//// tab | Python 3.9+ -=== "Python 3.9+" +You can use the same builtin types as generics (with square brackets and types inside): - You can use the same builtin types as generics (with square brackets and types inside): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +And the same as with Python 3.8, from the `typing` module: - And the same as with Python 3.8, from the `typing` module: +* `Union` +* `Optional` +* ...and others. - * `Union` - * `Optional` - * ...and others. +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...and others. +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...and others. + +//// ### Classes as types @@ -446,55 +483,71 @@ And you get all the editor support with that resulting object. An example from the official Pydantic docs: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +//// tab | Python 3.8+ -!!! info - To learn more about <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, check its docs</a>. +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +To learn more about <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, check its docs</a>. + +/// **FastAPI** is all based on Pydantic. You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. +/// tip + +Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. + +/// ## Type Hints with Metadata Annotations Python also has a feature that allows putting **additional <abbr title="Data about the data, in this case, information about the type, e.g. a description.">metadata</abbr>** in these type hints using `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`. +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +In versions below Python 3.9, you import `Annotated` from `typing_extensions`. - In versions below Python 3.9, you import `Annotated` from `typing_extensions`. +It will already be installed with **FastAPI**. - It will already be installed with **FastAPI**. +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`. @@ -506,10 +559,13 @@ For now, you just need to know that `Annotated` exists, and that it's standard P Later you will see how **powerful** it can be. -!!! tip - The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨ +/// tip - And also that your code will be very compatible with many other Python tools and libraries. 🚀 +The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨ + +And also that your code will be very compatible with many other Python tools and libraries. 🚀 + +/// ## Type hints in **FastAPI** @@ -533,5 +589,8 @@ This might all sound abstract. Don't worry. You'll see all this in action in the The important thing is that by using standard Python types, in a single place (instead of adding more classes, decorators, etc), **FastAPI** will do a lot of the work for you. -!!! info - If you already went through all the tutorial and came back to see more about types, a good resource is <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">the "cheat sheet" from `mypy`</a>. +/// info + +If you already went through all the tutorial and came back to see more about types, a good resource is <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">the "cheat sheet" from `mypy`</a>. + +/// diff --git a/docs/en/docs/reference/request.md b/docs/en/docs/reference/request.md index 0326f3fc7..f1de21642 100644 --- a/docs/en/docs/reference/request.md +++ b/docs/en/docs/reference/request.md @@ -8,7 +8,10 @@ You can import it directly from `fastapi`: from fastapi import Request ``` -!!! tip - When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. +/// tip + +When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. + +/// ::: fastapi.Request diff --git a/docs/en/docs/reference/websockets.md b/docs/en/docs/reference/websockets.md index d21e81a07..4b7244e08 100644 --- a/docs/en/docs/reference/websockets.md +++ b/docs/en/docs/reference/websockets.md @@ -8,8 +8,11 @@ It is provided directly by Starlette, but you can import it from `fastapi`: from fastapi import WebSocket ``` -!!! tip - When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. +/// tip + +When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. + +/// ::: fastapi.WebSocket options: diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index bcfadc8b8..5370b9ba8 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -57,41 +57,57 @@ Using `BackgroundTasks` also works with the dependency injection system, you can **FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="14 16 23 26" +{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// In this example, the messages will be written to the `log.txt` file *after* the response is sent. diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index eccdd8aeb..97f6b205b 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ If you are building an application or a web API, it's rarely the case that you c **FastAPI** provides a convenience tool to structure your application while keeping all the flexibility. -!!! info - If you come from Flask, this would be the equivalent of Flask's Blueprints. +/// info + +If you come from Flask, this would be the equivalent of Flask's Blueprints. + +/// ## An example file structure @@ -26,16 +29,19 @@ Let's say you have a file structure like this: │ └── admin.py ``` -!!! tip - There are several `__init__.py` files: one in each directory or subdirectory. +/// tip + +There are several `__init__.py` files: one in each directory or subdirectory. - This is what allows importing code from one file into another. +This is what allows importing code from one file into another. - For example, in `app/main.py` you could have a line like: +For example, in `app/main.py` you could have a line like: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * The `app` directory contains everything. And it has an empty file `app/__init__.py`, so it is a "Python package" (a collection of "Python modules"): `app`. * It contains an `app/main.py` file. As it is inside a Python package (a directory with a file `__init__.py`), it is a "module" of that package: `app.main`. @@ -99,8 +105,11 @@ All the same options are supported. All the same `parameters`, `responses`, `dependencies`, `tags`, etc. -!!! tip - In this example, the variable is called `router`, but you can name it however you want. +/// tip + +In this example, the variable is called `router`, but you can name it however you want. + +/// We are going to include this `APIRouter` in the main `FastAPI` app, but first, let's check the dependencies and another `APIRouter`. @@ -112,31 +121,43 @@ So we put them in their own `dependencies` module (`app/dependencies.py`). We will now use a simple dependency to read a custom `X-Token` header: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` - ```Python hl_lines="3 6-8" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 5-7" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} - ``` +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="1 4-6" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app/dependencies.py!} - ``` +/// tip -!!! tip - We are using an invented header to simplify this example. +Prefer to use the `Annotated` version if possible. - But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}. +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip + +We are using an invented header to simplify this example. + +But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}. + +/// ## Another module with `APIRouter` @@ -180,8 +201,11 @@ We can also add a list of `tags` and extra `responses` that will be applied to a And we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them. -!!! tip - Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*. +/// tip + +Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*. + +/// The end result is that the item paths are now: @@ -198,11 +222,17 @@ The end result is that the item paths are now: * The router dependencies are executed first, then the [`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, and then the normal parameter dependencies. * You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -!!! tip - Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them. +/// tip + +Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them. + +/// + +/// check -!!! check - The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication. +The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication. + +/// ### Import the dependencies @@ -218,8 +248,11 @@ So we use a relative import with `..` for the dependencies: #### How relative imports work -!!! tip - If you know perfectly how imports work, continue to the next section below. +/// tip + +If you know perfectly how imports work, continue to the next section below. + +/// A single dot `.`, like in: @@ -286,10 +319,13 @@ But we can still add _more_ `tags` that will be applied to a specific *path oper {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - This last path operation will have the combination of tags: `["items", "custom"]`. +/// tip - And it will also have both responses in the documentation, one for `404` and one for `403`. +This last path operation will have the combination of tags: `["items", "custom"]`. + +And it will also have both responses in the documentation, one for `404` and one for `403`. + +/// ## The main `FastAPI` @@ -345,20 +381,23 @@ We could also import them like: from app.routers import items, users ``` -!!! info - The first version is a "relative import": +/// info - ```Python - from .routers import items, users - ``` +The first version is a "relative import": - The second version is an "absolute import": +```Python +from .routers import items, users +``` + +The second version is an "absolute import": + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +To learn more about Python Packages and Modules, read <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">the official Python documentation about Modules</a>. - To learn more about Python Packages and Modules, read <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">the official Python documentation about Modules</a>. +/// ### Avoid name collisions @@ -389,26 +428,35 @@ Now, let's include the `router`s from the submodules `users` and `items`: {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` contains the `APIRouter` inside of the file `app/routers/users.py`. +/// info + +`users.router` contains the `APIRouter` inside of the file `app/routers/users.py`. - And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`. +And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`. + +/// With `app.include_router()` we can add each `APIRouter` to the main `FastAPI` application. It will include all the routes from that router as part of it. -!!! note "Technical Details" - It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`. +/// note | "Technical Details" + +It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`. + +So, behind the scenes, it will actually work as if everything was the same single app. - So, behind the scenes, it will actually work as if everything was the same single app. +/// -!!! check - You don't have to worry about performance when including routers. +/// check - This will take microseconds and will only happen at startup. +You don't have to worry about performance when including routers. - So it won't affect performance. ⚡ +This will take microseconds and will only happen at startup. + +So it won't affect performance. ⚡ + +/// ### Include an `APIRouter` with a custom `prefix`, `tags`, `responses`, and `dependencies` @@ -455,16 +503,19 @@ Here we do it... just to show that we can 🤷: and it will work correctly, together with all the other *path operations* added with `app.include_router()`. -!!! info "Very Technical Details" - **Note**: this is a very technical detail that you probably can **just skip**. +/// info | "Very Technical Details" + +**Note**: this is a very technical detail that you probably can **just skip**. + +--- - --- +The `APIRouter`s are not "mounted", they are not isolated from the rest of the application. - The `APIRouter`s are not "mounted", they are not isolated from the rest of the application. +This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces. - This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces. +As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly. - As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly. +/// ## Check the automatic API docs diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md index 55e67fdd6..466df29f1 100644 --- a/docs/en/docs/tutorial/body-fields.md +++ b/docs/en/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ The same way you can declare additional validation and metadata in *path operati First, you have to import it: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! warning - Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc). +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning + +Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc). + +/// ## Declare model attributes You can then use `Field` with model attributes: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc. -!!! note "Technical Details" - Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class. +/// note | "Technical Details" - And Pydantic's `Field` returns an instance of `FieldInfo` as well. +Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class. - `Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class. +And Pydantic's `Field` returns an instance of `FieldInfo` as well. - Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes. +`Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class. -!!! tip - Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`. +Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes. + +/// + +/// tip + +Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`. + +/// ## Add extra information @@ -105,9 +146,12 @@ You can declare extra information in `Field`, `Query`, `Body`, etc. And it will You will learn more about adding extra information later in the docs, when learning to declare examples. -!!! warning - Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application. - As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema. +/// warning + +Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application. +As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema. + +/// ## Recap diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 689db7ece..3adfcd4d1 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ First, of course, you can mix `Path`, `Query` and request body parameter declara And you can also declare body parameters as optional, by setting the default to `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip -!!! note - Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note + +Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value. + +/// ## Multiple body parameters @@ -62,17 +81,21 @@ In the previous example, the *path operations* would expect a JSON body with the But you can also declare multiple body parameters, e.g. `item` and `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models). @@ -93,9 +116,11 @@ So, it will then use the parameter names as keys (field names) in the body, and } ``` -!!! note - Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`. +/// note + +Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`. +/// **FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`. @@ -111,41 +136,57 @@ If you declare it as is, because it is a singular value, **FastAPI** will assume But you can instruct **FastAPI** to treat it as another body key using `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +/// + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +//// In this case, **FastAPI** will expect a body like: @@ -185,44 +226,63 @@ q: str | None = None For example: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later. -!!! info - `Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later. +/// ## Embed a single body parameter @@ -238,41 +298,57 @@ item: Item = Body(embed=True) as in: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// In this case **FastAPI** will expect a body like: diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 4c199f028..f823a9033 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ With **FastAPI**, you can define, validate, document, and use arbitrarily deeply You can define an attribute to be a subtype. For example, a Python `list`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// This will make `tags` be a list, although it doesn't declare the type of the elements of the list. @@ -61,23 +65,29 @@ Use that same standard syntax for model attributes with internal types. So, in our example, we can make `tags` be specifically a "list of strings": -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Set types @@ -87,23 +97,29 @@ And Python has a special data type for sets of unique items, the `set`. Then we can declare `tags` as a set of strings: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// With this, even if you receive a request with duplicate data, it will be converted to a set of unique items. @@ -125,45 +141,57 @@ All that, arbitrarily nested. For example, we can define an `Image` model: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### Use the submodel as a type And then we can use it as the type of an attribute: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// This would mean that **FastAPI** would expect a body similar to: @@ -196,23 +224,29 @@ To see all the options you have, checkout the docs for <a href="https://docs.pyd For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such. @@ -220,23 +254,29 @@ The string will be checked to be a valid URL, and documented in JSON Schema / Op You can also use Pydantic models as subtypes of `list`, `set`, etc.: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// This will expect (convert, validate, document, etc.) a JSON body like: @@ -264,33 +304,45 @@ This will expect (convert, validate, document, etc.) a JSON body like: } ``` -!!! info - Notice how the `images` key now has a list of image objects. +/// info + +Notice how the `images` key now has a list of image objects. + +/// ## Deeply nested models You can define arbitrarily deeply nested models: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s -!!! info - Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s +/// ## Bodies of pure lists @@ -308,17 +360,21 @@ images: list[Image] as in: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## Editor support everywhere @@ -348,26 +404,33 @@ That's what we are going to see here. In this case, you would accept any `dict` as long as it has `int` keys with `float` values: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Keep in mind that JSON only supports `str` as keys. -!!! tip - Keep in mind that JSON only supports `str` as keys. +But Pydantic has automatic data conversion. - But Pydantic has automatic data conversion. +This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them. - This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them. +And the `dict` you receive as `weights` will actually have `int` keys and `float` values. - And the `dict` you receive as `weights` will actually have `int` keys and `float` values. +/// ## Recap diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3ba2632d8..261f44d33 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ To update an item you can use the <a href="https://developer.mozilla.org/en-US/d You can use the `jsonable_encoder` to convert the input data to data that can be stored as JSON (e.g. with a NoSQL database). For example, converting `datetime` to `str`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// `PUT` is used to receive data that should replace the existing data. @@ -48,14 +54,17 @@ You can also use the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/ This means that you can send only the data that you want to update, leaving the rest intact. -!!! note - `PATCH` is less commonly used and known than `PUT`. +/// note + +`PATCH` is less commonly used and known than `PUT`. - And many teams use only `PUT`, even for partial updates. +And many teams use only `PUT`, even for partial updates. - You are **free** to use them however you want, **FastAPI** doesn't impose any restrictions. +You are **free** to use them however you want, **FastAPI** doesn't impose any restrictions. - But this guide shows you, more or less, how they are intended to be used. +But this guide shows you, more or less, how they are intended to be used. + +/// ### Using Pydantic's `exclude_unset` parameter @@ -63,61 +72,79 @@ If you want to receive partial updates, it's very useful to use the parameter `e Like `item.model_dump(exclude_unset=True)`. -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +/// info + +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + +/// That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values. Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// ### Using Pydantic's `update` parameter Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update. -!!! info - In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`. +/// info + +In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`. - The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2. +The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2. + +/// Like `stored_item_model.model_copy(update=update_data)`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// ### Partial updates recap @@ -134,32 +161,44 @@ In summary, to apply partial updates you would: * Save the data to your DB. * Return the updated model. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// -=== "Python 3.9+" +/// tip - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +You can actually use this same technique with an HTTP `PUT` operation. -=== "Python 3.8+" +But the example here uses `PATCH` because it was created for these use cases. - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +/// -!!! tip - You can actually use this same technique with an HTTP `PUT` operation. +/// note - But the example here uses `PATCH` because it was created for these use cases. +Notice that the input model is still validated. -!!! note - Notice that the input model is still validated. +So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`). - So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`). +To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md){.internal-link target=_blank}. - To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index f9af42938..f3a8685c6 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -8,28 +8,35 @@ Your API almost always has to send a **response** body. But clients don't necess To declare a **request** body, you use <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> models with all their power and benefits. -!!! info - To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`. +/// info - Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases. +To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`. - As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it. +Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases. + +As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it. + +/// ## Import Pydantic's `BaseModel` First, you need to import `BaseModel` from `pydantic`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// ## Create your data model @@ -37,17 +44,21 @@ Then you declare your data model as a class that inherits from `BaseModel`. Use standard Python types for all the attributes: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use `None` to make it just optional. @@ -75,17 +86,21 @@ For example, this model above declares a JSON "`object`" (or Python `dict`) like To add it to your *path operation*, declare it the same way you declared path and query parameters: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ...and declare its type as the model you created, `Item`. @@ -134,32 +149,39 @@ But you would get the same editor support with <a href="https://www.jetbrains.co <img src="/img/tutorial/body/image05.png"> -!!! tip - If you use <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> as your editor, you can use the <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. +/// tip + +If you use <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> as your editor, you can use the <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. - It improves editor support for Pydantic models, with: +It improves editor support for Pydantic models, with: - * auto-completion - * type checks - * refactoring - * searching - * inspections +* auto-completion +* type checks +* refactoring +* searching +* inspections + +/// ## Use the model Inside of the function, you can access all the attributes of the model object directly: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## Request body + path parameters @@ -167,17 +189,21 @@ You can declare path parameters and request body at the same time. **FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## Request body + path + query parameters @@ -185,17 +211,21 @@ You can also declare **body**, **path** and **query** parameters, all at the sam **FastAPI** will recognize each of them and take the data from the correct place. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` + +//// The function parameters will be recognized as follows: @@ -203,10 +233,13 @@ The function parameters will be recognized as follows: * If the parameter is of a **singular type** (like `int`, `float`, `str`, `bool`, etc) it will be interpreted as a **query** parameter. * If the parameter is declared to be of the type of a **Pydantic model**, it will be interpreted as a request **body**. -!!! note - FastAPI will know that the value of `q` is not required because of the default value `= None`. +/// note + +FastAPI will know that the value of `q` is not required because of the default value `= None`. + +The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors. - The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors. +/// ## Without Pydantic diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 3436a7df3..6196b34d0 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ You can define Cookie parameters the same way you define `Query` and `Path` para First import `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Declare `Cookie` parameters @@ -48,49 +64,71 @@ Then declare the cookie parameters using the same structure as with `Path` and ` The first value is the default value, you can pass all the extra validation or annotation parameters: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Technical Details" -=== "Python 3.8+ non-Annotated" +`Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class. - !!! tip - Prefer to use the `Annotated` version if possible. +But remember that when you import `Query`, `Path`, `Cookie` and others from `fastapi`, those are actually functions that return special classes. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Technical Details" - `Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class. +/// info - But remember that when you import `Query`, `Path`, `Cookie` and others from `fastapi`, those are actually functions that return special classes. +To declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters. -!!! info - To declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters. +/// ## Recap diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 33b11983b..665249ffa 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -78,7 +78,10 @@ Any request with an `Origin` header. In this case the middleware will pass the r For more info about <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS documentation</a>. -!!! note "Technical Details" - You could also use `from starlette.middleware.cors import CORSMiddleware`. +/// note | "Technical Details" - **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. +You could also use `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. + +/// diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md index 3deba54d5..c520a631d 100644 --- a/docs/en/docs/tutorial/debugging.md +++ b/docs/en/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ So, the line: will not be executed. -!!! info - For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>. +/// info + +For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>. + +/// ## Run your code with your debugger diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index 4b958a665..a392672bb 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ Before diving deeper into the **Dependency Injection** system, let's upgrade the In the previous example, we were returning a `dict` from our dependency ("dependable"): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// But then we get a `dict` in the parameter `commons` of the *path operation function*. @@ -103,117 +119,165 @@ That also applies to callables with no parameters at all. The same as it would b Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="12-16" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +/// + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// Pay attention to the `__init__` method used to create the instance of the class: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...it has the same parameters as our previous `common_parameters`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Those parameters are what **FastAPI** will use to "solve" the dependency. @@ -229,41 +293,57 @@ In both cases the data will be converted, validated, documented on the OpenAPI s Now you can declare your dependency using this class. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** calls the `CommonQueryParams` class. This creates an "instance" of that class and the instance will be passed as the parameter `commons` to your function. @@ -271,20 +351,27 @@ Now you can declare your dependency using this class. Notice how we write `CommonQueryParams` twice in the above code: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// The last `CommonQueryParams`, in: @@ -300,77 +387,107 @@ From it is that FastAPI will extract the declared parameters and that is what Fa In this case, the first `CommonQueryParams`, in: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - commons: CommonQueryParams ... - ``` +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ...doesn't have any special meaning for **FastAPI**. FastAPI won't use it for data conversion, validation, etc. (as it is using the `Depends(CommonQueryParams)` for that). You could actually write just: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python - commons = Depends(CommonQueryParams) - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// ...as in: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` + +//// But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc: @@ -380,20 +497,27 @@ But declaring the type is encouraged as that way your editor will know what will But you see that we are having some code repetition here, writing `CommonQueryParams` twice: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// **FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will "call" to create an instance of the class itself. @@ -401,81 +525,114 @@ For those specific cases, you can do the following: Instead of writing: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ...you write: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` -=== "Python 3.8 non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8 non-Annotated - ```Python - commons: CommonQueryParams = Depends() - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// You declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`. The same example would then look like: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` + +//// ...and **FastAPI** will know what to do. -!!! tip - If that seems more confusing than helpful, disregard it, you don't *need* it. +/// tip + +If that seems more confusing than helpful, disregard it, you don't *need* it. + +It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition. - It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition. +/// diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 082417f11..7c3ac7922 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,40 +14,55 @@ The *path operation decorator* receives an optional argument `dependencies`. It should be a `list` of `Depends()`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*. -!!! tip - Some editors check for unused function parameters, and show them as errors. +/// tip + +Some editors check for unused function parameters, and show them as errors. - Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors. +Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors. - It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary. +It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary. -!!! info - In this example we use invented custom headers `X-Key` and `X-Token`. +/// - But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}. +/// info + +In this example we use invented custom headers `X-Key` and `X-Token`. + +But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}. + +/// ## Dependencies errors and return values @@ -57,51 +72,69 @@ You can use the same dependency *functions* you use normally. They can declare request requirements (like headers) or other sub-dependencies: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 non-Annotated -=== "Python 3.8 non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Raise exceptions These dependencies can `raise` exceptions, the same as normal dependencies: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 non-Annotated - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip -=== "Python 3.8 non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Return values @@ -109,26 +142,35 @@ And they can return values or not, the values won't be used. So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## Dependencies for a group of *path operations* diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index ad5aed932..279fc4d1e 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI supports dependencies that do some <abbr title='sometimes also called "e To do this, use `yield` instead of `return`, and write the extra steps (code) after. -!!! tip - Make sure to use `yield` one single time. +/// tip -!!! note "Technical Details" - Any function that is valid to use with: +Make sure to use `yield` one single time. - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +/// - would be valid to use as a **FastAPI** dependency. +/// note | "Technical Details" - In fact, FastAPI uses those two decorators internally. +Any function that is valid to use with: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + +would be valid to use as a **FastAPI** dependency. + +In fact, FastAPI uses those two decorators internally. + +/// ## A database dependency with `yield` @@ -39,10 +45,13 @@ The code following the `yield` statement is executed after the response has been {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip - You can use `async` or regular functions. +/// tip - **FastAPI** will do the right thing with each, the same as with normal dependencies. +You can use `async` or regular functions. + +**FastAPI** will do the right thing with each, the same as with normal dependencies. + +/// ## A dependency with `yield` and `try` @@ -66,26 +75,35 @@ 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`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 14 22" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +```Python hl_lines="6 14 22" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 13 21" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="5 13 21" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="4 12 20" - {!> ../../../docs_src/dependencies/tutorial008.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!} +``` + +//// And all of them can use `yield`. @@ -93,26 +111,35 @@ 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. -=== "Python 3.9+" +//// 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!} +``` + +//// - ```Python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="16-17 24-25" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` - ```Python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// 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. @@ -122,10 +149,13 @@ You can have any combinations of dependencies that you want. **FastAPI** will make sure everything is run in the correct order. -!!! note "Technical Details" - This works thanks to Python's <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>. +/// note | "Technical Details" + +This works thanks to Python's <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>. - **FastAPI** uses them internally to achieve this. +**FastAPI** uses them internally to achieve this. + +/// ## Dependencies with `yield` and `HTTPException` @@ -133,32 +163,43 @@ You saw that you can use dependencies with `yield` and have `try` blocks that ca The same way, you could raise an `HTTPException` or similar in the exit code, after the `yield`. -!!! tip +/// tip + +This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*. - This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*. +But it's there for you if you need it. 🤓 - But it's there for you if you need it. 🤓 +/// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18-22 31" +{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +``` - ```Python hl_lines="18-22 31" - {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="17-21 30" +{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17-21 30" - {!> ../../../docs_src/dependencies/tutorial008b_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="16-20 29" - {!> ../../../docs_src/dependencies/tutorial008b.py!} - ``` +/// + +```Python hl_lines="16-20 29" +{!> ../../../docs_src/dependencies/tutorial008b.py!} +``` + +//// An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. @@ -166,26 +207,35 @@ An alternative you could use to catch exceptions (and possibly also raise anothe If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +``` + +//// - ```Python hl_lines="15-16" - {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="14-15" +{!> ../../../docs_src/dependencies/tutorial008c_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="14-15" - {!> ../../../docs_src/dependencies/tutorial008c_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="13-14" - {!> ../../../docs_src/dependencies/tutorial008c.py!} - ``` +/// + +```Python hl_lines="13-14" +{!> ../../../docs_src/dependencies/tutorial008c.py!} +``` + +//// In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱 @@ -195,27 +245,35 @@ If you catch an exception in a dependency with `yield`, unless you are raising a You can re-raise the same exception using `raise`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial008d_an.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial008d_an.py!} - ``` +//// +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial008d.py!} - ``` +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial008d.py!} +``` + +//// Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎 @@ -258,22 +316,31 @@ participant tasks as Background tasks end ``` -!!! info - Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*. +/// info + +Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*. + +After one of those responses is sent, no other response can be sent. + +/// + +/// tip - After one of those responses is sent, no other response can be sent. +This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. -!!! tip - This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. +If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled. - If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled. +/// ## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks -!!! warning - You most probably don't need these technical details, you can skip this section and continue below. +/// warning - These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. +You most probably don't need these technical details, you can skip this section and continue below. + +These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. + +/// ### Dependencies with `yield` and `except`, Technical Details @@ -289,11 +356,13 @@ This was designed this way mainly to allow using the same objects "yielded" by d Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. -!!! tip +/// tip - Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). +Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). - So, this way you will probably have cleaner code. +So, this way you will probably have cleaner code. + +/// If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. @@ -321,10 +390,13 @@ When you create a dependency with `yield`, **FastAPI** will internally create a ### Using context managers in dependencies with `yield` -!!! warning - This is, more or less, an "advanced" idea. +/// warning + +This is, more or less, an "advanced" idea. - If you are just starting with **FastAPI** you might want to skip it for now. +If you are just starting with **FastAPI** you might want to skip it for now. + +/// In Python, you can create Context Managers by <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">creating a class with two methods: `__enter__()` and `__exit__()`</a>. @@ -335,16 +407,19 @@ You can also use them inside of **FastAPI** dependencies with `yield` by using {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - Another way to create a context manager is with: +/// tip + +Another way to create a context manager is with: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +using them to decorate a function with a single `yield`. - using them to decorate a function with a single `yield`. +That's what **FastAPI** uses internally for dependencies with `yield`. - That's what **FastAPI** uses internally for dependencies with `yield`. +But you don't have to use the decorators for FastAPI dependencies (and you shouldn't). - But you don't have to use the decorators for FastAPI dependencies (and you shouldn't). +FastAPI will do it for you internally. - FastAPI will do it for you internally. +/// diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md index 0dcf73176..03a9a42f0 100644 --- a/docs/en/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ Similar to the way you can [add `dependencies` to the *path operation decorators In that case, they will be applied to all the *path operations* in the application: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial012.py!} +``` + +//// And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app. diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index e05d40685..a608222f2 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -31,41 +31,57 @@ Let's first focus on the dependency. It is just a function that can take all the same parameters that a *path operation function* can take: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// That's it. @@ -85,90 +101,125 @@ In this case, this dependency expects: And then it just returns a `dict` containing those values. -!!! info - FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. +/// info + +FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. - If you have an older version, you would get errors when trying to use `Annotated`. +If you have an older version, you would get errors when trying to use `Annotated`. - Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. +Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. + +/// ### Import `Depends` -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### Declare the dependency, in the "dependant" The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently. @@ -180,8 +231,11 @@ You **don't call it** directly (don't add the parenthesis at the end), you just And that function takes parameters in the same way that *path operation functions* do. -!!! tip - You'll see what other "things", apart from functions, can be used as dependencies in the next chapter. +/// tip + +You'll see what other "things", apart from functions, can be used as dependencies in the next chapter. + +/// Whenever a new request arrives, **FastAPI** will take care of: @@ -202,10 +256,13 @@ common_parameters --> read_users This way you write shared code once and **FastAPI** takes care of calling it for your *path operations*. -!!! check - Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar. +/// check + +Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar. + +You just pass it to `Depends` and **FastAPI** knows how to do the rest. - You just pass it to `Depends` and **FastAPI** knows how to do the rest. +/// ## Share `Annotated` dependencies @@ -219,28 +276,37 @@ commons: Annotated[dict, Depends(common_parameters)] But because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip -!!! tip - This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**. +This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**. - But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎 +But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎 + +/// The dependencies will keep working as expected, and the **best part** is that the **type information will be preserved**, which means that your editor will be able to keep providing you with **autocompletion**, **inline errors**, etc. The same for other tools like `mypy`. @@ -256,8 +322,11 @@ And you can declare dependencies with `async def` inside of normal `def` *path o It doesn't matter. **FastAPI** will know what to do. -!!! note - If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} section about `async` and `await` in the docs. +/// note + +If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} section about `async` and `await` in the docs. + +/// ## Integrated with OpenAPI diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index e5def9b7d..85b252e13 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -10,41 +10,57 @@ They can be as **deep** as you need them to be. You could create a first dependency ("dependable") like: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9-10" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.10 non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="9-10" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// It declares an optional query parameter `q` as a `str`, and then it just returns it. @@ -54,41 +70,57 @@ This is quite simple (not very useful), but will help us focus on how the sub-de Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 non-Annotated - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Let's focus on the parameters declared: @@ -101,46 +133,65 @@ Let's focus on the parameters declared: Then we can use the dependency with: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10 non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +/// info -!!! info - Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`. +Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`. - But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it. +But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it. + +/// ```mermaid graph TB @@ -161,22 +212,29 @@ And it will save the returned value in a <abbr title="A utility/system to store In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` - ```Python hl_lines="1" - async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): - return {"fresh_value": fresh_value} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1" - async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): - return {"fresh_value": fresh_value} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// ## Recap @@ -186,9 +244,12 @@ Just functions that look the same as the *path operation functions*. But still, it is very powerful, and allows you to declare arbitrarily deeply nested dependency "graphs" (trees). -!!! tip - All this might not seem as useful with these simple examples. +/// tip + +All this might not seem as useful with these simple examples. + +But you will see how useful it is in the chapters about **security**. - But you will see how useful it is in the chapters about **security**. +And you will also see the amounts of code it will save you. - And you will also see the amounts of code it will save you. +/// diff --git a/docs/en/docs/tutorial/encoder.md b/docs/en/docs/tutorial/encoder.md index 845cc25fc..c110a2ac5 100644 --- a/docs/en/docs/tutorial/encoder.md +++ b/docs/en/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ You can use `jsonable_encoder` for that. It receives an object, like a Pydantic model, and returns a JSON compatible version: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`. @@ -38,5 +42,8 @@ The result of calling it is something that can be encoded with the Python standa It doesn't return a large `str` containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a `dict`) with values and sub-values that are all compatible with JSON. -!!! note - `jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios. +/// note + +`jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios. + +/// diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index e705a18e4..aed9f7880 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ Here are some of the additional data types you can use: Here's an example *path operation* with parameters using some of the above types. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index cc0680cfd..982f59782 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -8,31 +8,41 @@ This is especially the case for user models, because: * The **output model** should not have a password. * The **database model** would probably need to have a hashed password. -!!! danger - Never store user's plaintext passwords. Always store a "secure hash" that you can then verify. +/// danger - If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Never store user's plaintext passwords. Always store a "secure hash" that you can then verify. + +If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// ## Multiple models Here's a general idea of how the models could look like with their password fields and the places where they are used: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +/// ### About `**user_in.dict()` @@ -144,8 +154,11 @@ UserInDB( ) ``` -!!! warning - The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security. +/// warning + +The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security. + +/// ## Reduce duplication @@ -163,17 +176,21 @@ All the data conversion, validation, documentation, etc. will still work as norm That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` or `anyOf` @@ -183,20 +200,27 @@ It will be defined in OpenAPI with `anyOf`. To do that, use the standard Python type hint <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: -!!! note - When defining a <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. +/// note -=== "Python 3.10+" +When defining a <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ### `Union` in Python 3.10 @@ -218,17 +242,21 @@ The same way, you can declare responses of lists of objects. For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +//// ## Response with arbitrary `dict` @@ -238,17 +266,21 @@ This is useful if you don't know the valid field/attribute names (that would be In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above): -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index d18b25d97..b48a0ee38 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -163,10 +163,13 @@ You could also use it to generate code automatically, for clients that communica `FastAPI` is a Python class that provides all the functionality for your API. -!!! note "Technical Details" - `FastAPI` is a class that inherits directly from `Starlette`. +/// note | "Technical Details" - You can use all the <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> functionality with `FastAPI` too. +`FastAPI` is a class that inherits directly from `Starlette`. + +You can use all the <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> functionality with `FastAPI` too. + +/// ### Step 2: create a `FastAPI` "instance" @@ -196,8 +199,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - A "path" is also commonly called an "endpoint" or a "route". +/// info + +A "path" is also commonly called an "endpoint" or a "route". + +/// While building an API, the "path" is the main way to separate "concerns" and "resources". @@ -247,16 +253,19 @@ The `@app.get("/")` tells **FastAPI** that the function right below is in charge * the path `/` * using a <abbr title="an HTTP GET method"><code>get</code> operation</abbr> -!!! info "`@decorator` Info" - That `@something` syntax in Python is called a "decorator". +/// info | "`@decorator` Info" + +That `@something` syntax in Python is called a "decorator". - You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from). +You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from). - A "decorator" takes the function below and does something with it. +A "decorator" takes the function below and does something with it. - In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`. +In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`. - It is the "**path operation decorator**". +It is the "**path operation decorator**". + +/// You can also use the other operations: @@ -271,14 +280,17 @@ And the more exotic ones: * `@app.patch()` * `@app.trace()` -!!! tip - You are free to use each operation (HTTP method) as you wish. +/// tip + +You are free to use each operation (HTTP method) as you wish. + +**FastAPI** doesn't enforce any specific meaning. - **FastAPI** doesn't enforce any specific meaning. +The information here is presented as a guideline, not a requirement. - The information here is presented as a guideline, not a requirement. +For example, when using GraphQL you normally perform all the actions using only `POST` operations. - For example, when using GraphQL you normally perform all the actions using only `POST` operations. +/// ### Step 4: define the **path operation function** @@ -306,8 +318,11 @@ You could also define it as a normal function instead of `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Step 5: return the content diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 6133898e4..ca3cff661 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ But if the client requests `http://example.com/items/bar` (a non-existent `item_ } ``` -!!! tip - When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`. +/// tip - You could pass a `dict`, a `list`, etc. +When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`. - They are handled automatically by **FastAPI** and converted to JSON. +You could pass a `dict`, a `list`, etc. + +They are handled automatically by **FastAPI** and converted to JSON. + +/// ## Add custom headers @@ -106,10 +109,13 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Technical Details" - You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. +/// note | "Technical Details" + +You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`. +/// ## Override the default exception handlers @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` vs `ValidationError` -!!! warning - These are technical details that you might skip if it's not important for you now. +/// warning + +These are technical details that you might skip if it's not important for you now. + +/// `RequestValidationError` is a sub-class of Pydantic's <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. @@ -183,10 +192,13 @@ For example, you could want to return a plain text response instead of JSON for {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.responses import PlainTextResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import PlainTextResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ### Use the `RequestValidationError` body diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index bbba90998..cc5975b85 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ You can define Header parameters the same way you define `Query`, `Path` and `Co First import `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// ## Declare `Header` parameters @@ -48,49 +64,71 @@ Then declare the header parameters using the same structure as with `Path`, `Que The first value is the default value, you can pass all the extra validation or annotation parameters: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! note "Technical Details" - `Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class. +/// - But remember that when you import `Query`, `Path`, `Header`, and others from `fastapi`, those are actually functions that return special classes. +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` -!!! info - To declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters. +//// + +/// note | "Technical Details" + +`Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class. + +But remember that when you import `Query`, `Path`, `Header`, and others from `fastapi`, those are actually functions that return special classes. + +/// + +/// info + +To declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters. + +/// ## Automatic conversion @@ -108,44 +146,63 @@ So, you can use `user_agent` as you normally would in Python code, instead of ne If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11" +{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/header_params/tutorial002_an.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! warning - Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores. +/// + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` + +//// + +/// warning + +Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores. + +/// ## Duplicate headers @@ -157,50 +214,71 @@ You will receive all the values from the duplicate header as a Python `list`. For example, to declare a header of `X-Token` that can appear more than once, you can write: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.9+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// If you communicate with that *path operation* sending two HTTP headers like: diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index f22dc01dd..5f8c51c4c 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -83,10 +83,13 @@ $ pip install "fastapi[standard]" </div> -!!! note - When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies. +/// note - If you don't want to have those optional dependencies, you can instead install `pip install fastapi`. +When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies. + +If you don't want to have those optional dependencies, you can instead install `pip install fastapi`. + +/// ## Advanced User Guide diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index 4dce9af13..c62509b8b 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -22,8 +22,11 @@ You can set them as follows: {!../../../docs_src/metadata/tutorial001.py!} ``` -!!! tip - You can write Markdown in the `description` field and it will be rendered in the output. +/// tip + +You can write Markdown in the `description` field and it will be rendered in the output. + +/// With this configuration, the automatic API docs would look like: @@ -65,8 +68,11 @@ Create metadata for your tags and pass it to the `openapi_tags` parameter: Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_). -!!! tip - You don't have to add metadata for all the tags that you use. +/// tip + +You don't have to add metadata for all the tags that you use. + +/// ### Use your tags @@ -76,8 +82,11 @@ Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assig {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info - Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}. +/// info + +Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// ### Check the docs diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 492a1b065..f0b3faf3b 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ A "middleware" is a function that works with every **request** before it is proc * It can do something to that **response** or run any needed code. * Then it returns the **response**. -!!! note "Technical Details" - If you have dependencies with `yield`, the exit code will run *after* the middleware. +/// note | "Technical Details" - If there were any background tasks (documented later), they will run *after* all the middleware. +If you have dependencies with `yield`, the exit code will run *after* the middleware. + +If there were any background tasks (documented later), they will run *after* all the middleware. + +/// ## Create a middleware @@ -32,15 +35,21 @@ The middleware function receives: {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>. +/// tip + +Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>. + +But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>. + +/// + +/// note | "Technical Details" - But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>. +You could also use `from starlette.requests import Request`. -!!! note "Technical Details" - You could also use `from starlette.requests import Request`. +**FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette. +/// ### Before and after the `response` diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index babf85acb..a1a4953a6 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ There are several parameters that you can pass to your *path operation decorator* to configure it. -!!! warning - Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*. +/// warning + +Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*. + +/// ## Response Status Code @@ -13,52 +16,67 @@ You can pass directly the `int` code, like `404`. But if you don't remember what each number code is for, you can use the shortcut constants in `status`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// That status code will be used in the response and will be added to the OpenAPI schema. -!!! note "Technical Details" - You could also use `from starlette import status`. +/// note | "Technical Details" + +You could also use `from starlette import status`. + +**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. +/// ## Tags You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// They will be added to the OpenAPI schema and used by the automatic documentation interfaces: @@ -80,23 +98,29 @@ In these cases, it could make sense to store the tags in an `Enum`. You can add a `summary` and `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// ## Description from docstring @@ -104,23 +128,29 @@ As descriptions tend to be long and cover multiple lines, you can declare the *p You can write <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// It will be used in the interactive docs: @@ -130,31 +160,43 @@ It will be used in the interactive docs: You can specify the response description with the parameter `response_description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check -!!! info - Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general. +OpenAPI specifies that each *path operation* requires a response description. -!!! check - OpenAPI specifies that each *path operation* requires a response description. +So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response". - So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response". +/// <img src="/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index ca86ad226..bd835d0d4 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ In the same way that you can declare more validations and metadata for query par First, import `Path` from `fastapi`, and import `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. -!!! info - FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. +If you have an older version, you would get errors when trying to use `Annotated`. - If you have an older version, you would get errors when trying to use `Annotated`. +Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. - Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. +/// ## Declare metadata @@ -55,49 +74,71 @@ You can declare all the same parameters as for `Query`. For example, to declare a `title` metadata value for the path parameter `item_id` you can type: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! note - A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note + +A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. + +/// ## Order the parameters as you need -!!! tip - This is probably not as important or necessary if you use `Annotated`. +/// tip + +This is probably not as important or necessary if you use `Annotated`. + +/// Let's say that you want to declare the query parameter `q` as a required `str`. @@ -113,33 +154,45 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names, So, you can declare your function as: -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated + +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` + +//// ## Order the parameters as you need, tricks -!!! tip - This is probably not as important or necessary if you use `Annotated`. +/// tip + +This is probably not as important or necessary if you use `Annotated`. + +/// Here's a **small trick** that can be handy, but you won't need it often. @@ -164,17 +217,21 @@ Python won't do anything with that `*`, but it will know that all the following Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Number validations: greater than or equal @@ -182,26 +239,35 @@ With `Query` and `Path` (and others you'll see later) you can declare number con Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Number validations: greater than and less than or equal @@ -210,26 +276,35 @@ The same applies for: * `gt`: `g`reater `t`han * `le`: `l`ess than or `e`qual -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Number validations: floats, greater than and less than @@ -241,26 +316,35 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not. And the same for <abbr title="less than"><code>lt</code></abbr>. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Recap @@ -273,18 +357,24 @@ And you can also declare numeric validations: * `lt`: `l`ess `t`han * `le`: `l`ess than or `e`qual -!!! info - `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class. +/// info + +`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class. + +All of them share the same parameters for additional validation and metadata you have seen. + +/// + +/// note | "Technical Details" - All of them share the same parameters for additional validation and metadata you have seen. +When you import `Query`, `Path` and others from `fastapi`, they are actually functions. -!!! note "Technical Details" - When you import `Query`, `Path` and others from `fastapi`, they are actually functions. +That when called, return instances of classes of the same name. - That when called, return instances of classes of the same name. +So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`. - So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`. +These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types. - These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types. +That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors. - That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors. +/// diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index 6246d6680..a87a29e08 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ You can declare the type of a path parameter in the function, using standard Pyt In this case, `item_id` is declared to be an `int`. -!!! check - This will give you editor support inside of your function, with error checks, completion, etc. +/// check + +This will give you editor support inside of your function, with error checks, completion, etc. + +/// ## Data <abbr title="also known as: serialization, parsing, marshalling">conversion</abbr> @@ -35,10 +38,13 @@ If you run this example and open your browser at <a href="http://127.0.0.1:8000/ {"item_id":3} ``` -!!! check - Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`. +/// check + +Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`. + +So, with that type declaration, **FastAPI** gives you automatic request <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>. - So, with that type declaration, **FastAPI** gives you automatic request <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>. +/// ## Data validation @@ -65,12 +71,15 @@ because the path parameter `item_id` had a value of `"foo"`, which is not an `in The same error would appear if you provided a `float` instead of an `int`, as in: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! check - So, with the same Python type declaration, **FastAPI** gives you data validation. +/// check - Notice that the error also clearly states exactly the point where the validation didn't pass. +So, with the same Python type declaration, **FastAPI** gives you data validation. - This is incredibly helpful while developing and debugging code that interacts with your API. +Notice that the error also clearly states exactly the point where the validation didn't pass. + +This is incredibly helpful while developing and debugging code that interacts with your API. + +/// ## Documentation @@ -78,10 +87,13 @@ And when you open your browser at <a href="http://127.0.0.1:8000/docs" class="ex <img src="/img/tutorial/path-params/image01.png"> -!!! check - Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI). +/// check + +Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI). + +Notice that the path parameter is declared to be an integer. - Notice that the path parameter is declared to be an integer. +/// ## Standards-based benefits, alternative documentation @@ -141,11 +153,17 @@ Then create class attributes with fixed values, which will be the available vali {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (or enums) are available in Python</a> since version 3.4. +/// info -!!! tip - If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning <abbr title="Technically, Deep Learning model architectures">models</abbr>. +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (or enums) are available in Python</a> since version 3.4. + +/// + +/// tip + +If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning <abbr title="Technically, Deep Learning model architectures">models</abbr>. + +/// ### Declare a *path parameter* @@ -181,8 +199,11 @@ You can get the actual value (a `str` in this case) using `model_name.value`, or {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip - You could also access the value `"lenet"` with `ModelName.lenet.value`. +/// tip + +You could also access the value `"lenet"` with `ModelName.lenet.value`. + +/// #### Return *enumeration members* @@ -235,10 +256,13 @@ So, you can use it with: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip - You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`). +/// tip + +You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`). + +In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`. - In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`. +/// ## Recap diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index da8e53720..ce7d0580d 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ Let's take this application as example: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. -!!! note - FastAPI will know that the value of `q` is not required because of the default value `= None`. +/// note - The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors. +FastAPI will know that the value of `q` is not required because of the default value `= None`. + +The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors. + +/// ## Additional validation @@ -34,30 +41,37 @@ To achieve that, first import: * `Query` from `fastapi` * `Annotated` from `typing` (or from `typing_extensions` in Python below 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ + +In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. + +```Python hl_lines="1 3" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// - In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. +//// tab | Python 3.8+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`. -=== "Python 3.8+" +It will already be installed with FastAPI. + +```Python hl_lines="3-4" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`. +//// - It will already be installed with FastAPI. +/// info - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. -!!! info - FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. +If you have an older version, you would get errors when trying to use `Annotated`. - If you have an older version, you would get errors when trying to use `Annotated`. +Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. - Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. +/// ## Use `Annotated` in the type for the `q` parameter @@ -67,31 +81,39 @@ Now it's the time to use it with FastAPI. 🚀 We had this type annotation: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: str | None = None - ``` +```Python +q: str | None = None +``` -=== "Python 3.8+" +//// - ```Python - q: Union[str, None] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// What we will do is wrap that with `Annotated`, so it becomes: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: Annotated[str | None] = None - ``` +```Python +q: Annotated[str | None] = None +``` -=== "Python 3.8+" +//// - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// Both of those versions mean the same thing, `q` is a parameter that can be a `str` or `None`, and by default, it is `None`. @@ -101,25 +123,31 @@ Now let's jump to the fun stuff. 🎉 Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` + +//// Notice that the default value is still `None`, so the parameter is still optional. But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to have **additional validation** for this value, we want it to have maximum 50 characters. 😎 -!!! tip +/// tip + +Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`. - Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`. +/// FastAPI will now: @@ -131,22 +159,29 @@ FastAPI will now: Previous versions of FastAPI (before <abbr title="before 2023-03">0.95.0</abbr>) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you. -!!! tip - For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰 +/// tip + +For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰 + +/// This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI). @@ -176,22 +211,25 @@ q: str | None = None But it declares it explicitly as being a query parameter. -!!! info - Keep in mind that the most important part to make a parameter optional is the part: +/// info - ```Python - = None - ``` +Keep in mind that the most important part to make a parameter optional is the part: - or the: +```Python += None +``` - ```Python - = Query(default=None) - ``` +or the: - as it will use that `None` as the default value, and that way make the parameter **not required**. +```Python += Query(default=None) +``` + +as it will use that `None` as the default value, and that way make the parameter **not required**. + +The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. - The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. +/// Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings: @@ -243,81 +281,113 @@ Because `Annotated` can have more than one metadata annotation, you could now ev You can also add a parameter `min_length`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +//// ## Add regular expressions You can define a <abbr title="A regular expression, regex or regexp is a sequence of characters that define a search pattern for strings.">regular expression</abbr> `pattern` that the parameter should match: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="12" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +//// This specific regular expression pattern checks that the received parameter value: @@ -335,11 +405,13 @@ Before Pydantic version 2 and before FastAPI 0.100.0, the parameter was called ` You could still see some code using it: -=== "Python 3.10+ Pydantic v1" +//// tab | Python 3.10+ Pydantic v1 + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} - ``` +//// But know that this is deprecated and it should be updated to use the new parameter `pattern`. 🤓 @@ -349,29 +421,41 @@ You can, of course, use default values other than `None`. Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +/// note -!!! note - Having a default value of any type, including `None`, makes the parameter optional (not required). +Having a default value of any type, including `None`, makes the parameter optional (not required). + +/// ## Make it required @@ -389,75 +473,103 @@ q: Union[str, None] = None But we are now declaring it with `Query`, for example like: -=== "Annotated" +//// tab | Annotated - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// -=== "non-Annotated" +//// tab | non-Annotated - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +//// So, when you need to declare a value as required while using `Query`, you can simply not declare a default value: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +``` -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` +Still, probably better to use the `Annotated` version. 😉 - !!! tip - Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`. +/// - Still, probably better to use the `Annotated` version. 😉 +//// ### Required with Ellipsis (`...`) There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +/// info -!!! info - If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>. +If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>. - It is used by Pydantic and FastAPI to explicitly declare that a value is required. +It is used by Pydantic and FastAPI to explicitly declare that a value is required. + +/// This will let **FastAPI** know that this parameter is required. @@ -467,47 +579,69 @@ You can declare that a parameter can accept `None`, but that it's still required To do that, you can declare that `None` is a valid type but still use `...` as the default: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +/// -!!! tip - Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` -!!! tip - Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`. +//// + +/// tip + +Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. + +/// + +/// tip + +Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`. + +/// ## Query parameter list / multiple values @@ -515,50 +649,71 @@ When you define a query parameter explicitly with `Query` you can also declare i For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.9+" +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.9+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` -=== "Python 3.9+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +//// Then, with a URL like: @@ -579,8 +734,11 @@ So, the response to that URL would be: } ``` -!!! tip - To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body. +/// tip + +To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body. + +/// The interactive API docs will update accordingly, to allow multiple values: @@ -590,35 +748,49 @@ The interactive API docs will update accordingly, to allow multiple values: And you can also define a default `list` of values if none are provided: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` +/// -=== "Python 3.9+ non-Annotated" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` + +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +//// If you go to: @@ -641,31 +813,43 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` +/// note -!!! note - Keep in mind that in this case, FastAPI won't check the contents of the list. +Keep in mind that in this case, FastAPI won't check the contents of the list. - For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. +For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. + +/// ## Declare more metadata @@ -673,86 +857,121 @@ You can add more information about the parameter. That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools. -!!! note - Keep in mind that different tools might have different levels of OpenAPI support. +/// note + +Keep in mind that different tools might have different levels of OpenAPI support. - Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. +Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. + +/// You can add a `title`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +//// And a `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` + +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +//// ## Alias parameters @@ -772,41 +991,57 @@ But you still need it to be exactly `item-query`... Then you can declare an `alias`, and that alias is what will be used to find the parameter value: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +//// ## Deprecating parameters @@ -816,41 +1051,57 @@ You have to leave it there a while because there are clients using it, but you w Then pass the parameter `deprecated=True` to `Query`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// The docs will show it like this: @@ -860,41 +1111,57 @@ The docs will show it like this: To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index bc3b11948..a98ac9b28 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ The parameter values in your function will be: The same way, you can declare optional query parameters, by setting their default to `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// In this case, the function parameter `q` will be optional, and will be `None` by default. -!!! check - Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter. +/// check + +Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter. + +/// ## Query parameter type conversion You can also declare `bool` types, and they will be converted: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// In this case, if you go to: @@ -137,17 +148,21 @@ And you don't have to declare them in any specific order. They will be detected by name: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Required query parameters @@ -205,17 +220,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy And of course, you can define some parameters as required, some as having a default value, and some entirely optional: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// In this case, there are 3 query parameters: @@ -223,5 +242,8 @@ In this case, there are 3 query parameters: * `skip`, an `int` with a default value of `0`. * `limit`, an optional `int`. -!!! tip - You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip + +You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. + +/// diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 17ac3b25d..ceaea3626 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -2,70 +2,97 @@ You can define files to be uploaded by the client using `File`. -!!! info - To receive uploaded files, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info - E.g. `pip install python-multipart`. +To receive uploaded files, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. - This is because uploaded files are sent as "form data". +E.g. `pip install python-multipart`. + +This is because uploaded files are sent as "form data". + +/// ## Import `File` Import `File` and `UploadFile` from `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// ## Define `File` Parameters Create file parameters the same way you would for `Body` or `Form`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +/// info -=== "Python 3.8+ non-Annotated" +`File` is a class that inherits directly from `Form`. - !!! tip - Prefer to use the `Annotated` version if possible. +But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes. - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// -!!! info - `File` is a class that inherits directly from `Form`. +/// tip - But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes. +To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters. -!!! tip - To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters. +/// The files will be uploaded as "form data". @@ -79,26 +106,35 @@ But there are several cases in which you might benefit from using `UploadFile`. Define a file parameter with a type of `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// Using `UploadFile` has several advantages over `bytes`: @@ -141,11 +177,17 @@ If you are inside of a normal `def` *path operation function*, you can access th contents = myfile.file.read() ``` -!!! note "`async` Technical Details" - When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them. +/// note | "`async` Technical Details" + +When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them. + +/// + +/// note | "Starlette Technical Details" -!!! note "Starlette Technical Details" - **FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI. +**FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI. + +/// ## What is "Form Data" @@ -153,82 +195,113 @@ The way HTML forms (`<form></form>`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -!!! note "Technical Details" - Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files. +/// note | "Technical Details" + +Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files. + +But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body. + +If you want to read more about these encodings and form fields, head to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>. + +/// - But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body. +/// warning - If you want to read more about these encodings and form fields, head to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>. +You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. -!!! warning - You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. +This is not a limitation of **FastAPI**, it's part of the HTTP protocol. - This is not a limitation of **FastAPI**, it's part of the HTTP protocol. +/// ## Optional File Upload You can make a file optional by using standard type annotations and setting a default value of `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// ## `UploadFile` with Additional Metadata You can also use `File()` with `UploadFile`, for example, to set additional metadata: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="8 14" - {!> ../../../docs_src/request_files/tutorial001_03_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +//// ## Multiple File Uploads @@ -238,76 +311,107 @@ They would be associated to the same "form field" sent using "form data". To use that, declare a list of `bytes` or `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` -=== "Python 3.9+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.9+ non-Annotated - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// You will receive, as declared, a `list` of `bytes` or `UploadFile`s. -!!! note "Technical Details" - You could also use `from starlette.responses import HTMLResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import HTMLResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ### Multiple File Uploads with Additional Metadata And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+ non-Annotated" +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 676ed35ad..9b4342652 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,91 @@ You can define files and form fields at the same time using `File` and `Form`. -!!! info - To receive uploaded files and/or form data, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info - E.g. `pip install python-multipart`. +To receive uploaded files and/or form data, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +E.g. `pip install python-multipart`. + +/// ## Import `File` and `Form` -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// ## Define `File` and `Form` parameters Create file and form parameters the same way you would for `Body` or `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10-12" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="9-11" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +//// The files and form fields will be uploaded as form data and you will receive the files and form fields. And you can declare some of the files as `bytes` and some as `UploadFile`. -!!! warning - You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. +/// warning + +You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. + +This is not a limitation of **FastAPI**, it's part of the HTTP protocol. - This is not a limitation of **FastAPI**, it's part of the HTTP protocol. +/// ## Recap diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 5f8f7b148..88b5b86b6 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ When you need to receive form fields instead of JSON, you can use `Form`. -!!! info - To use forms, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info - E.g. `pip install python-multipart`. +To use forms, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +E.g. `pip install python-multipart`. + +/// ## Import `Form` Import `Form` from `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## Define `Form` parameters Create form parameters the same way you would for `Body` or `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields. @@ -63,11 +84,17 @@ The <abbr title="specification">spec</abbr> requires the fields to be exactly na With `Form` you can declare the same configurations as with `Body` (and `Query`, `Path`, `Cookie`), including validation, examples, an alias (e.g. `user-name` instead of `username`), etc. -!!! info - `Form` is a class that inherits directly from `Body`. +/// info + +`Form` is a class that inherits directly from `Body`. + +/// + +/// tip -!!! tip - To declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters. +To declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters. + +/// ## About "Form Fields" @@ -75,17 +102,23 @@ The way HTML forms (`<form></form>`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -!!! note "Technical Details" - Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`. +/// note | "Technical Details" + +Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`. + +But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter. + +If you want to read more about these encodings and form fields, head to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>. + +/// - But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter. +/// warning - If you want to read more about these encodings and form fields, head to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>. +You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`. -!!! warning - You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`. +This is not a limitation of **FastAPI**, it's part of the HTTP protocol. - This is not a limitation of **FastAPI**, it's part of the HTTP protocol. +/// ## Recap diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 75d5df106..8a2dccc81 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ You can declare the type used for the response by annotating the *path operation You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +//// FastAPI will use this return type to: @@ -53,35 +59,47 @@ You can use the `response_model` parameter in any of the *path operations*: * `@app.delete()` * etc. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note - Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. +//// + +/// note + +Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. + +/// `response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`. FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration. -!!! tip - If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`. +/// tip + +If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`. + +That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`. - That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`. +/// ### `response_model` Priority @@ -95,37 +113,48 @@ You can also use `response_model=None` to disable creating a response model for Here we are declaring a `UserIn` model, it will contain a plaintext password: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. -!!! info - To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +E.g. `pip install email-validator` +or `pip install pydantic[email]`. - E.g. `pip install email-validator` - or `pip install pydantic[email]`. +/// And we are using this model to declare our input and the same model to declare our output: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// Now, whenever a browser is creating a user with a password, the API will return the same password in the response. @@ -133,52 +162,67 @@ In this case, it might not be a problem, because it's the same user sending the But if we use the same model for another *path operation*, we could be sending our user's passwords to every client. -!!! danger - Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing. +/// danger + +Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing. + +/// ## Add an output model We can instead create an input model with the plaintext password and an output model without it: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// Here, even though our *path operation function* is returning the same input user that contains the password: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// ...we declared the `response_model` to be our model `UserOut`, that doesn't include the password: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic). @@ -202,17 +246,21 @@ But in most of the cases where we need to do something like this, we want the mo And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` + +//// - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI. @@ -278,17 +326,21 @@ But when you return some other arbitrary object that is not a valid Pydantic typ The same would happen if you had something like a <abbr title='A union between multiple types means "any of these types".'>union</abbr> between different types where one or more of them are not valid Pydantic types, for example this would fail 💥: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +//// ...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`. @@ -300,17 +352,21 @@ But you might want to still keep the return type annotation in the function to g In this case, you can disable the response model generation by setting `response_model=None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` + +//// This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓 @@ -318,23 +374,29 @@ This will make FastAPI skip the response model generation and that way you can h Your response model could have default values, like: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// * `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`. * `tax: float = 10.5` has a default of `10.5`. @@ -348,23 +410,29 @@ For example, if you have models with many optional attributes in a NoSQL databas You can set the *path operation decorator* parameter `response_model_exclude_unset=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// and those default values won't be included in the response, only the values actually set. @@ -377,21 +445,30 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t } ``` -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +/// info + +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + +/// + +/// info + +FastAPI uses Pydantic model's `.dict()` with <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this. - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +/// -!!! info - FastAPI uses Pydantic model's `.dict()` with <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this. +/// info -!!! info - You can also use: +You can also use: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - as described in <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`. +as described in <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`. + +/// #### Data with values for fields with defaults @@ -426,10 +503,13 @@ FastAPI is smart enough (actually, Pydantic is smart enough) to realize that, ev So, they will be included in the JSON response. -!!! tip - Notice that the default values can be anything, not only `None`. +/// tip + +Notice that the default values can be anything, not only `None`. + +They can be a list (`[]`), a `float` of `10.5`, etc. - They can be a list (`[]`), a `float` of `10.5`, etc. +/// ### `response_model_include` and `response_model_exclude` @@ -439,45 +519,59 @@ They take a `set` of `str` with the name of the attributes to include (omitting This can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the output. -!!! tip - But it is still recommended to use the ideas above, using multiple classes, instead of these parameters. +/// tip - This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes. +But it is still recommended to use the ideas above, using multiple classes, instead of these parameters. - This also applies to `response_model_by_alias` that works similarly. +This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes. -=== "Python 3.10+" +This also applies to `response_model_by_alias` that works similarly. - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` -!!! tip - The syntax `{"name", "description"}` creates a `set` with those two values. +//// - It is equivalent to `set(["name", "description"])`. +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` + +//// + +/// tip + +The syntax `{"name", "description"}` creates a `set` with those two values. + +It is equivalent to `set(["name", "description"])`. + +/// #### Using `list`s instead of `set`s If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 646378aa1..2613bf73d 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ The same way you can specify a response model, you can also declare the HTTP sta {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note - Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. +/// note + +Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. + +/// The `status_code` parameter receives a number with the HTTP status code. -!!! info - `status_code` can alternatively also receive an `IntEnum`, such as Python's <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. +/// info + +`status_code` can alternatively also receive an `IntEnum`, such as Python's <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. + +/// It will: @@ -27,15 +33,21 @@ It will: <img src="/img/tutorial/response-status-code/image01.png"> -!!! note - Some response codes (see the next section) indicate that the response does not have a body. +/// note + +Some response codes (see the next section) indicate that the response does not have a body. + +FastAPI knows this, and will produce OpenAPI docs that state there is no response body. - FastAPI knows this, and will produce OpenAPI docs that state there is no response body. +/// ## About HTTP status codes -!!! note - If you already know what HTTP status codes are, skip to the next section. +/// note + +If you already know what HTTP status codes are, skip to the next section. + +/// In HTTP, you send a numeric status code of 3 digits as part of the response. @@ -54,8 +66,11 @@ In short: * For generic errors from the client, you can just use `400`. * `500` and above are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes. -!!! tip - To know more about each status code and which code is for what, check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentation about HTTP status codes</a>. +/// tip + +To know more about each status code and which code is for what, check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentation about HTTP status codes</a>. + +/// ## Shortcut to remember the names @@ -79,10 +94,13 @@ They are just a convenience, they hold the same number, but that way you can use <img src="/img/tutorial/response-status-code/image02.png"> -!!! note "Technical Details" - You could also use `from starlette import status`. +/// note | "Technical Details" + +You could also use `from starlette import status`. + +**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. +/// ## Changing the default diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 40231dc0b..141a0bc55 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -8,71 +8,93 @@ Here are several ways to do it. You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema. -=== "Python 3.10+ Pydantic v2" +//// tab | Python 3.10+ Pydantic v2 - ```Python hl_lines="13-24" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-24" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.10+ Pydantic v1" +//// - ```Python hl_lines="13-23" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} - ``` +//// tab | Python 3.10+ Pydantic v1 -=== "Python 3.8+ Pydantic v2" +```Python hl_lines="13-23" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +``` - ```Python hl_lines="15-26" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// -=== "Python 3.8+ Pydantic v1" +//// tab | Python 3.8+ Pydantic v2 - ```Python hl_lines="15-25" - {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} - ``` +```Python hl_lines="15-26" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// + +//// tab | Python 3.8+ Pydantic v1 + +```Python hl_lines="15-25" +{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +``` + +//// That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs. -=== "Pydantic v2" +//// tab | Pydantic v2 + +In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic's docs: Model Config</a>. + +You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. - In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic's docs: Model Config</a>. +//// - You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. +//// tab | Pydantic v1 -=== "Pydantic v1" +In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic's docs: Schema customization</a>. - In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic's docs: Schema customization</a>. +You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. - You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. +//// -!!! tip - You could use the same technique to extend the JSON Schema and add your own custom extra info. +/// tip - For example you could use it to add metadata for a frontend user interface, etc. +You could use the same technique to extend the JSON Schema and add your own custom extra info. -!!! info - OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard. +For example you could use it to add metadata for a frontend user interface, etc. - Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓 +/// - You can read more at the end of this page. +/// info + +OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard. + +Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓 + +You can read more at the end of this page. + +/// ## `Field` additional arguments When using `Field()` with Pydantic models, you can also declare additional `examples`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// ## `examples` in JSON Schema - OpenAPI @@ -92,41 +114,57 @@ you can also declare a group of `examples` with additional information that will Here we pass `examples` containing one example of the data expected in `Body()`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` - ```Python hl_lines="23-30" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="23-30" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` - ```Python hl_lines="18-25" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="20-27" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="18-25" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="20-27" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### Example in the docs UI @@ -138,41 +176,57 @@ With any of the methods above it would look like this in the `/docs`: You can of course also pass multiple `examples`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24-39" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` - ```Python hl_lines="24-39" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="19-34" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="19-34" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - ```Python hl_lines="21-36" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="21-36" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// When you do this, the examples will be part of the internal **JSON Schema** for that body data. @@ -213,41 +267,57 @@ Each specific example `dict` in the `examples` can contain: You can use it like this: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +``` - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial005.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +``` + +//// ### OpenAPI Examples in the Docs UI @@ -257,17 +327,23 @@ With `openapi_examples` added to `Body()` the `/docs` would look like: ## Technical Details -!!! tip - If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details. +/// tip + +If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details. + +They are more relevant for older versions, before OpenAPI 3.1.0 was available. + +You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓 - They are more relevant for older versions, before OpenAPI 3.1.0 was available. +/// - You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓 +/// warning -!!! warning - These are very technical details about the standards **JSON Schema** and **OpenAPI**. +These are very technical details about the standards **JSON Schema** and **OpenAPI**. - If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them. +If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them. + +/// Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**. @@ -285,8 +361,11 @@ OpenAPI also added `example` and `examples` fields to other parts of the specifi * `File()` * `Form()` -!!! info - This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`. +/// info + +This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`. + +/// ### JSON Schema's `examples` field @@ -298,10 +377,13 @@ And now this new `examples` field takes precedence over the old single (and cust This new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above). -!!! info - Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉). +/// info + +Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉). + +Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0. - Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0. +/// ### Pydantic and FastAPI `examples` diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index d8682a054..ed427a282 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -20,38 +20,49 @@ Let's first just use the code and see how it works, and then we'll come back to Copy the example in a file `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` +//// ## Run it -!!! info - The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. +/// info - However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: +The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. - `pip install python-multipart` +However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: - This is because **OAuth2** uses "form data" for sending the `username` and `password`. +`pip install python-multipart` + +This is because **OAuth2** uses "form data" for sending the `username` and `password`. + +/// Run the example with: @@ -73,17 +84,23 @@ You will see something like this: <img src="/img/tutorial/security/image01.png"> -!!! check "Authorize button!" - You already have a shiny new "Authorize" button. +/// check | "Authorize button!" + +You already have a shiny new "Authorize" button. - And your *path operation* has a little lock in the top-right corner that you can click. +And your *path operation* has a little lock in the top-right corner that you can click. + +/// And if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields): <img src="/img/tutorial/security/image02.png"> -!!! note - It doesn't matter what you type in the form, it won't work yet. But we'll get there. +/// note + +It doesn't matter what you type in the form, it won't work yet. But we'll get there. + +/// This is of course not the frontend for the final users, but it's a great automatic tool to document interactively all your API. @@ -125,53 +142,71 @@ So, let's review it from that simplified point of view: In this example we are going to use **OAuth2**, with the **Password** flow, using a **Bearer** token. We do that using the `OAuth2PasswordBearer` class. -!!! info - A "bearer" token is not the only option. +/// info + +A "bearer" token is not the only option. + +But it's the best one for our use case. - But it's the best one for our use case. +And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs. - And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs. +In that case, **FastAPI** also provides you with the tools to build it. - In that case, **FastAPI** also provides you with the tools to build it. +/// When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="6" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// + +/// tip - ```Python hl_lines="6" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`. -!!! tip - Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`. +Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`. - Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`. +Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. - Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +/// This parameter doesn't create that endpoint / *path operation*, but declares that the URL `/token` will be the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems. We will soon also create the actual path operation. -!!! info - If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`. +/// info + +If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`. + +That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it. - That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it. +/// The `oauth2_scheme` variable is an instance of `OAuth2PasswordBearer`, but it is also a "callable". @@ -187,35 +222,47 @@ So, it can be used with `Depends`. Now you can pass that `oauth2_scheme` in a dependency with `Depends`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*. **FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs). -!!! info "Technical Details" - **FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`. +/// info | "Technical Details" + +**FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`. + +All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI. - All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI. +/// ## What it does diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index dc6d87c9c..6f3bf3944 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -2,26 +2,35 @@ In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// But that is still not that useful. @@ -33,41 +42,57 @@ First, let's create a Pydantic user model. The same way we use Pydantic to declare bodies, we can use it anywhere else: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 13-17" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="5 13-17" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Create a `get_current_user` dependency @@ -79,135 +104,189 @@ Remember that dependencies can have sub-dependencies? The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="26" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="26" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Get the user `get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +```Python hl_lines="20-23 27-28" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20-23 27-28" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Inject the current user So now we can use the same `Depends` with our `get_current_user` in the *path operation*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="32" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="32" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// Notice that we declare the type of `current_user` as the Pydantic model `User`. This will help us inside of the function with all the completion and type checks. -!!! tip - You might remember that request bodies are also declared with Pydantic models. +/// tip - Here **FastAPI** won't get confused because you are using `Depends`. +You might remember that request bodies are also declared with Pydantic models. -!!! check - The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model. +Here **FastAPI** won't get confused because you are using `Depends`. - We are not restricted to having only one dependency that can return that type of data. +/// + +/// check + +The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model. + +We are not restricted to having only one dependency that can return that type of data. + +/// ## Other models @@ -241,41 +320,57 @@ And all of them (or any portion of them that you want) can take the advantage of And all these thousands of *path operations* can be as small as 3 lines: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="31-33" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="31-33" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/security/index.md b/docs/en/docs/tutorial/security/index.md index 659a94dc3..d33a2b14d 100644 --- a/docs/en/docs/tutorial/security/index.md +++ b/docs/en/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ It is not very popular or used nowadays. OAuth2 doesn't specify how to encrypt the communication, it expects you to have your application served with HTTPS. -!!! tip - In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt. +/// tip +In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI defines the following security schemes: * This automatic discovery is what is defined in the OpenID Connect specification. -!!! tip - Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy. +/// tip + +Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy. + +The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you. - The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you. +/// ## **FastAPI** utilities diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index b011db67a..52877b916 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -40,10 +40,13 @@ $ pip install pyjwt </div> -!!! info - If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`. +/// info - You can read more about it in the <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a>. +If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`. + +You can read more about it in the <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a>. + +/// ## Password hashing @@ -79,12 +82,15 @@ $ pip install "passlib[bcrypt]" </div> -!!! tip - With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others. +/// tip + +With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others. - So, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database. +So, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database. - And your users would be able to login from your Django app or from your **FastAPI** app, at the same time. +And your users would be able to login from your Django app or from your **FastAPI** app, at the same time. + +/// ## Hash and verify the passwords @@ -92,12 +98,15 @@ Import the tools we need from `passlib`. Create a PassLib "context". This is what will be used to hash and verify passwords. -!!! tip - The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc. +/// tip + +The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc. - For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt. +For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt. - And be compatible with all of them at the same time. +And be compatible with all of them at the same time. + +/// Create a utility function to hash a password coming from the user. @@ -105,44 +114,63 @@ And another utility to verify if a received password matches the hash stored. And another one to authenticate and return a user. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 50 57-58 61-62 71-77" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="8 50 57-58 61-62 71-77" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// note - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. -!!! note - If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +/// ## Handle JWT tokens @@ -172,41 +200,57 @@ Define a Pydantic Model that will be used in the token endpoint for the response Create a utility function to generate a new access token. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 7 14-16 30-32 80-88" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="4 7 14-16 30-32 80-88" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3 6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ## Update the dependencies @@ -216,41 +260,57 @@ Decode the received token, verify it, and return the current user. If the token is invalid, return an HTTP error right away. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="91-108" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="91-108" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ## Update the `/token` *path operation* @@ -258,41 +318,57 @@ Create a `timedelta` with the expiration time of the token. Create a real JWT access token and return it. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="119-134" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="119-134" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="116-131" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="116-131" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ### Technical details about the JWT "subject" `sub` @@ -331,8 +407,11 @@ Using the credentials: Username: `johndoe` Password: `secret` -!!! check - Notice that nowhere in the code is the plaintext password "`secret`", we only have the hashed version. +/// check + +Notice that nowhere in the code is the plaintext password "`secret`", we only have the hashed version. + +/// <img src="/img/tutorial/security/image08.png"> @@ -353,8 +432,11 @@ If you open the developer tools, you could see how the data sent only includes t <img src="/img/tutorial/security/image10.png"> -!!! note - Notice the header `Authorization`, with a value that starts with `Bearer `. +/// note + +Notice the header `Authorization`, with a value that starts with `Bearer `. + +/// ## Advanced usage with `scopes` diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index 6f40531d7..c9f6a1382 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ They are normally used to declare specific security permissions, for example: * `instagram_basic` is used by Facebook / Instagram. * `https://www.googleapis.com/auth/drive` is used by Google. -!!! info - In OAuth2 a "scope" is just a string that declares a specific permission required. +/// info - It doesn't matter if it has other characters like `:` or if it is a URL. +In OAuth2 a "scope" is just a string that declares a specific permission required. - Those details are implementation specific. +It doesn't matter if it has other characters like `:` or if it is a URL. - For OAuth2 they are just strings. +Those details are implementation specific. + +For OAuth2 they are just strings. + +/// ## Code to get the `username` and `password` @@ -49,41 +52,57 @@ Now let's use the utilities provided by **FastAPI** to handle this. First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 79" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="4 79" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// `OAuth2PasswordRequestForm` is a class dependency that declares a form body with: @@ -92,29 +111,38 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe * An optional `scope` field as a big string, composed of strings separated by spaces. * An optional `grant_type`. -!!! tip - The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it. +/// tip + +The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it. - If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`. +If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`. + +/// * An optional `client_id` (we don't need it for our example). * An optional `client_secret` (we don't need it for our example). -!!! info - The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`. +/// info + +The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI. - `OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI. +But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly. - But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly. +But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier. - But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier. +/// ### Use the form data -!!! tip - The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent. +/// tip + +The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent. + +We are not using `scopes` in this example, but the functionality is there if you need it. - We are not using `scopes` in this example, but the functionality is there if you need it. +/// Now, get the user data from the (fake) database, using the `username` from the form field. @@ -122,41 +150,57 @@ If there is no such user, we return an error saying "Incorrect username or passw For the error, we use the exception `HTTPException`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 80-82" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="3 80-82" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +/// + +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// ### Check the password @@ -182,41 +226,57 @@ If your database is stolen, the thief won't have your users' plaintext passwords So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="83-86" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="83-86" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// #### About `**user_dict` @@ -234,8 +294,11 @@ UserInDB( ) ``` -!!! info - For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. +/// info + +For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// ## Return the token @@ -247,55 +310,77 @@ And it should have an `access_token`, with a string containing our access token. For this simple example, we are going to just be completely insecure and return the same `username` as the token. -!!! tip - In the next chapter, you will see a real secure implementation, with password hashing and <abbr title="JSON Web Tokens">JWT</abbr> tokens. +/// tip + +In the next chapter, you will see a real secure implementation, with password hashing and <abbr title="JSON Web Tokens">JWT</abbr> tokens. + +But for now, let's focus on the specific details we need. - But for now, let's focus on the specific details we need. +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="88" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +```Python hl_lines="88" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` -!!! tip - By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example. +//// - This is something that you have to do yourself in your code, and make sure you use those JSON keys. +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` - It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications. +//// - For the rest, **FastAPI** handles it for you. +/// tip + +By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example. + +This is something that you have to do yourself in your code, and make sure you use those JSON keys. + +It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications. + +For the rest, **FastAPI** handles it for you. + +/// ## Update the dependencies @@ -309,56 +394,75 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="59-67 70-75 95" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="59-67 70-75 95" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="56-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="56-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec. -!!! info - The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec. +Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header. - Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header. +In the case of bearer tokens (our case), the value of that header should be `Bearer`. - In the case of bearer tokens (our case), the value of that header should be `Bearer`. +You can actually skip that extra header and it would still work. - You can actually skip that extra header and it would still work. +But it's provided here to be compliant with the specifications. - But it's provided here to be compliant with the specifications. +Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future. - Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future. +That's the benefit of standards... - That's the benefit of standards... +/// ## See it in action diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 1f0ebc08b..0645cc9f1 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -1,11 +1,14 @@ # SQL (Relational) Databases -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. +These docs are about to be updated. 🎉 - The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. +The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. + +The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. + +/// **FastAPI** doesn't require you to use a SQL (relational) database. @@ -25,13 +28,19 @@ In this example, we'll use **SQLite**, because it uses a single file and Python Later, for your production application, you might want to use a database server like **PostgreSQL**. -!!! tip - There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> +/// tip + +There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> + +/// -!!! note - Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework. +/// note - The **FastAPI** specific code is as small as always. +Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework. + +The **FastAPI** specific code is as small as always. + +/// ## ORMs @@ -65,8 +74,11 @@ Here we will see how to work with **SQLAlchemy ORM**. In a similar way you could use any other ORM. -!!! tip - There's an equivalent article using Peewee here in the docs. +/// tip + +There's an equivalent article using Peewee here in the docs. + +/// ## File structure @@ -131,9 +143,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...and adapt it with your database data and credentials (equivalently for MySQL, MariaDB or any other). -!!! tip +/// tip + +This is the main line that you would have to modify if you wanted to use a different database. - This is the main line that you would have to modify if you wanted to use a different database. +/// ### Create the SQLAlchemy `engine` @@ -155,15 +169,17 @@ connect_args={"check_same_thread": False} ...is needed only for `SQLite`. It's not needed for other databases. -!!! info "Technical Details" +/// info | "Technical Details" + +By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request. - By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request. +This is to prevent accidentally sharing the same connection for different things (for different requests). - This is to prevent accidentally sharing the same connection for different things (for different requests). +But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`. - But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`. +Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism. - Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism. +/// ### Create a `SessionLocal` class @@ -199,10 +215,13 @@ Let's now see the file `sql_app/models.py`. We will use this `Base` class we created before to create the SQLAlchemy models. -!!! tip - SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database. +/// tip - But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. +SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database. + +But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. + +/// Import `Base` from `database` (the file `database.py` from above). @@ -252,12 +271,15 @@ And when accessing the attribute `owner` in an `Item`, it will contain a `User` Now let's check the file `sql_app/schemas.py`. -!!! tip - To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models. +/// tip + +To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models. - These Pydantic models define more or less a "schema" (a valid data shape). +These Pydantic models define more or less a "schema" (a valid data shape). - So this will help us avoiding confusion while using both. +So this will help us avoiding confusion while using both. + +/// ### Create initial Pydantic *models* / schemas @@ -269,23 +291,29 @@ So, the user will also have a `password` when creating it. But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// #### SQLAlchemy style and Pydantic style @@ -313,26 +341,35 @@ The same way, when reading a user, we can now declare that `items` will contain Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13-15 29-32" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`. -!!! tip - Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`. +/// ### Use Pydantic's `orm_mode` @@ -342,32 +379,41 @@ This <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link In the `Config` class, set the attribute `orm_mode = True`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="13 17-18 29 34-35" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | Python 3.8+ -!!! tip - Notice it's assigning a value with `=`, like: +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - `orm_mode = True` +//// - It doesn't use `:` as for the type declarations before. +/// tip - This is setting a config value, not declaring a type. +Notice it's assigning a value with `=`, like: + +`orm_mode = True` + +It doesn't use `:` as for the type declarations before. + +This is setting a config value, not declaring a type. + +/// Pydantic's `orm_mode` will tell the Pydantic *model* to read the data even if it is not a `dict`, but an ORM model (or any other arbitrary object with attributes). @@ -433,8 +479,11 @@ Create utility functions to: {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">unit tests</abbr> for them. +/// tip + +By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">unit tests</abbr> for them. + +/// ### Create data @@ -451,39 +500,51 @@ The steps are: {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +/// info - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. -!!! tip - The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application. +/// - And then pass the `hashed_password` argument with the value to save. +/// tip -!!! warning - This example is not secure, the password is not hashed. +The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. - In a real life application you would need to hash the password and never save them in plaintext. +But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application. - For more details, go back to the Security section in the tutorial. +And then pass the `hashed_password` argument with the value to save. - Here we are focusing only on the tools and mechanics of databases. +/// -!!! tip - Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with: +/// warning - `item.dict()` +This example is not secure, the password is not hashed. - and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with: +In a real life application you would need to hash the password and never save them in plaintext. - `Item(**item.dict())` +For more details, go back to the Security section in the tutorial. - And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with: +Here we are focusing only on the tools and mechanics of databases. - `Item(**item.dict(), owner_id=user_id)` +/// + +/// tip + +Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with: + +`item.dict()` + +and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with: + +`Item(**item.dict())` + +And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with: + +`Item(**item.dict(), owner_id=user_id)` + +/// ## Main **FastAPI** app @@ -493,17 +554,21 @@ And now in the file `sql_app/main.py` let's integrate and use all the other part In a very simplistic way create the database tables: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// #### Alembic Note @@ -527,63 +592,81 @@ For that, we will create a new dependency with `yield`, as explained before in t Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="13-18" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="15-20" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -!!! info - We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. +/// info - And then we close it in the `finally` block. +We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. - This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. +And then we close it in the `finally` block. - But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} +This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. + +But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} + +/// And then, when using the dependency in a *path operation function*, we declare it with the type `Session` we imported directly from SQLAlchemy. This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="22 30 36 45 51" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ -!!! info "Technical Details" - The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided. +```Python hl_lines="24 32 38 47 53" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +/// info | "Technical Details" - But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object. +The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided. + +But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object. + +/// ### Create your **FastAPI** *path operations* Now, finally, here's the standard **FastAPI** *path operations* code. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards. @@ -591,15 +674,21 @@ And then we can create the required dependency in the *path operation function*, With that, we can just call `crud.get_user` directly from inside of the *path operation function* and use that session. -!!! tip - Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models. +/// tip + +Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models. + +But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation. + +/// - But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation. +/// tip -!!! tip - Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`. +Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`. - But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems. +But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems. + +/// ### About `def` vs `async def` @@ -628,11 +717,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. +/// info + +If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. + +/// -!!! note "Very Technical Details" - If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. +/// note | "Very Technical Details" + +If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. + +/// ## Migrations @@ -666,23 +761,29 @@ For example, in a background task worker with <a href="https://docs.celeryq.dev" * `sql_app/schemas.py`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.8+" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// * `sql_app/crud.py`: @@ -692,25 +793,31 @@ For example, in a background task worker with <a href="https://docs.celeryq.dev" * `sql_app/main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// ## Check it You can copy this code and use it as is. -!!! info +/// info + +In fact, the code shown here is part of the tests. As most of the code in these docs. - In fact, the code shown here is part of the tests. As most of the code in these docs. +/// Then you can run it with Uvicorn: @@ -751,24 +858,31 @@ A "middleware" is basically a function that is always executed for each request, The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="12-20" +{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +```Python hl_lines="14-22" +{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. -!!! info - We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. +And then we close it in the `finally` block. - And then we close it in the `finally` block. +This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. - This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. +/// ### About `request.state` @@ -789,10 +903,16 @@ Adding a **middleware** here is similar to what a dependency with `yield` does, * So, a connection will be created for every request. * Even when the *path operation* that handles that request didn't need the DB. -!!! tip - It's probably better to use dependencies with `yield` when they are enough for the use case. +/// tip + +It's probably better to use dependencies with `yield` when they are enough for the use case. + +/// + +/// info + +Dependencies with `yield` were added recently to **FastAPI**. -!!! info - Dependencies with `yield` were added recently to **FastAPI**. +A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management. - A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management. +/// diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 311d2b1c8..b8ce3b551 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ You can serve static files automatically from a directory using `StaticFiles`. {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.staticfiles import StaticFiles`. +/// note | "Technical Details" - **FastAPI** provides the same `starlette.staticfiles` as `fastapi.staticfiles` just as a convenience for you, the developer. But it actually comes directly from Starlette. +You could also use `from starlette.staticfiles import StaticFiles`. + +**FastAPI** provides the same `starlette.staticfiles` as `fastapi.staticfiles` just as a convenience for you, the developer. But it actually comes directly from Starlette. + +/// ### What is "Mounting" diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 8d199a4c7..95c8c5bef 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -8,10 +8,13 @@ With it, you can use <a href="https://docs.pytest.org/" class="external-link" ta ## Using `TestClient` -!!! info - To use `TestClient`, first install <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. +/// info - E.g. `pip install httpx`. +To use `TestClient`, first install <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. + +E.g. `pip install httpx`. + +/// Import `TestClient`. @@ -27,20 +30,29 @@ Write simple `assert` statements with the standard Python expressions that you n {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip - Notice that the testing functions are normal `def`, not `async def`. +/// tip + +Notice that the testing functions are normal `def`, not `async def`. + +And the calls to the client are also normal calls, not using `await`. + +This allows you to use `pytest` directly without complications. + +/// + +/// note | "Technical Details" + +You could also use `from starlette.testclient import TestClient`. - And the calls to the client are also normal calls, not using `await`. +**FastAPI** provides the same `starlette.testclient` as `fastapi.testclient` just as a convenience for you, the developer. But it comes directly from Starlette. - This allows you to use `pytest` directly without complications. +/// -!!! note "Technical Details" - You could also use `from starlette.testclient import TestClient`. +/// tip - **FastAPI** provides the same `starlette.testclient` as `fastapi.testclient` just as a convenience for you, the developer. But it comes directly from Starlette. +If you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} in the advanced tutorial. -!!! tip - If you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} in the advanced tutorial. +/// ## Separating tests @@ -110,41 +122,57 @@ It has a `POST` operation that could return several errors. Both *path operations* require an `X-Token` header. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### Extended testing file @@ -168,10 +196,13 @@ E.g.: For more information about how to pass data to the backend (using `httpx` or the `TestClient`) check the <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX documentation</a>. -!!! info - Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models. +/// info + +Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models. + +If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the `jsonable_encoder` described in [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}. - If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the `jsonable_encoder` described in [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}. +/// ## Run it diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index d204974b8..18c6d3f53 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -5,3 +5,8 @@ plugins: cards_layout_options: logo: ../en/docs/img/icon-white.svg typeset: +markdown_extensions: + material.extensions.preview: + targets: + include: + - ./* diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index c13e36798..782d4ef87 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -6,6 +6,10 @@ theme: name: material custom_dir: ../en/overrides palette: + - media: "(prefers-color-scheme)" + toggle: + icon: material/lightbulb-auto + name: Switch to light mode - media: '(prefers-color-scheme: light)' scheme: default primary: teal @@ -19,18 +23,30 @@ theme: accent: amber toggle: icon: material/lightbulb-outline - name: Switch to light mode + name: Switch to system preference features: - - search.suggest - - search.highlight + - content.code.annotate + - content.code.copy + # - content.code.select + - content.footnote.tooltips - content.tabs.link - - navigation.indexes - content.tooltips + - navigation.footer + - navigation.indexes + - navigation.instant + - navigation.instant.prefetch + - navigation.instant.preview + - navigation.instant.progress - navigation.path - - content.code.annotate - - content.code.copy - - content.code.select - navigation.tabs + - navigation.tabs.sticky + - navigation.top + - navigation.tracking + - search.highlight + - search.share + - search.suggest + - toc.follow + icon: repo: fontawesome/brands/github-alt logo: img/icon-white.svg @@ -38,9 +54,11 @@ theme: language: en repo_name: fastapi/fastapi repo_url: https://github.com/fastapi/fastapi -edit_uri: '' plugins: - search: null + # Material for MkDocs + search: + social: + # Other plugins macros: include_yaml: - external_links: ../en/data/external_links.yml @@ -81,6 +99,7 @@ plugins: signature_crossrefs: true show_symbol_type_heading: true show_symbol_type_toc: true + nav: - FastAPI: - index.md @@ -233,30 +252,72 @@ nav: - benchmarks.md - management.md - release-notes.md + markdown_extensions: + # Python Markdown + abbr: + attr_list: + footnotes: + md_in_html: + tables: toc: permalink: true - markdown.extensions.codehilite: - guess_lang: false - mdx_include: - base_path: docs - admonition: null - codehilite: null - extra: null + + # Python Markdown Extensions + pymdownx.betterem: + smart_enable: all + pymdownx.caret: + pymdownx.highlight: + line_spans: __span + pymdownx.inlinehilite: + pymdownx.keys: + pymdownx.mark: pymdownx.superfences: custom_fences: - name: mermaid class: mermaid - format: !!python/name:pymdownx.superfences.fence_code_format '' - pymdownx.tabbed: - alternate_style: true - pymdownx.tilde: null - attr_list: null - md_in_html: null + format: !!python/name:pymdownx.superfences.fence_code_format + pymdownx.tilde: + + # pymdownx blocks + pymdownx.blocks.admonition: + types: + - note + - attention + - caution + - danger + - error + - tip + - hint + - warning + # Custom types + - info + - check + pymdownx.blocks.details: + pymdownx.blocks.tab: + alternate_style: True + + # Other extensions + mdx_include: + base_path: docs + extra: analytics: provider: google property: G-YNEVN69SC3 + feedback: + title: Was this page helpful? + ratings: + - icon: material/emoticon-happy-outline + name: This page was helpful + data: 1 + note: >- + Thanks for your feedback! + - icon: material/emoticon-sad-outline + name: This page could be improved + data: 0 + note: >- + Thanks for your feedback! social: - icon: fontawesome/brands/github-alt link: https://github.com/fastapi/fastapi @@ -272,6 +333,7 @@ extra: link: https://medium.com/@tiangolo - icon: fontawesome/solid/globe link: https://tiangolo.com + alternate: - link: / name: en - English @@ -321,11 +383,14 @@ extra: name: zh-hant - 繁體中文 - link: /em/ name: 😉 + extra_css: - css/termynal.css - css/custom.css + extra_javascript: - js/termynal.js - js/custom.js + hooks: - ../../scripts/mkdocs_hooks.py diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index eaa3369eb..f40fad03c 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "Advertencia" - Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. +/// warning | "Advertencia" - No será serializado con el modelo, etc. +Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. - Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). +No será serializado con el modelo, etc. -!!! note "Detalles Técnicos" - También podrías utilizar `from starlette.responses import JSONResponse`. +Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). - **FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`. +/// + +/// note | "Detalles Técnicos" + +También podrías utilizar `from starlette.responses import JSONResponse`. + +**FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`. + +/// ## OpenAPI y documentación de API diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md index eb8fe5c1b..88ef8e19f 100644 --- a/docs/es/docs/advanced/index.md +++ b/docs/es/docs/advanced/index.md @@ -6,10 +6,13 @@ El [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_bl En las secciones siguientes verás otras opciones, configuraciones, y características adicionales. -!!! tip - Las próximas secciones **no son necesariamente "avanzadas"**. +/// tip - Y es posible que para tu caso, la solución se encuentre en una de estas. +Las próximas secciones **no son necesariamente "avanzadas"**. + +Y es posible que para tu caso, la solución se encuentre en una de estas. + +/// ## Lee primero el Tutorial diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index e4edcc52b..9e8714fe4 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning "Advertencia" - Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto. +/// warning | "Advertencia" + +Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto. + +/// Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de path* con el parámetro `operation_id`. @@ -23,13 +26,19 @@ Deberías hacerlo después de adicionar todas tus *operaciones de path*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "Consejo" - Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. +/// tip | "Consejo" + +Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. + +/// + +/// warning | "Advertencia" + +Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. -!!! warning "Advertencia" - Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. +Incluso si están en diferentes módulos (archivos Python). - Incluso si están en diferentes módulos (archivos Python). +/// ## Excluir de OpenAPI diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index dee44ac08..7ce5bddca 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizado De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma. -!!! tip "Consejo" - `JSONResponse` en sí misma es una subclase de `Response`. +/// tip | "Consejo" + +`JSONResponse` en sí misma es una subclase de `Response`. + +/// Y cuando devuelves una `Response`, **FastAPI** la pasará directamente. @@ -35,10 +38,13 @@ Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos ante {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Detalles Técnicos" - También puedes usar `from starlette.responses import JSONResponse`. +/// note | "Detalles Técnicos" + +También puedes usar `from starlette.responses import JSONResponse`. + +**FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. - **FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. +/// ## Devolviendo una `Response` personalizada diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md index aec88a584..414b145fc 100644 --- a/docs/es/docs/advanced/response-headers.md +++ b/docs/es/docs/advanced/response-headers.md @@ -29,13 +29,16 @@ Crea un response tal como se describe en [Retornar una respuesta directamente](r {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "Detalles Técnicos" - También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. +/// note | "Detalles Técnicos" - **FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette. +También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. +**FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette. - Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`. + +Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`. + +/// ## Headers Personalizados diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md index 139e8f9bd..7fa8047e9 100644 --- a/docs/es/docs/advanced/security/index.md +++ b/docs/es/docs/advanced/security/index.md @@ -4,10 +4,13 @@ Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - Las siguientes secciones **no necesariamente son "avanzadas"**. +/// tip - Y es posible que para tu caso de uso, la solución esté en alguna de ellas. +Las siguientes secciones **no necesariamente son "avanzadas"**. + +Y es posible que para tu caso de uso, la solución esté en alguna de ellas. + +/// ## Leer primero el Tutorial diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 18159775d..193d24270 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "Nota" - Solo puedes usar `await` dentro de funciones creadas con `async def`. +/// note | "Nota" + +Solo puedes usar `await` dentro de funciones creadas con `async def`. + +/// --- @@ -135,8 +138,11 @@ Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨. <img src="https://fastapi.tiangolo.com/img/async/concurrent-burgers/concurrent-burgers-07.png" alt="illustration"> -!!! info - Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -198,8 +204,11 @@ Sólo las comes y listo 🍔 ⏹. No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞. -!!! info - Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -387,12 +396,15 @@ Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que te ## Detalles muy técnicos -!!! warning "Advertencia" - Probablemente puedas saltarte esto. +/// warning | "Advertencia" + +Probablemente puedas saltarte esto. + +Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel. - Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel. +Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa. - Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa. +/// ### Path operation functions diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md index d8719d6bd..7d09a2739 100644 --- a/docs/es/docs/deployment/versions.md +++ b/docs/es/docs/deployment/versions.md @@ -42,8 +42,11 @@ Siguiendo las convenciones de *Semantic Versioning*, cualquier versión por deba FastAPI también sigue la convención de que cualquier cambio hecho en una <abbr title="versiones de parche">"PATCH" version</abbr> es para solucionar errores y <abbr title="cambios que no rompan funcionalidades o compatibilidad">*non-breaking changes*</abbr>. -!!! tip - El <abbr title="parche">"PATCH"</abbr> es el último número, por ejemplo, en `0.2.3`, la <abbr title="versiones de parche">PATCH version</abbr> es `3`. +/// tip + +El <abbr title="parche">"PATCH"</abbr> es el último número, por ejemplo, en `0.2.3`, la <abbr title="versiones de parche">PATCH version</abbr> es `3`. + +/// Entonces, deberías fijar la versión así: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 En versiones <abbr title="versiones menores">"MINOR"</abbr> son añadidas nuevas características y posibles <abbr title="Cambios que rompen posibles funcionalidades o compatibilidad">breaking changes</abbr>. -!!! tip - La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la <abbr title="versión menor">"MINOR" version</abbr> es `2`. +/// tip + +La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la <abbr title="versión menor">"MINOR" version</abbr> es `2`. + +/// ## Actualizando las versiones de FastAPI diff --git a/docs/es/docs/external-links.md b/docs/es/docs/external-links.md index 481f72e9e..8163349ab 100644 --- a/docs/es/docs/external-links.md +++ b/docs/es/docs/external-links.md @@ -6,8 +6,11 @@ Hay muchas publicaciones, artículos, herramientas y proyectos relacionados con Aquí hay una lista incompleta de algunos de ellos. -!!! tip "Consejo" - Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request agregándolo</a>. +/// tip | "Consejo" + +Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request agregándolo</a>. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index d957b10b7..3c610f8f1 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` significa: +/// info - Pasa las <abbr title="en español key se refiere a la guía de un diccionario">keys</abbr> y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` significa: + +Pasa las <abbr title="en español key se refiere a la guía de un diccionario">keys</abbr> y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Soporte del editor diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md index 1138af76a..d75af7d81 100644 --- a/docs/es/docs/how-to/graphql.md +++ b/docs/es/docs/how-to/graphql.md @@ -4,12 +4,15 @@ Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar c Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. -!!! tip - **GraphQL** resuelve algunos casos de uso específicos. +/// tip - Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes. +**GraphQL** resuelve algunos casos de uso específicos. - Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓 +Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes. + +Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓 + +/// ## Librerías GraphQL @@ -46,8 +49,11 @@ Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** -!!! tip - Si necesitas GraphQL, te recomendaría revisar <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. +/// tip + +Si necesitas GraphQL, te recomendaría revisar <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. + +/// ## Aprende más diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index 89edbb31e..fce434483 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -12,8 +12,11 @@ Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. -!!! note "Nota" - Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. +/// note | "Nota" + +Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. + +/// ## Motivación @@ -253,8 +256,11 @@ Tomado de la documentación oficial de Pydantic: {!../../../docs_src/python_types/tutorial010.py!} ``` -!!! info "Información" - Para aprender más sobre <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic mira su documentación</a>. +/// info | "Información" + +Para aprender más sobre <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic mira su documentación</a>. + +/// **FastAPI** está todo basado en Pydantic. @@ -282,5 +288,8 @@ Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. -!!! info "Información" - Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">la "cheat sheet" de `mypy`</a>. +/// info | "Información" + +Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">la "cheat sheet" de `mypy`</a>. + +/// diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 9f736575d..27ba8ed57 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ Puedes definir parámetros de Cookie de la misma manera que defines parámetros Primero importa `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Declarar parámetros de `Cookie` @@ -48,49 +64,71 @@ Luego declara los parámetros de cookie usando la misma estructura que con `Path El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Detalles Técnicos" -=== "Python 3.8+ non-Annotated" +`Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. - !!! tip - Prefer to use the `Annotated` version if possible. +Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Detalles Técnicos" - `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. +/// info - Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. +Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. -!!! info - Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. +/// ## Resumen diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index c37ce00fb..affdfebff 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note "Nota" - El comando `uvicorn main:app` se refiere a: +/// note | "Nota" - * `main`: el archivo `main.py` (el "módulo" de Python). - * `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. - * `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. +El comando `uvicorn main:app` se refiere a: + +* `main`: el archivo `main.py` (el "módulo" de Python). +* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. +* `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. + +/// En el output, hay una línea que dice más o menos: @@ -136,10 +139,13 @@ También podrías usarlo para generar código automáticamente, para los cliente `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. -!!! note "Detalles Técnicos" - `FastAPI` es una clase que hereda directamente de `Starlette`. +/// note | "Detalles Técnicos" + +`FastAPI` es una clase que hereda directamente de `Starlette`. - También puedes usar toda la funcionalidad de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. +También puedes usar toda la funcionalidad de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>. + +/// ### Paso 2: crea un "instance" de `FastAPI` @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Información" - Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". +/// info | "Información" + +Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". + +/// Cuando construyes una API, el "path" es la manera principal de separar los <abbr title="en inglés: separation of concerns">"intereses"</abbr> y los "recursos". @@ -250,16 +259,19 @@ El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo * el path `/` * usando una <abbr title="an HTTP GET method">operación <code>get</code></abbr> -!!! info "Información sobre `@decorator`" - Esa sintaxis `@algo` se llama un "decorador" en Python. +/// info | "Información sobre `@decorator`" - Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). +Esa sintaxis `@algo` se llama un "decorador" en Python. - Un "decorador" toma la función que tiene debajo y hace algo con ella. +Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). - En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. +Un "decorador" toma la función que tiene debajo y hace algo con ella. - Es el "**decorador de operaciones de path**". +En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. + +Es el "**decorador de operaciones de path**". + +/// También puedes usar las otras operaciones: @@ -274,14 +286,17 @@ y las más exóticas: * `@app.patch()` * `@app.trace()` -!!! tip "Consejo" - Tienes la libertad de usar cada operación (método de HTTP) como quieras. +/// tip | "Consejo" + +Tienes la libertad de usar cada operación (método de HTTP) como quieras. - **FastAPI** no impone ningún significado específico. +**FastAPI** no impone ningún significado específico. - La información que está presentada aquí es una guía, no un requerimiento. +La información que está presentada aquí es una guía, no un requerimiento. - Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. +Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. + +/// ### Paso 4: define la **función de la operación de path** @@ -309,8 +324,11 @@ También podrías definirla como una función estándar en lugar de `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Nota" - Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. +/// note | "Nota" + +Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. + +/// ### Paso 5: devuelve el contenido diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index f11820ef2..46c57c4c3 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -50,22 +50,25 @@ $ pip install "fastapi[all]" ...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código. -!!! note "Nota" - También puedes instalarlo parte por parte. +/// note | "Nota" - Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: +También puedes instalarlo parte por parte. - ``` - pip install fastapi - ``` +Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: - También debes instalar `uvicorn` para que funcione como tu servidor: +``` +pip install fastapi +``` + +También debes instalar `uvicorn` para que funcione como tu servidor: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. - Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. +/// ## Guía Avanzada de Usuario diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 7faa92f51..73bd586f1 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota En este caso, `item_id` es declarado como un `int`. -!!! check "Revisa" - Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. +/// check | "Revisa" + +Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. + +/// ## <abbr title="también conocido en inglés como: serialization, parsing, marshalling">Conversión</abbr> de datos @@ -35,10 +38,13 @@ Si corres este ejemplo y abres tu navegador en <a href="http://127.0.0.1:8000/it {"item_id":3} ``` -!!! check "Revisa" - Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`. +/// check | "Revisa" + +Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`. + +Entonces, con esa declaración de tipos **FastAPI** te da <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> automático del request. - Entonces, con esa declaración de tipos **FastAPI** te da <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> automático del request. +/// ## Validación de datos @@ -63,12 +69,15 @@ debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es El mismo error aparecería si pasaras un `float` en vez de un `int` como en: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! check "Revisa" - Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. +/// check | "Revisa" - Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. +Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. - Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. +Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. + +Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. + +/// ## Documentación @@ -76,10 +85,13 @@ Cuando abras tu navegador en <a href="http://127.0.0.1:8000/docs" class="externa <img src="/img/tutorial/path-params/image01.png"> -!!! check "Revisa" - Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) +/// check | "Revisa" + +Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) + +Observa que el parámetro de path está declarado como un integer. - Observa que el parámetro de path está declarado como un integer. +/// ## Beneficios basados en estándares, documentación alternativa @@ -131,11 +143,17 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Información" - Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4. +/// info | "Información" -!!! tip "Consejo" - Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Técnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning. +Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4. + +/// + +/// tip | "Consejo" + +Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Técnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning. + +/// ### Declara un *parámetro de path* @@ -171,8 +189,11 @@ Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value` {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Consejo" - También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. +/// tip | "Consejo" + +También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. + +/// #### Devuelve *enumeration members* @@ -225,10 +246,13 @@ Entonces lo puedes usar con: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Consejo" - Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). +/// tip | "Consejo" + +Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). + +En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. - En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. +/// ## Repaso diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 76dc331a9..52a3e66a4 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -69,13 +69,19 @@ Del mismo modo puedes declarar parámetros de query opcionales definiendo el val En este caso el parámetro de la función `q` será opcional y será `None` por defecto. -!!! check "Revisa" - También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. +/// check | "Revisa" -!!! note "Nota" - FastAPI sabrá que `q` es opcional por el `= None`. +También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. - El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. +/// + +/// note | "Nota" + +FastAPI sabrá que `q` es opcional por el `= None`. + +El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. + +/// ## Conversión de tipos de parámetros de query @@ -193,5 +199,8 @@ En este caso hay 3 parámetros de query: * `skip`, un `int` con un valor por defecto de `0`. * `limit`, un `int` opcional. -!!! tip "Consejo" - También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. +/// tip | "Consejo" + +También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. + +/// diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md index 58c34b7fc..a5ab1597e 100644 --- a/docs/fa/docs/features.md +++ b/docs/fa/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` یعنی: +/// info - کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` یعنی: + +کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### پشتیبانی ویرایشگر diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md index c5752a4b5..e3ee5fcbc 100644 --- a/docs/fa/docs/tutorial/middleware.md +++ b/docs/fa/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند. * سپس **پاسخ** را برمی گرداند. -!!! توجه "جزئیات فنی" - در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد. +/// توجه | "جزئیات فنی" - در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد. +در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد. + +در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد. + +/// ## ساخت یک میان افزار @@ -31,14 +34,19 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. +/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. + +اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">CORS از Starlette</a> توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. + +/// + +/// توجه | "جزئیات فنی" - اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">CORS از Starlette</a> توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. +شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید. -!!! توجه "جزئیات فنی" - شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید. +**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید. - **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید. +/// ### قبل و بعد از `پاسخ` diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md index 4e68ba961..c0827a8b3 100644 --- a/docs/fa/docs/tutorial/security/index.md +++ b/docs/fa/docs/tutorial/security/index.md @@ -33,8 +33,11 @@ پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود. -!!! نکته - در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. +/// نکته + +در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. + +/// ## استاندارد OpenID Connect @@ -86,10 +89,13 @@ * شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف دادههای احراز هویت OAuth2 به صورت خودکار. * کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص میکند. -!!! نکته - ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است. +/// نکته + +ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است. + +مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد. - مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد. +/// ## ابزارهای **FastAPI** diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md index 685a054ad..44bbf50f8 100644 --- a/docs/fr/docs/advanced/additional-responses.md +++ b/docs/fr/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Réponses supplémentaires dans OpenAPI -!!! warning "Attention" - Ceci concerne un sujet plutôt avancé. +/// warning | "Attention" - Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. +Ceci concerne un sujet plutôt avancé. + +Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. + +/// Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc. @@ -27,20 +30,26 @@ Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un mod {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note "Remarque" - Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. +/// note | "Remarque" + +Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. + +/// + +/// info -!!! info - La clé `model` ne fait pas partie d'OpenAPI. +La clé `model` ne fait pas partie d'OpenAPI. - **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. +**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. - Le bon endroit est : +Le bon endroit est : - * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : - * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : - * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. - * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. +* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : + * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : + * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. + * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. + +/// Les réponses générées au format OpenAPI pour cette *opération de chemin* seront : @@ -172,13 +181,19 @@ Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note "Remarque" - Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. +/// note | "Remarque" + +Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. + +/// + +/// info + +À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). -!!! info - À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). +Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. - Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. +/// ## Combinaison d'informations diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md index 51f0db737..46db2e0b6 100644 --- a/docs/fr/docs/advanced/additional-status-codes.md +++ b/docs/fr/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "Attention" - Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. +/// warning | "Attention" - Elle ne sera pas sérialisée avec un modèle. +Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. - Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). +Elle ne sera pas sérialisée avec un modèle. -!!! note "Détails techniques" - Vous pouvez également utiliser `from starlette.responses import JSONResponse`. +Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). - Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. +/// + +/// note | "Détails techniques" + +Vous pouvez également utiliser `from starlette.responses import JSONResponse`. + +Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. + +/// ## Documents OpenAPI et API diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md index 4599bcb6f..198fa8c30 100644 --- a/docs/fr/docs/advanced/index.md +++ b/docs/fr/docs/advanced/index.md @@ -6,10 +6,13 @@ Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link targ Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires. -!!! note "Remarque" - Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. +/// note | "Remarque" - Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. +Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. + +Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. + +/// ## Lisez d'abord le didacticiel diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index 77f551aea..4727020ae 100644 --- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## ID d'opération OpenAPI -!!! warning "Attention" - Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. +/// warning | "Attention" + +Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. + +/// Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`. @@ -23,13 +26,19 @@ Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "Astuce" - Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. +/// tip | "Astuce" + +Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. + +/// + +/// warning | "Attention" + +Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. -!!! warning "Attention" - Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. +Même s'ils se trouvent dans des modules différents (fichiers Python). - Même s'ils se trouvent dans des modules différents (fichiers Python). +/// ## Exclusion d'OpenAPI @@ -65,8 +74,11 @@ Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI. -!!! note "Détails techniques" - La spécification OpenAPI appelle ces métadonnées des <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Objets d'opération</a>. +/// note | "Détails techniques" + +La spécification OpenAPI appelle ces métadonnées des <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Objets d'opération</a>. + +/// Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation. @@ -74,8 +86,11 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc. Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre. -!!! tip "Astuce" - Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. +/// tip | "Astuce" + +Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`. @@ -162,7 +177,10 @@ Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le {!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` -!!! tip "Astuce" - Ici, nous réutilisons le même modèle Pydantic. +/// tip | "Astuce" + +Ici, nous réutilisons le même modèle Pydantic. + +Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. - Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. +/// diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index ed29446d4..49ca32230 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci. -!!! note "Remarque" - `JSONResponse` est elle-même une sous-classe de `Response`. +/// note | "Remarque" + +`JSONResponse` est elle-même une sous-classe de `Response`. + +/// Et quand vous retournez une `Response`, **FastAPI** la transmet directement. @@ -35,10 +38,13 @@ Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convert {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Détails techniques" - Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. +/// note | "Détails techniques" + +Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. + +**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. - **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. +/// ## Renvoyer une `Response` personnalisée diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md index a64edd671..059a60b69 100644 --- a/docs/fr/docs/alternatives.md +++ b/docs/fr/docs/alternatives.md @@ -37,12 +37,18 @@ Il est utilisé par de nombreuses entreprises, dont Mozilla, Red Hat et Eventbri Il s'agissait de l'un des premiers exemples de **documentation automatique pour API**, et c'est précisément l'une des premières idées qui a inspiré "la recherche de" **FastAPI**. -!!! note +/// note + Django REST framework a été créé par Tom Christie. Le créateur de Starlette et Uvicorn, sur lesquels **FastAPI** est basé. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Avoir une interface de documentation automatique de l'API. +/// + ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django. @@ -59,11 +65,14 @@ qui est nécessaire, était une caractéristique clé que je voulais conserver. Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires. Proposer un système de routage simple et facile à utiliser. +/// + ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> **FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent. @@ -98,9 +107,13 @@ def read_url(): Notez les similitudes entre `requests.get(...)` et `@app.get(...)`. -!!! check "A inspiré **FastAPI** à" -_ Avoir une API simple et intuitive. -_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. +/// check | "A inspiré **FastAPI** à" + +Avoir une API simple et intuitive. + +Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. + +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -115,15 +128,18 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI". -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé. - Intégrer des outils d'interface utilisateur basés sur des normes : +Intégrer des outils d'interface utilisateur basés sur des normes : - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> - Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). +Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). + +/// ### Frameworks REST pour Flask @@ -150,9 +166,12 @@ Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une e Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque <abbr title="la définition de la façon dont les données doivent être formées">schéma</abbr>, 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. +/// + ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> Une autre grande fonctionnalité requise par les API est le <abbr title="la lecture et la conversion en données @@ -164,12 +183,18 @@ Il utilise Marshmallow pour effectuer la validation des données. Et il a été C'est un outil formidable et je l'ai beaucoup utilisé aussi, avant d'avoir **FastAPI**. -!!! info +/// info + 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. +/// + ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins. @@ -188,12 +213,18 @@ Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans u L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète. -!!! info +/// info + APISpec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Supporter la norme ouverte pour les API, OpenAPI. +/// + ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec. @@ -215,12 +246,18 @@ j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent : Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}. -!!! info +/// info + Flask-apispec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation. +/// + ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (et <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular. @@ -236,24 +273,33 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur. - Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. +Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. + +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> 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 <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide. - Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. +Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. + +/// + +/// check | "A inspiré **FastAPI** à" -!!! check "A inspiré **FastAPI** à" Trouvez un moyen d'avoir une performance folle. - C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). +C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -267,12 +313,15 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Trouver des moyens d'obtenir de bonnes performances. - Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. +Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. + +Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. - Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -294,10 +343,13 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses qui sont relativement fortement couplées. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant. - Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). +Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). + +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -314,16 +366,22 @@ API et des CLI. Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant. -!!! info +/// info + Hug a été créé par Timothy Crosley, le créateur de <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, un excellent outil pour trier automatiquement les imports dans les fichiers Python. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar. - Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python - pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. +Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python +pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. + +Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. - Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5) @@ -351,23 +409,29 @@ Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web. -!!! info +/// info + APIStar a été créé par Tom Christie. Le même gars qui a créé : - * Django REST Framework - * Starlette (sur lequel **FastAPI** est basé) - * Uvicorn (utilisé par Starlette et **FastAPI**) +* Django REST Framework +* Starlette (sur lequel **FastAPI** est basé) +* Uvicorn (utilisé par Starlette et **FastAPI**) + +/// + +/// check | "A inspiré **FastAPI** à" -!!! check "A inspiré **FastAPI** à" Exister. - L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. +L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. - Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. +Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. - Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. +Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. - Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. +Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. + +/// ## Utilisés par **FastAPI** @@ -380,10 +444,13 @@ Cela le rend extrêmement intuitif. Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est basé sur les mêmes type hints Python, le support de l'éditeur est grand. -!!! check "**FastAPI** l'utilise pour" +/// check | "**FastAPI** l'utilise pour" + Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON). - **FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. +**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. + +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -413,17 +480,23 @@ Mais il ne fournit pas de validation automatique des données, de sérialisation C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc. -!!! note "Détails techniques" +/// note | "Détails techniques" + ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire. - Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. +Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. + +/// + +/// check | "**FastAPI** l'utilise pour" -!!! check "**FastAPI** l'utilise pour" Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus. - La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. +La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. - Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. +Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -434,12 +507,15 @@ quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-de C'est le serveur recommandé pour Starlette et **FastAPI**. -!!! check "**FastAPI** le recommande comme" +/// check | "**FastAPI** le recommande comme" + Le serveur web principal pour exécuter les applications **FastAPI**. - Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. +Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. + +Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. - Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. +/// ## Benchmarks et vitesse diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index eabd9686a..0f8f34e65 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -20,8 +20,11 @@ async def read_results(): return results ``` -!!! note - Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. +/// note + +Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. + +/// --- @@ -135,8 +138,11 @@ Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨. <img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration"> -!!! info - Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -198,8 +204,11 @@ Vous les mangez, et vous avez terminé 🍔 ⏹. Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞. -!!! info - Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -384,12 +393,15 @@ Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) e ## Détails très techniques -!!! warning "Attention !" - Vous pouvez probablement ignorer cela. +/// warning | "Attention !" + +Vous pouvez probablement ignorer cela. + +Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. - Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. +Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. - Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. +/// ### Fonctions de chemin diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md index ed4d32f5a..408958339 100644 --- a/docs/fr/docs/contributing.md +++ b/docs/fr/docs/contributing.md @@ -24,72 +24,85 @@ Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez Activez le nouvel environnement avec : -=== "Linux, macOS" +//// tab | Linux, macOS - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +<div class="termy"> - </div> +```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +</div> + +//// - Ou si vous utilisez Bash pour Windows (par exemple <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): +//// tab | Windows Bash - <div class="termy"> +Ou si vous utilisez Bash pour Windows (par exemple <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): - ```console - $ source ./env/Scripts/activate - ``` +<div class="termy"> - </div> +```console +$ source ./env/Scripts/activate +``` + +</div> + +//// Pour vérifier que cela a fonctionné, utilisez : -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash + +<div class="termy"> + +```console +$ which pip - <div class="termy"> +some/directory/fastapi/env/bin/pip +``` - ```console - $ which pip +</div> - some/directory/fastapi/env/bin/pip - ``` +//// - </div> +//// tab | Windows PowerShell -=== "Windows PowerShell" +<div class="termy"> - <div class="termy"> +```console +$ Get-Command pip - ```console - $ Get-Command pip +some/directory/fastapi/env/bin/pip +``` - some/directory/fastapi/env/bin/pip - ``` +</div> - </div> +//// Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉 -!!! tip - Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. +/// tip - Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. +Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. + +Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. + +/// ### Flit @@ -111,31 +124,35 @@ Réactivez maintenant l'environnement pour vous assurer que vous utilisez le "fl Et maintenant, utilisez `flit` pour installer les dépendances de développement : -=== "Linux, macOS" +//// tab | Linux, macOS + +<div class="termy"> + +```console +$ flit install --deps develop --symlink - <div class="termy"> +---> 100% +``` - ```console - $ flit install --deps develop --symlink +</div> - ---> 100% - ``` +//// - </div> +//// tab | Windows -=== "Windows" +Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : - Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : +<div class="termy"> - <div class="termy"> +```console +$ flit install --deps develop --pth-file - ```console - $ flit install --deps develop --pth-file +---> 100% +``` - ---> 100% - ``` +</div> - </div> +//// Il installera toutes les dépendances et votre FastAPI local dans votre environnement local. @@ -185,8 +202,11 @@ La documentation utilise <a href="https://www.mkdocs.org/" class="external-link" 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. +/// 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/`. @@ -271,10 +291,13 @@ Voici les étapes à suivre pour aider à la traduction. * Vérifiez les <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">pull requests existantes</a> pour votre langue et ajouter des reviews demandant des changements ou les approuvant. -!!! tip - Vous pouvez <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">ajouter des commentaires avec des suggestions de changement</a> aux pull requests existantes. +/// tip + +Vous pouvez <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">ajouter des commentaires avec des suggestions de changement</a> aux pull requests existantes. + +Consultez les documents concernant <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">l'ajout d'un review de pull request</a> pour l'approuver ou demander des modifications. - Consultez les documents concernant <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">l'ajout d'un review de pull request</a> pour l'approuver ou demander des modifications. +/// * Vérifiez dans <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">issues</a> pour voir s'il y a une personne qui coordonne les traductions pour votre langue. @@ -296,8 +319,11 @@ Disons que vous voulez traduire une page pour une langue qui a déjà des traduc Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`. -!!! tip - La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". +/// tip + +La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". + +/// Maintenant, lancez le serveur en live pour les documents en espagnol : @@ -334,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. +/// tip + +Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. + +/// * Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à @@ -406,10 +435,13 @@ Updating en Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`. -!!! tip - Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. +/// tip + +Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. + +Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 - Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 +/// Commencez par traduire la page principale, `docs/ht/index.md`. diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md index d2dcae722..0f3b64700 100644 --- a/docs/fr/docs/deployment/docker.md +++ b/docs/fr/docs/deployment/docker.md @@ -17,8 +17,11 @@ Cette image est dotée d'un mécanisme d'"auto-tuning", de sorte qu'il vous suff Mais vous pouvez toujours changer et mettre à jour toutes les configurations avec des variables d'environnement ou des fichiers de configuration. -!!! tip "Astuce" - Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +/// tip | "Astuce" + +Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +/// ## Créer un `Dockerfile` diff --git a/docs/fr/docs/deployment/https.md b/docs/fr/docs/deployment/https.md index ccf1f847a..3f7068ff0 100644 --- a/docs/fr/docs/deployment/https.md +++ b/docs/fr/docs/deployment/https.md @@ -4,8 +4,11 @@ Il est facile de penser que HTTPS peut simplement être "activé" ou non. Mais c'est beaucoup plus complexe que cela. -!!! tip - Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. +/// tip + +Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. + +/// Pour apprendre les bases du HTTPS, du point de vue d'un utilisateur, consultez <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>. diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index eb1253cf8..6a737fdef 100644 --- a/docs/fr/docs/deployment/manually.md +++ b/docs/fr/docs/deployment/manually.md @@ -25,75 +25,89 @@ Lorsqu'on se réfère à la machine distante, il est courant de l'appeler **serv Vous pouvez installer un serveur compatible ASGI avec : -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. - <div class="termy"> +<div class="termy"> + +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +</div> - ---> 100% - ``` +/// tip | "Astuce" - </div> +En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. - !!! tip "Astuce" - En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. +Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. - Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. +/// -=== "Hypercorn" +//// - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2. +//// tab | Hypercorn - <div class="termy"> +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2. - ```console - $ pip install hypercorn +<div class="termy"> + +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +</div> - </div> +...ou tout autre serveur ASGI. - ...ou tout autre serveur ASGI. +//// ## Exécutez le programme serveur Vous pouvez ensuite exécuter votre application de la même manière que vous l'avez fait dans les tutoriels, mais sans l'option `--reload`, par exemple : -=== "Uvicorn" +//// tab | Uvicorn - <div class="termy"> +<div class="termy"> - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - </div> +</div> + +//// -=== "Hypercorn" +//// tab | Hypercorn - <div class="termy"> +<div class="termy"> + +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +</div> - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning - </div> +N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. -!!! warning - N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. + L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. - L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. + Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. - Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. +/// ## Hypercorn avec Trio diff --git a/docs/fr/docs/deployment/versions.md b/docs/fr/docs/deployment/versions.md index 136165e9d..8ea79a172 100644 --- a/docs/fr/docs/deployment/versions.md +++ b/docs/fr/docs/deployment/versions.md @@ -48,8 +48,11 @@ des changements non rétrocompatibles. FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et des changements rétrocompatibles. -!!! tip "Astuce" - Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. +/// tip | "Astuce" + +Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. + +/// Donc, vous devriez être capable d'épingler une version comme suit : @@ -59,8 +62,11 @@ fastapi>=0.45.0,<0.46.0 Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR". -!!! tip "Astuce" - Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. +/// tip | "Astuce" + +Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. + +/// ## Mise à jour des versions FastAPI diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md index 2f928f523..91a9eae58 100644 --- a/docs/fr/docs/external-links.md +++ b/docs/fr/docs/external-links.md @@ -6,8 +6,11 @@ Il existe de nombreux articles, outils et projets liés à **FastAPI**. Voici une liste incomplète de certains d'entre eux. -!!! tip "Astuce" - Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>. +/// tip | "Astuce" + +Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index 1457df2a5..afb1de243 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` signifie: +/// info - Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` signifie: + +Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Support d'éditeurs diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index 4232633e3..e3c99e0a9 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -13,8 +13,11 @@ Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières. -!!! note - Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. +/// note + +Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. + +/// ## Motivations @@ -174,10 +177,13 @@ Les listes étant un type contenant des types internes, mettez ces derniers entr {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Astuce" - Ces types internes entre crochets sont appelés des "paramètres de type". +/// tip | "Astuce" + +Ces types internes entre crochets sont appelés des "paramètres de type". + +Ici, `str` est un paramètre de type passé à `List`. - Ici, `str` est un paramètre de type passé à `List`. +/// Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`. @@ -281,8 +287,11 @@ Extrait de la documentation officielle de **Pydantic** : {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Pour en savoir plus à propos de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, allez jeter un coup d'oeil à sa documentation</a>. +/// info + +Pour en savoir plus à propos de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, allez jeter un coup d'oeil à sa documentation</a>. + +/// **FastAPI** est basé entièrement sur **Pydantic**. @@ -310,5 +319,8 @@ Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous. -!!! info - Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" de `mypy`</a>. +/// info + +Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" de `mypy`</a>. + +/// diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md index 563b601f0..fd8e5d688 100644 --- a/docs/fr/docs/tutorial/body-multiple-params.md +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip -!!! note - Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note + +Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). + +/// ## Paramètres multiples du body @@ -62,17 +81,21 @@ Dans l'exemple précédent, les opérations de routage attendaient un body JSON Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). @@ -93,8 +116,11 @@ Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevo } ``` -!!! note - "Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. +/// note + +"Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. + +/// **FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis. @@ -109,41 +135,57 @@ Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +//// Dans ce cas, **FastAPI** s'attendra à un body semblable à : @@ -183,44 +225,63 @@ q: str | None = None Par exemple : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// tip - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +//// -!!! info - `Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. +/// info + +`Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. + +/// ## Inclure un paramètre imbriqué dans le body @@ -236,41 +297,57 @@ item: Item = Body(embed=True) Voici un exemple complet : -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// tip - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// Dans ce cas **FastAPI** attendra un body semblable à : diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index ae952405c..9a5121f10 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -8,12 +8,15 @@ Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un cli Pour déclarer un corps de **requête**, on utilise les modèles de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> en profitant de tous leurs avantages et fonctionnalités. -!!! info - Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. +/// info - Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. +Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. - Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. +Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. + +Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. + +/// ## Importez le `BaseModel` de Pydantic @@ -110,16 +113,19 @@ Mais vous auriez le même support de l'éditeur avec <a href="https://www.jetbra <img src="/img/tutorial/body/image05.png"> -!!! tip "Astuce" - Si vous utilisez <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> comme éditeur, vous pouvez utiliser le Plugin <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. +/// tip | "Astuce" + +Si vous utilisez <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> comme éditeur, vous pouvez utiliser le Plugin <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. - Ce qui améliore le support pour les modèles Pydantic avec : +Ce qui améliore le support pour les modèles Pydantic avec : - * de l'auto-complétion - * des vérifications de type - * du "refactoring" (ou remaniement de code) - * de la recherche - * de l'inspection +* de l'auto-complétion +* des vérifications de type +* du "refactoring" (ou remaniement de code) +* de la recherche +* de l'inspection + +/// ## Utilisez le modèle @@ -155,10 +161,13 @@ Les paramètres de la fonction seront reconnus comme tel : * Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**. * Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. +/// note + +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. + +Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. - Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. +/// ## Sans Pydantic diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md index e58872d30..bcd780a82 100644 --- a/docs/fr/docs/tutorial/debugging.md +++ b/docs/fr/docs/tutorial/debugging.md @@ -74,9 +74,12 @@ Ainsi, la ligne : ne sera pas exécutée. -!!! info +/// info + Pour plus d'informations, consultez <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">la documentation officielle de Python</a>. +/// + ## Exécutez votre code avec votre <abbr title="En anglais: debugger">débogueur</abbr> Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le <abbr title="En anglais: debugger">débogueur</abbr>. diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index e98283f1e..bf476d990 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note - La commande `uvicorn main:app` fait référence à : +/// note - * `main` : le fichier `main.py` (le module Python). - * `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. - * `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! +La commande `uvicorn main:app` fait référence à : + +* `main` : le fichier `main.py` (le module Python). +* `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. +* `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! + +/// Vous devriez voir dans la console, une ligne semblable à la suivante : @@ -137,10 +140,13 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. -!!! note "Détails techniques" - `FastAPI` est une classe héritant directement de `Starlette`. +/// note | "Détails techniques" + +`FastAPI` est une classe héritant directement de `Starlette`. - Vous pouvez donc aussi utiliser toutes les fonctionnalités de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> depuis `FastAPI`. +Vous pouvez donc aussi utiliser toutes les fonctionnalités de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> depuis `FastAPI`. + +/// ### Étape 2 : créer une "instance" `FastAPI` @@ -200,9 +206,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". +/// info + +Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". +/// #### Opération @@ -251,16 +259,19 @@ Le `@app.get("/")` dit à **FastAPI** que la fonction en dessous est chargée de * le chemin `/` * en utilisant une <abbr title="une méthode GET HTTP">opération <code>get</code></abbr> -!!! info "`@décorateur` Info" - Cette syntaxe `@something` en Python est appelée un "décorateur". +/// info | "`@décorateur` Info" + +Cette syntaxe `@something` en Python est appelée un "décorateur". - Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂). +Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂). - Un "décorateur" prend la fonction en dessous et en fait quelque chose. +Un "décorateur" prend la fonction en dessous et en fait quelque chose. - Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. +Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. - C'est le "**décorateur d'opération de chemin**". +C'est le "**décorateur d'opération de chemin**". + +/// Vous pouvez aussi utiliser les autres opérations : @@ -275,14 +286,17 @@ Tout comme celles les plus exotiques : * `@app.patch()` * `@app.trace()` -!!! tip "Astuce" - Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. +/// tip | "Astuce" + +Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. + +**FastAPI** n'impose pas de sens spécifique à chacune d'elle. - **FastAPI** n'impose pas de sens spécifique à chacune d'elle. +Les informations qui sont présentées ici forment une directive générale, pas des obligations. - Les informations qui sont présentées ici forment une directive générale, pas des obligations. +Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. - Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. +/// ### Étape 4 : définir la **fonction de chemin**. @@ -310,8 +324,11 @@ Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `as {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. +/// note + +Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. + +/// ### Étape 5 : retourner le contenu diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md index 4dc202b33..83cc5f9e8 100644 --- a/docs/fr/docs/tutorial/index.md +++ b/docs/fr/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install fastapi[all] ... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code. -!!! note - Vous pouvez également l'installer pièce par pièce. +/// note - C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : +Vous pouvez également l'installer pièce par pièce. - ``` - pip install fastapi - ``` +C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : - Installez également `uvicorn` pour qu'il fonctionne comme serveur : +``` +pip install fastapi +``` + +Installez également `uvicorn` pour qu'il fonctionne comme serveur : + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. - Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. +/// ## Guide utilisateur avancé diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md index e8dcd37fb..eedd59f91 100644 --- a/docs/fr/docs/tutorial/path-params-numeric-validations.md +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ De la même façon que vous pouvez déclarer plus de validations et de métadonn Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+" +/// - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Préférez utiliser la version `Annotated` si possible. +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// info - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0. -!!! info - FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0. +Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`. - Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`. +Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`. - Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`. +/// ## Déclarer des métadonnées @@ -55,49 +74,71 @@ Vous pouvez déclarer les mêmes paramètres que pour `Query`. Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Préférez utiliser la version `Annotated` si possible. +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -!!! note - Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis. +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note + +Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis. + +/// ## Ordonnez les paramètres comme vous le souhaitez -!!! tip - Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis. @@ -113,33 +154,45 @@ Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par le Ainsi, vous pouvez déclarer votre fonction comme suit : -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +//// ## Ordonnez les paramètres comme vous le souhaitez (astuces) -!!! tip - Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin. @@ -164,17 +217,21 @@ Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Validations numériques : supérieur ou égal @@ -182,26 +239,35 @@ Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez décl Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Validations numériques : supérieur ou égal et inférieur ou égal @@ -210,26 +276,35 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +//// ## Validations numériques : supérieur et inférieur ou égal @@ -238,26 +313,35 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Préférez utiliser la version `Annotated` si possible. +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +/// + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Validations numériques : flottants, supérieur et inférieur @@ -269,26 +353,35 @@ Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas. Et la même chose pour <abbr title="less than"><code>lt</code></abbr>. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Pour résumer @@ -301,18 +394,24 @@ Et vous pouvez également déclarer des validations numériques : * `lt` : `l`ess `t`han * `le` : `l`ess than or `e`qual -!!! info - `Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`. +/// info + +`Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`. + +Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment. + +/// + +/// note | "Détails techniques" - Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment. +Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. -!!! note "Détails techniques" - Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. +Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom. - Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom. +Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`. - Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`. +Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types. - Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types. +De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs. - De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs. +/// diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 523e2c8c2..94c36a20d 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -28,9 +28,12 @@ Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en uti Ici, `item_id` est déclaré comme `int`. -!!! check "vérifier" - Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles - que des vérifications d'erreur, de l'auto-complétion, etc. +/// check | "vérifier" + +Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles +que des vérifications d'erreur, de l'auto-complétion, etc. + +/// ## <abbr title="aussi appelé sérialisation, ou parfois parsing ou marshalling en anglais">Conversion</abbr> de données @@ -40,12 +43,15 @@ Si vous exécutez cet exemple et allez sur <a href="http://127.0.0.1:8000/items/ {"item_id":3} ``` -!!! check "vérifier" - Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`, - en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`. +/// check | "vérifier" + +Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`, +en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`. + +Grâce aux déclarations de types, **FastAPI** fournit du +<abbr title="conversion de la chaîne de caractères venant de la requête HTTP en données Python">"parsing"</abbr> automatique. - Grâce aux déclarations de types, **FastAPI** fournit du - <abbr title="conversion de la chaîne de caractères venant de la requête HTTP en données Python">"parsing"</abbr> automatique. +/// ## Validation de données @@ -72,12 +78,15 @@ La même erreur se produira si vous passez un nombre flottant (`float`) et non u <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>. -!!! check "vérifier" - Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. +/// check | "vérifier" - Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. +Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. - Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. +Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. + +Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. + +/// ## Documentation @@ -86,10 +95,13 @@ documentation générée automatiquement et interactive : <img src="/img/tutorial/path-params/image01.png"> -!!! info - À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). +/// info + +À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). + +On voit bien dans la documentation que `item_id` est déclaré comme entier. - On voit bien dans la documentation que `item_id` est déclaré comme entier. +/// ## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative. @@ -141,11 +153,17 @@ Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les va {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Les énumérations (ou enums) sont disponibles en Python</a> depuis la version 3.4. +/// info -!!! tip "Astuce" - Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de <abbr title="Techniquement, des architectures de modèles">modèles</abbr> de Machine Learning. +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Les énumérations (ou enums) sont disponibles en Python</a> depuis la version 3.4. + +/// + +/// tip | "Astuce" + +Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de <abbr title="Techniquement, des architectures de modèles">modèles</abbr> de Machine Learning. + +/// ### Déclarer un paramètre de chemin @@ -181,8 +199,11 @@ Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici) {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Astuce" - Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. +/// tip | "Astuce" + +Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. + +/// #### Retourner des *membres d'énumération* @@ -235,10 +256,13 @@ Vous pouvez donc l'utilisez comme tel : {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Astuce" - Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). +/// tip | "Astuce" + +Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). + +Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. - Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. +/// ## Récapitulatif diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index f5248fe8b..63578ec40 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,13 @@ Commençons avec cette application pour exemple : Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. +/// note - Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. + +Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. + +/// ## Validation additionnelle @@ -51,22 +54,25 @@ q: Union[str, None] = None Mais déclare explicitement `q` comme étant un paramètre de requête. -!!! info - Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : +/// info - ```Python - = None - ``` +Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : - ou : +```Python += None +``` - ```Python - = Query(None) - ``` +ou : - et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. +```Python += Query(None) +``` + +et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. - Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. +Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. + +/// Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères : @@ -112,8 +118,11 @@ Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "Rappel" - Avoir une valeur par défaut rend le paramètre optionnel. +/// note | "Rappel" + +Avoir une valeur par défaut rend le paramètre optionnel. + +/// ## Rendre ce paramètre requis @@ -141,8 +150,11 @@ Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info - Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python <a href="https://docs.python.org/fr/3/library/constants.html#Ellipsis" class="external-link" target="_blank">appelée "Ellipsis"</a>. +/// info + +Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python <a href="https://docs.python.org/fr/3/library/constants.html#Ellipsis" class="external-link" target="_blank">appelée "Ellipsis"</a>. + +/// Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire. @@ -175,8 +187,11 @@ Donc la réponse de cette URL serait : } ``` -!!! tip "Astuce" - Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. +/// tip | "Astuce" + +Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. + +/// La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs : @@ -217,10 +232,13 @@ Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. +/// note - Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. +Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. + +Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. + +/// ## Déclarer des métadonnées supplémentaires @@ -228,10 +246,13 @@ On peut aussi ajouter plus d'informations sur le paramètre. Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés. -!!! note - Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. +/// note + +Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. + +Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. - Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. +/// Vous pouvez ajouter un `title` : diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index 962135f63..b9f1540c9 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -69,14 +69,19 @@ De la même façon, vous pouvez définir des paramètres de requête comme optio Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. -!!! check "Remarque" - On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. +/// check | "Remarque" -!!! note - **FastAPI** saura que `q` est optionnel grâce au `=None`. +On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. - Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. +/// +/// note + +**FastAPI** saura que `q` est optionnel grâce au `=None`. + +Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. + +/// ## Conversion des types des paramètres de requête @@ -194,5 +199,8 @@ Ici, on a donc 3 paramètres de requête : * `skip`, un `int` avec comme valeur par défaut `0`. * `limit`, un `int` optionnel. -!!! tip "Astuce" - Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. +/// tip | "Astuce" + +Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. + +/// diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index b7231ad56..e605bbb55 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -376,7 +376,7 @@ Visszatérve az előző kód példához. A **FastAPI**: * Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben. * Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben. * Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban. -* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. +* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. * Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális. * `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén). * a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be: diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md index 6b6de24f0..f0dee3d73 100644 --- a/docs/id/docs/tutorial/index.md +++ b/docs/id/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu. -!!! note "Catatan" - Kamu juga dapat meng-installnya bagian demi bagian. +/// note | "Catatan" - Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: +Kamu juga dapat meng-installnya bagian demi bagian. - ``` - pip install fastapi - ``` +Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: - Juga install `uvicorn` untuk menjalankan server" +``` +pip install fastapi +``` + +Juga install `uvicorn` untuk menjalankan server" + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. - Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. +/// ## Pedoman Pengguna Lanjutan diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 38f611734..272f9a37e 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -1,4 +1,3 @@ - {!../../../docs/missing-translation.md!} diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index d1f8e6451..622affa6e 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "注意" - 上記の例のように `Response` を明示的に返す場合、それは直接返されます。 +/// warning | "注意" - モデルなどはシリアライズされません。 +上記の例のように `Response` を明示的に返す場合、それは直接返されます。 - 必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 +モデルなどはシリアライズされません。 -!!! note "技術詳細" - `from starlette.responses import JSONResponse` を利用することもできます。 +必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 - **FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 +/// + +/// note | "技術詳細" + +`from starlette.responses import JSONResponse` を利用することもできます。 + +**FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 + +/// ## OpenAPIとAPIドキュメント diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index d8b47629a..a7ce6b54d 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。 -!!! note "備考" - メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 +/// note | "備考" + +メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 + +/// ## `ORJSONResponse` を使う @@ -25,15 +28,21 @@ {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 +/// info | "情報" + +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 + +この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 + +そして、OpenAPIにはそのようにドキュメントされます。 + +/// - この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 +/// tip | "豆知識" - そして、OpenAPIにはそのようにドキュメントされます。 +`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 -!!! tip "豆知識" - `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 +/// ## HTMLレスポンス @@ -46,12 +55,15 @@ {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 +/// info | "情報" - この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 - そして、OpenAPIにはそのようにドキュメント化されます。 +この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 + +そして、OpenAPIにはそのようにドキュメント化されます。 + +/// ### `Response` を返す @@ -63,11 +75,17 @@ {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "注意" - *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 +/// warning | "注意" + +*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 + +/// + +/// info | "情報" -!!! info "情報" - もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 +もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 + +/// ### OpenAPIドキュメントと `Response` のオーバーライド @@ -97,10 +115,13 @@ `Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。 -!!! note "技術詳細" - `from starlette.responses import HTMLResponse` も利用できます。 +/// note | "技術詳細" + +`from starlette.responses import HTMLResponse` も利用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ### `Response` @@ -147,15 +168,21 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>を使った、代替のJSONレスポンスです。 -!!! warning "注意" - `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 +/// warning | "注意" + +`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "豆知識" - `ORJSONResponse` のほうが高速な代替かもしれません。 +/// tip | "豆知識" + +`ORJSONResponse` のほうが高速な代替かもしれません。 + +/// ### `RedirectResponse` @@ -183,8 +210,11 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス {!../../../docs_src/custom_response/tutorial008.py!} ``` -!!! tip "豆知識" - ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 +/// tip | "豆知識" + +ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 + +/// ### `FileResponse` @@ -215,8 +245,11 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip "豆知識" - 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 +/// tip | "豆知識" + +前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 + +/// ## その他のドキュメント diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md index 2d60e7489..da3c2a2bf 100644 --- a/docs/ja/docs/advanced/index.md +++ b/docs/ja/docs/advanced/index.md @@ -6,10 +6,13 @@ 以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。 -!!! tip "豆知識" - 以降のセクションは、 **必ずしも"応用編"ではありません**。 +/// tip | "豆知識" - ユースケースによっては、その中から解決策を見つけられるかもしれません。 +以降のセクションは、 **必ずしも"応用編"ではありません**。 + +ユースケースによっては、その中から解決策を見つけられるかもしれません。 + +/// ## 先にチュートリアルを読む diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index 35b381cae..ae60126cb 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning "注意" - あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 +/// warning | "注意" + +あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 + +/// *path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。 @@ -23,13 +26,19 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "豆知識" - `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 +/// tip | "豆知識" + +`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 + +/// + +/// warning | "注意" + +この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 -!!! warning "注意" - この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 +それらが異なるモジュール (Pythonファイル) にあるとしてもです。 - それらが異なるモジュール (Pythonファイル) にあるとしてもです。 +/// ## OpenAPIから除外する diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index 10ec88548..5c25471b1 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 実際は、`Response` やそのサブクラスを返すことができます。 -!!! tip "豆知識" - `JSONResponse` それ自体は、 `Response` のサブクラスです。 +/// tip | "豆知識" + +`JSONResponse` それ自体は、 `Response` のサブクラスです。 + +/// `Response` を返した場合は、**FastAPI** は直接それを返します。 @@ -35,10 +38,13 @@ {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "技術詳細" - また、`from starlette.responses import JSONResponse` も利用できます。 +/// note | "技術詳細" + +また、`from starlette.responses import JSONResponse` も利用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ## カスタム `Response` を返す diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index 65e4112a6..615f9d17c 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -50,10 +50,13 @@ $ pip install websockets {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "技術詳細" - `from starlette.websockets import WebSocket` を使用しても構いません. +/// note | "技術詳細" - **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 +`from starlette.websockets import WebSocket` を使用しても構いません. + +**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 + +/// ## メッセージの送受信 @@ -116,12 +119,15 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート {!../../../docs_src/websockets/tutorial002.py!} ``` -!!! info "情報" - WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 +/// info | "情報" + +WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 + +クロージングコードは、<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">仕様で定義された有効なコード</a>の中から使用することができます。 - クロージングコードは、<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">仕様で定義された有効なコード</a>の中から使用することができます。 +将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の <a href="https://github.com/encode/starlette/pull/527" class="external-link" target="_blank">PR #527</a> に依存するものです。 - 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の <a href="https://github.com/encode/starlette/pull/527" class="external-link" target="_blank">PR #527</a> に依存するものです。 +/// ### 依存関係を用いてWebSocketsを試してみる @@ -144,8 +150,11 @@ $ uvicorn main:app --reload * パスで使用される「Item ID」 * クエリパラメータとして使用される「Token」 -!!! tip "豆知識" - クエリ `token` は依存パッケージによって処理されることに注意してください。 +/// tip | "豆知識" + +クエリ `token` は依存パッケージによって処理されることに注意してください。 + +/// これにより、WebSocketに接続してメッセージを送受信できます。 @@ -171,12 +180,15 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例 Client #1596980209979 left the chat ``` -!!! tip "豆知識" - 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 +/// tip | "豆知識" + +上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 + +しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 - しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 +もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、<a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> を確認してください。 - もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、<a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> を確認してください。 +/// ## その他のドキュメント diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index ce4b36408..343ae4ed8 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -30,11 +30,17 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。 -!!! note "備考" - Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 +/// note | "備考" -!!! check "**FastAPI**へ与えたインスピレーション" - 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 +Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 + +/// ### <a href="http://flask.pocoo.org/" class="external-link" target="_blank">Flask</a> @@ -50,11 +56,13 @@ Flask は「マイクロフレームワーク」であり、データベース Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。 -!!! check "**FastAPI**へ与えたインスピレーション" - マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 - シンプルで簡単なルーティングの仕組みを持っている点。 +シンプルで簡単なルーティングの仕組みを持っている点。 +/// ### <a href="http://docs.python-requests.org" class="external-link" target="_blank">Requests</a> @@ -90,11 +98,13 @@ def read_url(): `requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 -!!! check "**FastAPI**へ与えたインスピレーション" - * シンプルで直感的なAPIを持っている点。 - * HTTPメソッド名を直接利用し、単純で直感的である。 - * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// check | "**FastAPI**へ与えたインスピレーション" + +* シンプルで直感的なAPIを持っている点。 +* HTTPメソッド名を直接利用し、単純で直感的である。 +* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -108,15 +118,18 @@ def read_url(): そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 +/// check | "**FastAPI**へ与えたインスピレーション" - そして、標準に基づくユーザーインターフェースツールを統合しています。 +独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> +そして、標準に基づくユーザーインターフェースツールを統合しています。 - この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> + +この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 + +/// ### Flask REST フレームワーク @@ -134,8 +147,11 @@ APIが必要とするもう一つの大きな機能はデータのバリデー しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべての<abbr title="データがどのように形成されるべきかの定義">スキーマ</abbr>を定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。 -!!! check "**FastAPI**へ与えたインスピレーション" - コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -147,11 +163,17 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上 素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。 -!!! info "情報" - Webargsは、Marshmallowと同じ開発者により作られました。 +/// info | "情報" + +Webargsは、Marshmallowと同じ開発者により作られました。 + +/// -!!! check "**FastAPI**へ与えたインスピレーション" - 受信したデータに対する自動的なバリデーションを持っている点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +受信したデータに対する自動的なバリデーションを持っている点。 + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。 -!!! info "情報" - APISpecは、Marshmallowと同じ開発者により作成されました。 +/// info | "情報" + +APISpecは、Marshmallowと同じ開発者により作成されました。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +OpenAPIという、APIについてのオープンな標準をサポートしている点。 -!!! check "**FastAPI**へ与えたインスピレーション" - OpenAPIという、APIについてのオープンな標準をサポートしている点。 +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -197,11 +225,17 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI** そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。 -!!! info "情報" - Flask-apispecはMarshmallowと同じ開発者により作成されました。 +/// info | "情報" -!!! check "**FastAPI**へ与えたインスピレーション" - シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 +Flask-apispecはMarshmallowと同じ開発者により作成されました。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (と<a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) @@ -217,24 +251,33 @@ Angular 2にインスピレーションを受けた、統合された依存性 入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 + +強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 - 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> `asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。 -!!! note "技術詳細" - Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 +/// note | "技術詳細" - `Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 +Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 物凄い性能を出す方法を見つけた点。 +`Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 - **FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +物凄い性能を出す方法を見つけた点。 + +**FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -246,12 +289,15 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしい性能を得るための方法を見つけた点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +素晴らしい性能を得るための方法を見つけた点。 + +Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 - Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 +**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 - **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -269,10 +315,13 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。 -!!! check "**FastAPI**へ与えたインスピレーション" - モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 +/// check | "**FastAPI**へ与えたインスピレーション" - 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) +モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 + +同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) + +/// ### <a href="http://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -288,15 +337,21 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。 -!!! info "情報" - HugはTimothy Crosleyにより作成されました。彼は<a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 +/// info | "情報" + +HugはTimothy Crosleyにより作成されました。彼は<a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 -!!! check "**FastAPI**へ与えたインスピレーション" - HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 +Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 - Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 +Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 - Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5) @@ -322,23 +377,29 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。 -!!! info "情報" - APIStarはTom Christieにより開発されました。以下の開発者でもあります: +/// info | "情報" - * Django REST Framework - * Starlette (**FastAPI**のベースになっています) - * Uvicorn (Starletteや**FastAPI**で利用されています) +APIStarはTom Christieにより開発されました。以下の開発者でもあります: -!!! check "**FastAPI**へ与えたインスピレーション" - 存在そのもの。 +* Django REST Framework +* Starlette (**FastAPI**のベースになっています) +* Uvicorn (Starletteや**FastAPI**で利用されています) - 複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 +/// - そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 +/// check | "**FastAPI**へ与えたインスピレーション" - その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 +存在そのもの。 - 私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 +複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 + +そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 + +その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 + +私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 + +/// ## **FastAPI**が利用しているもの @@ -350,10 +411,13 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、 Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。 -!!! check "**FastAPI**での使用用途" - データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 +/// check | "**FastAPI**での使用用途" + +データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 + +**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 - **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -383,17 +447,23 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。 -!!! note "技術詳細" - ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 +/// note | "技術詳細" - しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 +ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 -!!! check "**FastAPI**での使用用途" - webに関するコアな部分を全て扱います。その上に機能を追加します。 +しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 - `FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 +/// - 基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 +/// check | "**FastAPI**での使用用途" + +webに関するコアな部分を全て扱います。その上に機能を追加します。 + +`FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 + +基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -403,12 +473,15 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構 Starletteや**FastAPI**のサーバーとして推奨されています。 -!!! check "**FastAPI**が推奨する理由" - **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 +/// check | "**FastAPI**が推奨する理由" + +**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 + +Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 - Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 +詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 - 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 +/// ## ベンチマーク と スピード diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index 5e38d1cec..ce9dac56f 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "備考" - `async def` を使用して作成された関数の内部でしか `await` は使用できません。 +/// note | "備考" + +`async def` を使用して作成された関数の内部でしか `await` は使用できません。 + +/// --- @@ -355,12 +358,15 @@ async def read_burgers(): ## 非常に発展的な技術的詳細 -!!! warning "注意" - 恐らくスキップしても良いでしょう。 +/// warning | "注意" + +恐らくスキップしても良いでしょう。 + +この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 - この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 +かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 - かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 +/// ### Path operation 関数 diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md index be8e9280e..86926b213 100644 --- a/docs/ja/docs/contributing.md +++ b/docs/ja/docs/contributing.md @@ -24,71 +24,84 @@ $ python -m venv env 新しい環境を有効化するには: -=== "Linux, macOS" +//// tab | Linux, macOS - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +<div class="termy"> - </div> +```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +</div> - もしwindows用のBash (例えば、<a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>)を使っているなら: +//// - <div class="termy"> +//// tab | Windows Bash - ```console - $ source ./env/Scripts/activate - ``` +もしwindows用のBash (例えば、<a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>)を使っているなら: - </div> +<div class="termy"> + +```console +$ source ./env/Scripts/activate +``` + +</div> + +//// 動作の確認には、下記を実行します: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ Get-Command pip +<div class="termy"> - some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip - </div> +some/directory/fastapi/env/bin/pip +``` + +</div> + +//// `env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉 -!!! tip "豆知識" - この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 +/// tip | "豆知識" + +この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 - これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 +これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 + +/// ### pip @@ -152,8 +165,11 @@ $ bash scripts/format-imports.sh そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。 -!!! tip "豆知識" - `./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 +/// tip | "豆知識" + +`./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 + +/// すべてのドキュメントが、Markdown形式で`./docs/en/`ディレクトリにあります。 @@ -238,10 +254,13 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 * あなたの言語の<a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">今あるプルリクエスト</a>を確認し、変更や承認をするレビューを追加します。 -!!! tip "豆知識" - すでにあるプルリクエストに<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">修正提案つきのコメントを追加</a>できます。 +/// tip | "豆知識" + +すでにあるプルリクエストに<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">修正提案つきのコメントを追加</a>できます。 + +修正提案の承認のために<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">プルリクエストのレビューの追加</a>のドキュメントを確認してください。 - 修正提案の承認のために<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">プルリクエストのレビューの追加</a>のドキュメントを確認してください。 +/// * <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">issues</a>をチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 @@ -263,8 +282,11 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。 -!!! tip "豆知識" - メイン (「公式」) 言語は英語で、`docs/en/`にあります。 +/// tip | "豆知識" + +メイン (「公式」) 言語は英語で、`docs/en/`にあります。 + +/// 次に、ドキュメントのライブサーバーをスペイン語で実行します: @@ -301,8 +323,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "豆知識" - パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 +/// tip | "豆知識" + +パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 + +/// * ここで、英語のMkDocs構成ファイルを開きます: @@ -373,10 +398,13 @@ Updating en これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。 -!!! tip "豆知識" - 翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 +/// tip | "豆知識" + +翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 + +そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 - そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 +/// まず、メインページの`docs/ht/index.md`を翻訳します。 diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md index abe4f2c66..c6b21fd1b 100644 --- a/docs/ja/docs/deployment/concepts.md +++ b/docs/ja/docs/deployment/concepts.md @@ -151,10 +151,13 @@ FastAPIでWeb APIを構築する際に、コードにエラーがある場合、 しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう。 -!!! tip - ...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 +/// tip - そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 +...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 + +そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 + +/// あなたはおそらく**外部コンポーネント**がアプリケーションの再起動を担当することを望むと考えます。 なぜなら、その時点でUvicornとPythonを使った同じアプリケーションはすでにクラッシュしており、同じアプリケーションの同じコードに対して何もできないためです。 @@ -243,11 +246,14 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * **クラウド・サービス**によるレプリケーション * クラウド・サービスはおそらく**あなたのためにレプリケーションを処理**します。**実行するプロセス**や使用する**コンテナイメージ**を定義できるかもしれませんが、いずれにせよ、それはおそらく**単一のUvicornプロセス**であり、クラウドサービスはそのレプリケーションを担当するでしょう。 -!!! tip - これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 - <!-- NOTE: the current version of docker.md is outdated compared to English one. --> +/// tip + +これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 +<!-- NOTE: the current version of docker.md is outdated compared to English one. --> + +コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. - コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. +/// ## 開始前の事前のステップ @@ -265,10 +271,13 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ もちろん、事前のステップを何度も実行しても問題がない場合もあり、その際は対処がかなり楽になります。 -!!! tip - また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 +/// tip - その場合は、このようなことを心配する必要はないです。🤷 +また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 + +その場合は、このようなことを心配する必要はないです。🤷 + +/// ### 事前ステップの戦略例 @@ -280,9 +289,12 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * 事前のステップを実行し、アプリケーションを起動するbashスクリプト * 利用するbashスクリプトを起動/再起動したり、エラーを検出したりする方法は以前として必要になるでしょう。 -!!! tip - <!-- NOTE: the current version of docker.md is outdated compared to English one. --> - コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. +/// tip + +<!-- NOTE: the current version of docker.md is outdated compared to English one. --> +コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. + +/// ## リソースの利用 diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index 0c9df648d..c294ef88d 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -6,9 +6,12 @@ FastAPIアプリケーションをデプロイする場合、一般的なアプ Linuxコンテナの使用には、**セキュリティ**、**反復可能性(レプリカビリティ)**、**シンプリシティ**など、いくつかの利点があります。 -!!! tip - TODO: なぜか遷移できない - お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 +/// tip + +TODO: なぜか遷移できない +お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 + +/// <details> <summary>Dockerfile プレビュー 👀</summary> @@ -139,10 +142,13 @@ Successfully installed fastapi pydantic uvicorn </div> -!!! info - パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 +/// info + +パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 - Poetryを使った例は、後述するセクションでご紹介します。👇 +Poetryを使った例は、後述するセクションでご紹介します。👇 + +/// ### **FastAPI**コードを作成する @@ -230,8 +236,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] そのためプログラムは `/code` で開始しその中にあなたのコードがある `./app` ディレクトリがあるので、**Uvicorn** は `app.main` から `app` を参照し、**インポート** することができます。 -!!! tip - コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 +/// tip + +コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 + +/// これで、次のようなディレクトリ構造になるはずです: @@ -305,10 +314,13 @@ $ docker build -t myimage . </div> -!!! tip - 末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 +/// tip + +末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 + +この場合、同じカレント・ディレクトリ(`.`)です。 - この場合、同じカレント・ディレクトリ(`.`)です。 +/// ### Dockerコンテナの起動する @@ -405,8 +417,11 @@ FastAPI アプリケーションの **コンテナ・イメージ**(および 例えば<a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>のように、**HTTPS**と**証明書**の**自動**取得を扱う別のコンテナである可能性もあります。 -!!! tip - TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 +/// tip + +TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 + +/// あるいは、(コンテナ内でアプリケーションを実行しながら)クラウド・プロバイダーがサービスの1つとしてHTTPSを処理することもできます。 @@ -434,8 +449,11 @@ Kubernetesのような分散コンテナ管理システムの1つは通常、入 このコンポーネントはリクエストの **負荷** を受け、 (うまくいけば) その負荷を**バランスよく** ワーカーに分配するので、一般に **ロードバランサ** とも呼ばれます。 -!!! tip - HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 +/// tip + +HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 + +/// そしてコンテナで作業する場合、コンテナの起動と管理に使用する同じシステムには、**ロードバランサー**(**TLS Termination Proxy**の可能性もある)から**ネットワーク通信**(HTTPリクエストなど)をアプリのあるコンテナ(複数可)に送信するための内部ツールが既にあるはずです。 @@ -520,8 +538,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ 複数の**コンテナ**があり、おそらくそれぞれが**単一のプロセス**を実行している場合(**Kubernetes**クラスタなど)、レプリケートされたワーカーコンテナを実行する**前に**、単一のコンテナで**事前のステップ**の作業を行う**別のコンテナ**を持ちたいと思うでしょう。 -!!! info - もしKubernetesを使用している場合, これはおそらく<a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init コンテナ</a>でしょう。 +/// info + +もしKubernetesを使用している場合, これはおそらく<a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init コンテナ</a>でしょう。 + +/// ユースケースが事前のステップを**並列で複数回**実行するのに問題がない場合(例:データベースの準備チェック)、メインプロセスを開始する前に、それらのステップを各コンテナに入れることが可能です。 @@ -537,8 +558,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. -!!! warning - このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 +/// warning + +このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 + +/// このイメージには、利用可能なCPUコアに基づいて**ワーカー・プロセスの数**を設定する**オートチューニング**メカニズムが含まれています。 @@ -546,8 +570,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ また、スクリプトで<a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**開始前の事前ステップ**</a>を実行することもサポートしている。 -!!! tip - すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a> +/// tip + +すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a> + +/// ### 公式Dockerイメージのプロセス数 @@ -672,8 +699,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 9. 生成された `requirements.txt` ファイルにあるパッケージの依存関係をインストールします 10. app` ディレクトリを `/code` ディレクトリにコピーします 11. uvicorn` コマンドを実行して、`app.main` からインポートした `app` オブジェクトを使用するように指示します -!!! tip - "+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます +/// tip + +"+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます + +/// **Dockerステージ**は`Dockerfile`の一部で、**一時的なコンテナイメージ**として動作します。 diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md index a291f870f..ac40b0982 100644 --- a/docs/ja/docs/deployment/https.md +++ b/docs/ja/docs/deployment/https.md @@ -4,8 +4,11 @@ HTTPSは単に「有効」か「無効」かで決まるものだと思いがち しかし、それよりもはるかに複雑です。 -!!! tip - もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 +/// tip + +もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 + +/// 利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>. @@ -75,8 +78,11 @@ DNSサーバーでは、**取得したドメイン**をあなたのサーバー これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。 -!!! tip - ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 +/// tip + +ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 + +/// ### DNS @@ -124,8 +130,11 @@ TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)に これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。 -!!! tip - 通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 +/// tip + +通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 + +/// ### HTTPS リクエスト diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index 449aea31e..c17e63728 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -4,66 +4,77 @@ 以下の様なASGI対応のサーバをインストールする必要があります: -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, uvloopとhttptoolsを基にした高速なASGIサーバ。 +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, uvloopとhttptoolsを基にした高速なASGIサーバ。 - <div class="termy"> +<div class="termy"> - ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` - </div> +</div> -!!! tip "豆知識" - `standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 +//// - これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 +/// tip | "豆知識" -=== "Hypercorn" +`standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。 +これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 - <div class="termy"> +/// - ```console - $ pip install hypercorn +//// tab | Hypercorn - ---> 100% - ``` +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。 - </div> +<div class="termy"> - ...または、これら以外のASGIサーバ。 +```console +$ pip install hypercorn + +---> 100% +``` + +</div> + +...または、これら以外のASGIサーバ。 + +//// そして、チュートリアルと同様な方法でアプリケーションを起動して下さい。ただし、以下の様に`--reload` オプションは使用しないで下さい: -=== "Uvicorn" +//// tab | Uvicorn + +<div class="termy"> + +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - <div class="termy"> +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +</div> - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// - </div> +//// tab | Hypercorn -=== "Hypercorn" +<div class="termy"> - <div class="termy"> +```console +$ hypercorn main:app --bind 0.0.0.0:80 - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +</div> - </div> +//// 停止した場合に自動的に再起動させるツールを設定したいかもしれません。 diff --git a/docs/ja/docs/deployment/server-workers.md b/docs/ja/docs/deployment/server-workers.md index 51d0bc2d4..38ceab017 100644 --- a/docs/ja/docs/deployment/server-workers.md +++ b/docs/ja/docs/deployment/server-workers.md @@ -17,11 +17,14 @@ ここでは<a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a>が**Uvicornのワーカー・プロセス**を管理する場合の使い方について紹介していきます。 -!!! info - <!-- NOTE: the current version of docker.md is outdated compared to English one. --> - DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank} +/// info - 特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 +<!-- NOTE: the current version of docker.md is outdated compared to English one. --> +DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank} + +特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +/// ## GunicornによるUvicornのワーカー・プロセスの管理 diff --git a/docs/ja/docs/deployment/versions.md b/docs/ja/docs/deployment/versions.md index 03cccb3f3..941ddb71b 100644 --- a/docs/ja/docs/deployment/versions.md +++ b/docs/ja/docs/deployment/versions.md @@ -42,8 +42,11 @@ PoetryやPipenvなど、他のインストール管理ツールを使用して FastAPIでは「パッチ」バージョンはバグ修正と非破壊的な変更に留めるという規約に従っています。 -!!! tip "豆知識" - 「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 +/// tip | "豆知識" + +「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 + +/// 従って、以下の様なバージョンの固定が望ましいです: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 破壊的な変更と新機能実装は「マイナー」バージョンで加えられます。 -!!! tip "豆知識" - 「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 +/// tip | "豆知識" + +「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 + +/// ## FastAPIのバージョンのアップグレード diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md index 4cd15c8aa..65cebc8d2 100644 --- a/docs/ja/docs/external-links.md +++ b/docs/ja/docs/external-links.md @@ -6,8 +6,11 @@ それらの不完全なリストを以下に示します。 -!!! tip "豆知識" - ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">プルリクエストして下さい</a>。 +/// tip | "豆知識" + +ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">プルリクエストして下さい</a>。 + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 98c59e7c4..73c0192c7 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "情報" - `**second_user_data` は以下を意味します: +/// info | "情報" - `second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 +`**second_user_data` は以下を意味します: + +`second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 + +/// ### エディタのサポート diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index f8e02fdc3..730a209ab 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -12,8 +12,11 @@ しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 -!!! note "備考" - もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 +/// note | "備考" + +もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 + +/// ## 動機 @@ -172,10 +175,13 @@ John Doe {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "豆知識" - 角括弧内の内部の型は「型パラメータ」と呼ばれています。 +/// tip | "豆知識" + +角括弧内の内部の型は「型パラメータ」と呼ばれています。 + +この場合、`str`は`List`に渡される型パラメータです。 - この場合、`str`は`List`に渡される型パラメータです。 +/// つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。 @@ -282,8 +288,11 @@ Pydanticの公式ドキュメントから引用: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info "情報" - Pydanticについてより学びたい方は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">ドキュメントを参照してください</a>. +/// info | "情報" + +Pydanticについてより学びたい方は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">ドキュメントを参照してください</a>. + +/// **FastAPI** はすべてPydanticをベースにしています。 @@ -311,5 +320,8 @@ Pydanticの公式ドキュメントから引用: 重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。 -!!! info "情報" - すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`のチートシートを参照してください</a> +/// info | "情報" + +すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`のチートシートを参照してください</a> + +/// diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index 8f01e8216..b9f6d694b 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -10,8 +10,11 @@ {!../../../docs_src/body_fields/tutorial001.py!} ``` -!!! warning "注意" - `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 +/// warning | "注意" + +`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 + +/// ## モデルの属性の宣言 @@ -23,17 +26,23 @@ `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 -!!! note "技術詳細" - 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 +/// note | "技術詳細" + +実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 + +また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 + +`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 + +`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 - また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 +/// - `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 +/// tip | "豆知識" - `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 +型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 -!!! tip "豆知識" - 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 +/// ## 追加情報の追加 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 2ba10c583..c051fde24 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -12,8 +12,11 @@ {!../../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! note "備考" - この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 +/// note | "備考" + +この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 + +/// ## 複数のボディパラメータ @@ -53,8 +56,11 @@ } ``` -!!! note "備考" - 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 +/// note | "備考" + +以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 + +/// **FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。 @@ -112,9 +118,11 @@ q: str = None {!../../../docs_src/body_multiple_params/tutorial004.py!} ``` -!!! info "情報" - `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 +/// info | "情報" + +`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 +/// ## 単一のボディパラメータの埋め込み diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 092e25798..59ee67295 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -162,8 +162,11 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する } ``` -!!! info "情報" - `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 +/// info | "情報" + +`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 + +/// ## 深くネストされたモデル @@ -173,8 +176,11 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する {!../../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "情報" - `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 +/// info | "情報" + +`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 + +/// ## 純粋なリストのボディ @@ -222,14 +228,17 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの {!../../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "豆知識" - JSONはキーとして`str`しかサポートしていないことに注意してください。 +/// tip | "豆知識" + +JSONはキーとして`str`しかサポートしていないことに注意してください。 + +しかしPydanticには自動データ変換機能があります。 - しかしPydanticには自動データ変換機能があります。 +これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 - これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 +そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 - そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index 95d328ec5..672a03a64 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -34,14 +34,17 @@ つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。 -!!! note "備考" - `PATCH`は`PUT`よりもあまり使われておらず、知られていません。 +/// note | "備考" - また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 +`PATCH`は`PUT`よりもあまり使われておらず、知られていません。 - **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 +また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 - しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 +**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 + +しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 + +/// ### Pydanticの`exclude_unset`パラメータの使用 @@ -86,14 +89,20 @@ {!../../../docs_src/body_updates/tutorial002.py!} ``` -!!! tip "豆知識" - 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 +/// tip | "豆知識" + +実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 + +しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 + +/// + +/// note | "備考" - しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 +入力モデルがまだ検証されていることに注目してください。 -!!! note "備考" - 入力モデルがまだ検証されていることに注目してください。 +そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 - そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 +**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 - **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 +/// diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index ccce9484d..017ff8986 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -8,12 +8,15 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **リクエスト** ボディを宣言するために <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> モデルを使用します。そして、その全てのパワーとメリットを利用します。 -!!! info "情報" - データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 +/// info | "情報" - GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 +データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 - 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 +GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 + +非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 + +/// ## Pydanticの `BaseModel` をインポート @@ -110,16 +113,19 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ <img src="/img/tutorial/body/image05.png"> -!!! tip "豆知識" - <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>エディタを使用している場合は、<a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>が使用可能です。 +/// tip | "豆知識" + +<a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>エディタを使用している場合は、<a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>が使用可能です。 - 以下のエディターサポートが強化されます: +以下のエディターサポートが強化されます: - * 自動補完 - * 型チェック - * リファクタリング - * 検索 - * インスペクション +* 自動補完 +* 型チェック +* リファクタリング +* 検索 +* インスペクション + +/// ## モデルの使用 @@ -155,10 +161,13 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ * パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。 * パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。 -!!! note "備考" - FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 +/// note | "備考" + +FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 + +`Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 - `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 +/// ## Pydanticを使わない方法 diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 193be305f..212885209 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -20,13 +20,19 @@ {!../../../docs_src/cookie_params/tutorial001.py!} ``` -!!! note "技術詳細" - `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// note | "技術詳細" - しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +`Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 -!!! info "情報" - クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 +しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 + +/// + +/// info | "情報" + +クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## まとめ diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9d6ce8cdc..738240342 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -78,7 +78,10 @@ <abbr title="Cross-Origin Resource Sharing (オリジン間リソース共有)">CORS</abbr>についてより詳しい情報は、<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS documentation</a> を参照して下さい。 -!!! note "技術詳細" - `from starlette.middleware.cors import CORSMiddleware` も使用できます。 +/// note | "技術詳細" - **FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 +`from starlette.middleware.cors import CORSMiddleware` も使用できます。 + +**FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 + +/// diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 35e1ca7ad..06b8ad277 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app は実行されません。 -!!! info "情報" - より詳しい情報は、<a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">公式Pythonドキュメント</a>を参照してください。 +/// info | "情報" + +より詳しい情報は、<a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">公式Pythonドキュメント</a>を参照してください。 + +/// ## デバッガーでコードを実行 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index 5c150d00c..69b67d042 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -185,7 +185,10 @@ commons: CommonQueryParams = Depends() ...そして **FastAPI** は何をすべきか知っています。 -!!! tip "豆知識" - 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 +/// tip | "豆知識" - それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 +役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 + +それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 + +/// diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 1684d9ca1..c6472cab5 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,12 +20,15 @@ これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 -!!! tip "豆知識" - エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 +/// tip | "豆知識" - `dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 +エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 - また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 +`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 + +また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 + +/// ## 依存関係のエラーと戻り値 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index c0642efd4..3f22a7a7b 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,27 +4,36 @@ FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown" これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップを書きます。 -!!! tip "豆知識" - `yield`は必ず一度だけ使用するようにしてください。 +/// tip | "豆知識" -!!! info "情報" - これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります: +`yield`は必ず一度だけ使用するようにしてください。 - ``` - pip install async-exit-stack async-generator - ``` +/// - これにより<a href="https://github.com/sorcio/async_exit_stack" class="external-link" target="_blank">async-exit-stack</a>と<a href="https://github.com/python-trio/async_generator" class="external-link" target="_blank">async-generator</a>がインストールされます。 +/// info | "情報" -!!! note "技術詳細" - 以下と一緒に使用できる関数なら何でも有効です: +これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります: - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>または - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +``` +pip install async-exit-stack async-generator +``` + +これにより<a href="https://github.com/sorcio/async_exit_stack" class="external-link" target="_blank">async-exit-stack</a>と<a href="https://github.com/python-trio/async_generator" class="external-link" target="_blank">async-generator</a>がインストールされます。 + +/// + +/// note | "技術詳細" + +以下と一緒に使用できる関数なら何でも有効です: - これらは **FastAPI** の依存関係として使用するのに有効です。 +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>または +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - 実際、FastAPIは内部的にこれら2つのデコレータを使用しています。 +これらは **FastAPI** の依存関係として使用するのに有効です。 + +実際、FastAPIは内部的にこれら2つのデコレータを使用しています。 + +/// ## `yield`を持つデータベースの依存関係 @@ -48,10 +57,13 @@ FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown" {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip "豆知識" - `async`や通常の関数を使用することができます。 +/// tip | "豆知識" + +`async`や通常の関数を使用することができます。 - **FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。 +**FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。 + +/// ## `yield`と`try`を持つ依存関係 @@ -97,10 +109,13 @@ FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown" **FastAPI** は、全てが正しい順序で実行されていることを確認します。 -!!! note "技術詳細" - これはPythonの<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>のおかげで動作します。 +/// note | "技術詳細" + +これはPythonの<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>のおかげで動作します。 - **FastAPI** はこれを実現するために内部的に使用しています。 +**FastAPI** はこれを実現するために内部的に使用しています。 + +/// ## `yield`と`HTTPException`を持つ依存関係 @@ -122,8 +137,11 @@ FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown" レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成してください。 -!!! tip "豆知識" - `HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。 +/// tip | "豆知識" + +`HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。 + +/// 実行の順序は多かれ少なかれ以下の図のようになります。時間は上から下へと流れていきます。そして、各列はコードを相互作用させたり、実行したりしている部分の一つです。 @@ -165,15 +183,21 @@ participant tasks as Background tasks end ``` -!!! info "情報" - **1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。 +/// info | "情報" + +**1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。 + +いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。 + +/// - いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。 +/// tip | "豆知識" -!!! tip "豆知識" - この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。 +この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。 - しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。 +しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。 + +/// ## コンテキストマネージャ @@ -197,10 +221,13 @@ with open("./somefile.txt") as f: ### `yield`を持つ依存関係でのコンテキストマネージャの使用 -!!! warning "注意" - これは多かれ少なかれ、「高度な」発想です。 +/// warning | "注意" + +これは多かれ少なかれ、「高度な」発想です。 + +**FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。 - **FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。 +/// Pythonでは、<a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`</a>ことでコンテキストマネージャを作成することができます。 @@ -210,16 +237,19 @@ Pythonでは、<a href="https://docs.python.org/3/reference/datamodel.html#conte {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip "豆知識" - コンテキストマネージャを作成するもう一つの方法はwithです: +/// tip | "豆知識" + +コンテキストマネージャを作成するもう一つの方法はwithです: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> または +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> または - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +これらを使って、関数を単一の`yield`でデコレートすることができます。 - これらを使って、関数を単一の`yield`でデコレートすることができます。 +これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 - これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 +しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 - しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 +FastAPIが内部的にやってくれます。 - FastAPIが内部的にやってくれます。 +/// diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md index ec563a16d..000148d1c 100644 --- a/docs/ja/docs/tutorial/dependencies/index.md +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -75,8 +75,11 @@ そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。 -!!! tip "豆知識" - 次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 +/// tip | "豆知識" + +次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 + +/// 新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います: @@ -97,10 +100,13 @@ common_parameters --> read_users この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。 -!!! check "確認" - 特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 +/// check | "確認" + +特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 - `Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 +`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 + +/// ## `async`にするかどうか @@ -112,8 +118,11 @@ common_parameters --> read_users それは重要ではありません。**FastAPI** は何をすべきかを知っています。 -!!! note "備考" - わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 +/// note | "備考" + +わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 + +/// ## OpenAPIとの統合 diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md index 8848ac79e..e183f28ba 100644 --- a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md @@ -41,10 +41,13 @@ {!../../../docs_src/dependencies/tutorial005.py!} ``` -!!! info "情報" - *path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 +/// info | "情報" - しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 +*path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 + +しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 + +/// ```mermaid graph TB @@ -78,9 +81,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。 -!!! tip "豆知識" - これらの単純な例では、全てが役に立つとは言えないかもしれません。 +/// tip | "豆知識" + +これらの単純な例では、全てが役に立つとは言えないかもしれません。 + +しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 - しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 +そして、あなたを救うコードの量もみることになるでしょう。 - そして、あなたを救うコードの量もみることになるでしょう。 +/// diff --git a/docs/ja/docs/tutorial/encoder.md b/docs/ja/docs/tutorial/encoder.md index 305867ab7..086e1fc63 100644 --- a/docs/ja/docs/tutorial/encoder.md +++ b/docs/ja/docs/tutorial/encoder.md @@ -30,5 +30,8 @@ Pydanticモデルのようなオブジェクトを受け取り、JSON互換版 これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。 -!!! note "備考" - `jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 +/// note | "備考" + +`jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 + +/// diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md index aa2e5ffdc..90a22d3fa 100644 --- a/docs/ja/docs/tutorial/extra-models.md +++ b/docs/ja/docs/tutorial/extra-models.md @@ -8,10 +8,13 @@ * **出力モデル**はパスワードをもつべきではありません。 * **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。 -!!! danger "危険" - ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 +/// danger | "危険" - 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 +ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 + +知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 + +/// ## 複数のモデル @@ -131,8 +134,11 @@ UserInDB( ) ``` -!!! warning "注意" - サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 +/// warning | "注意" + +サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 + +/// ## 重複の削減 diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index f79ed94a4..dbe8e4518 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note "備考" - `uvicorn main:app`は以下を示します: +/// note | "備考" - * `main`: `main.py`ファイル (Python "module")。 - * `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 - * `--reload`: コードの変更時にサーバーを再起動させる。開発用。 +`uvicorn main:app`は以下を示します: + +* `main`: `main.py`ファイル (Python "module")。 +* `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 +* `--reload`: コードの変更時にサーバーを再起動させる。開発用。 + +/// 出力には次のような行があります: @@ -136,10 +139,13 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 -!!! note "技術詳細" - `FastAPI`は`Starlette`を直接継承するクラスです。 +/// note | "技術詳細" + +`FastAPI`は`Starlette`を直接継承するクラスです。 - `FastAPI`でも<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>のすべての機能を利用可能です。 +`FastAPI`でも<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>のすべての機能を利用可能です。 + +/// ### Step 2: `FastAPI`の「インスタンス」を生成 @@ -198,8 +204,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "情報" - 「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 +/// info | "情報" + +「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 + +/// APIを構築する際、「パス」は「関心事」と「リソース」を分離するための主要な方法です。 @@ -248,16 +257,19 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * パス `/` * <abbr title="an HTTP GET method"><code>get</code> オペレーション</abbr> -!!! info "`@decorator` について" - Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 +/// info | "`@decorator` について" - 「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 +Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 - 「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 +「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 - 私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 +「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 - これが「*パスオペレーションデコレータ*」です。 +私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 + +これが「*パスオペレーションデコレータ*」です。 + +/// 他のオペレーションも使用できます: @@ -272,14 +284,17 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * `@app.patch()` * `@app.trace()` -!!! tip "豆知識" - 各オペレーション (HTTPメソッド)は自由に使用できます。 +/// tip | "豆知識" + +各オペレーション (HTTPメソッド)は自由に使用できます。 - **FastAPI**は特定の意味づけを強制しません。 +**FastAPI**は特定の意味づけを強制しません。 - ここでの情報は、要件ではなくガイドラインとして提示されます。 +ここでの情報は、要件ではなくガイドラインとして提示されます。 - 例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 +例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 + +/// ### Step 4: **パスオペレーション**を定義 @@ -307,8 +322,11 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "備考" - 違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。 +/// note | "備考" + +違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。 + +/// ### Step 5: コンテンツの返信 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index 0b95cae0f..8be054858 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ Pythonの例外なので、`return`ではなく、`raise`です。 } ``` -!!! tip "豆知識" - `HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 +/// tip | "豆知識" - `dist`や`list`などを渡すことができます。 +`HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 - これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 +`dist`や`list`などを渡すことができます。 + +これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 + +/// ## カスタムヘッダーの追加 @@ -106,10 +109,13 @@ Pythonの例外なので、`return`ではなく、`raise`です。 {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "技術詳細" - また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 +/// note | "技術詳細" + +また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 +/// ## デフォルトの例外ハンドラのオーバーライド @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError`と`ValidationError` -!!! warning "注意" - これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 +/// warning | "注意" + +これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 + +/// `RequestValidationError`はPydanticの<a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>のサブクラスです。 @@ -183,10 +192,13 @@ path -> item_id {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "技術詳細" - また、`from starlette.responses import PlainTextResponse`を使用することもできます。 +/// note | "技術詳細" + +また、`from starlette.responses import PlainTextResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ### `RequestValidationError`のボディの使用 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index 1bf8440bb..4fab3d423 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -20,13 +20,19 @@ {!../../../docs_src/header_params/tutorial001.py!} ``` -!!! note "技術詳細" - `Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// note | "技術詳細" - しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +`Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 -!!! info "情報" - ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 +しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 + +/// + +/// info | "情報" + +ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## 自動変換 @@ -48,9 +54,11 @@ {!../../../docs_src/header_params/tutorial002.py!} ``` -!!! warning "注意" - `convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 +/// warning | "注意" + +`convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 +/// ## ヘッダーの重複 diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index 856cde44b..c5fe27259 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。 -!!! note "備考" - パーツ毎にインストールすることも可能です。 +/// note | "備考" - 以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: +パーツ毎にインストールすることも可能です。 - ``` - pip install fastapi - ``` +以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: - また、サーバーとして動作するように`uvicorn` をインストールします: +``` +pip install fastapi +``` + +また、サーバーとして動作するように`uvicorn` をインストールします: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +そして、使用したい依存関係をそれぞれ同様にインストールします。 - そして、使用したい依存関係をそれぞれ同様にインストールします。 +/// ## 高度なユーザーガイド diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index 73d7f02b2..eb85dc389 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -47,8 +47,11 @@ 説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 -!!! tip "豆知識" - 使用するすべてのタグにメタデータを追加する必要はありません。 +/// tip | "豆知識" + +使用するすべてのタグにメタデータを追加する必要はありません。 + +/// ### 自作タグの使用 @@ -58,8 +61,11 @@ {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info "情報" - タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 +/// info | "情報" + +タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 + +/// ### ドキュメントの確認 diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 973eb2b1a..05e1b7a8c 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * その**レスポンス**に対して何かを実行したり、必要なコードを実行したりできます。 * そして、**レスポンス**を返します。 -!!! note "技術詳細" - `yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 +/// note | "技術詳細" - バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 +`yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 + +バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 + +/// ## ミドルウェアの作成 @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "豆知識" - <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-'プレフィックスを使用</a>してカスタムの独自ヘッダーを追加できます。 +/// tip | "豆知識" + +<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-'プレフィックスを使用</a>してカスタムの独自ヘッダーを追加できます。 + +ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、<a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">StarletteのCORSドキュメント</a>に記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) + +/// + +/// note | "技術詳細" - ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、<a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">StarletteのCORSドキュメント</a>に記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) +`from starlette.requests import Request` を使用することもできます。 -!!! note "技術詳細" - `from starlette.requests import Request` を使用することもできます。 +**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 - **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 +/// ### `response` の前後 diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index 486c4b204..def12bd08 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ *path operationデコレータ*を設定するためのパラメータがいくつかあります。 -!!! warning "注意" - これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 +/// warning | "注意" + +これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 + +/// ## レスポンスステータスコード @@ -19,10 +22,13 @@ そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 -!!! note "技術詳細" - また、`from starlette import status`を使用することもできます。 +/// note | "技術詳細" + +また、`from starlette import status`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 +/// ## タグ @@ -66,13 +72,19 @@ docstringに<a href="https://en.wikipedia.org/wiki/Markdown" class="external-lin {!../../../docs_src/path_operation_configuration/tutorial005.py!} ``` -!!! info "情報" - `respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。 +/// info | "情報" + +`respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。 + +/// + +/// check | "確認" + +OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。 -!!! check "確認" - OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。 +そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。 - そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。 +/// <img src="https://fastapi.tiangolo.com/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 551aeabb3..9f0b72585 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -20,12 +20,15 @@ {!../../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` -!!! note "備考" - パスの一部でなければならないので、パスパラメータは常に必須です。 +/// note | "備考" - そのため、`...`を使用して必須と示す必要があります。 +パスの一部でなければならないので、パスパラメータは常に必須です。 - それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 +そのため、`...`を使用して必須と示す必要があります。 + +それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 + +/// ## 必要に応じてパラメータを並び替える @@ -105,18 +108,24 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `lt`: より小さい(`l`ess `t`han) * `le`: 以下(`l`ess than or `e`qual) -!!! info "情報" - `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) +/// info | "情報" + +`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) + +そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 + +/// + +/// note | "技術詳細" - そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 +`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 -!!! note "技術詳細" - `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 +呼び出されると、同じ名前のクラスのインスタンスを返します。 - 呼び出されると、同じ名前のクラスのインスタンスを返します。 +そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 - そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 +これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 - これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 +この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 - この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 +/// diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index b395dc41d..0a7916012 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー ここでは、 `item_id` は `int` として宣言されています。 -!!! check "確認" - これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 +/// check | "確認" + +これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 + +/// ## データ<abbr title="別名: serialization, parsing, marshalling">変換</abbr> @@ -35,10 +38,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {"item_id":3} ``` -!!! check "確認" - 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 +/// check | "確認" + +関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 + +したがって、型宣言を使用すると、**FastAPI**は自動リクエスト <abbr title="HTTPリクエストで受け取った文字列をPythonデータへ変換する">"解析"</abbr> を行います。 - したがって、型宣言を使用すると、**FastAPI**は自動リクエスト <abbr title="HTTPリクエストで受け取った文字列をPythonデータへ変換する">"解析"</abbr> を行います。 +/// ## データバリデーション @@ -63,12 +69,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。 -!!! check "確認" - したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 +/// check | "確認" - 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 +したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 - これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 +表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 + +これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 + +/// ## ドキュメント @@ -76,10 +85,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー <img src="/img/tutorial/path-params/image01.png"> -!!! check "確認" - 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 +/// check | "確認" + +繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 + +パスパラメータが整数として宣言されていることに注意してください。 - パスパラメータが整数として宣言されていることに注意してください。 +/// ## 標準であることのメリット、ドキュメンテーションの代替物 @@ -131,11 +143,17 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "情報" - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (もしくは、enums)はPython 3.4以降で利用できます</a>。 +/// info | "情報" -!!! tip "豆知識" - "AlexNet"、"ResNet"そして"LeNet"は機械学習<abbr title="Technically, Deep Learning model architectures">モデル</abbr>の名前です。 +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (もしくは、enums)はPython 3.4以降で利用できます</a>。 + +/// + +/// tip | "豆知識" + +"AlexNet"、"ResNet"そして"LeNet"は機械学習<abbr title="Technically, Deep Learning model architectures">モデル</abbr>の名前です。 + +/// ### *パスパラメータ*の宣言 @@ -171,8 +189,11 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "豆知識" - `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 +/// tip | "豆知識" + +`ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 + +/// #### *列挙型メンバ*の返却 @@ -225,10 +246,13 @@ Starletteのオプションを直接使用することで、以下のURLの様 {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "豆知識" - 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 +/// tip | "豆知識" + +最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 + +この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 - この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 8d375d7ce..ada048844 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,14 @@ クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 -!!! note "備考" - FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 +/// note | "備考" + +FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 + +`Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 + +/// - `Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 ## バリデーションの追加 `q`はオプショナルですが、もし値が渡されてきた場合には、**50文字を超えないこと**を強制してみましょう。 @@ -50,22 +54,25 @@ q: Optional[str] = None しかし、これはクエリパラメータとして明示的に宣言しています。 -!!! info "情報" - FastAPIは以下の部分を気にすることを覚えておいてください: +/// info | "情報" + +FastAPIは以下の部分を気にすることを覚えておいてください: + +```Python += None +``` - ```Python - = None - ``` +もしくは: - もしくは: +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 - そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 +`Optional` の部分は、エディターによるより良いサポートを可能にします。 - `Optional` の部分は、エディターによるより良いサポートを可能にします。 +/// そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。 @@ -111,8 +118,11 @@ q: Union[str, None] = Query(default=None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "備考" - デフォルト値を指定すると、パラメータは任意になります。 +/// note | "備考" + +デフォルト値を指定すると、パラメータは任意になります。 + +/// ## 必須にする @@ -140,8 +150,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "情報" - これまで`...`を見たことがない方へ: これは特殊な単一値です。<a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Pythonの一部であり、"Ellipsis"と呼ばれています</a>。 +/// info | "情報" + +これまで`...`を見たことがない方へ: これは特殊な単一値です。<a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Pythonの一部であり、"Ellipsis"と呼ばれています</a>。 + +/// これは **FastAPI** にこのパラメータが必須であることを知らせます。 @@ -174,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "豆知識" - 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 +/// tip | "豆知識" + +上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 + +/// 対話的APIドキュメントは複数の値を許可するために自動的に更新されます。 @@ -214,10 +230,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "備考" - この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 +/// note | "備考" - 例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 +この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 + +例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 + +/// ## より多くのメタデータを宣言する @@ -225,10 +244,13 @@ http://localhost:8000/items/ その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。 -!!! note "備考" - ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 +/// note | "備考" + +ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 + +その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 - その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 +/// `title`を追加できます: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 5c4cfc5fc..c0eb2d096 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -1,4 +1,3 @@ - # クエリパラメータ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 @@ -70,8 +69,11 @@ http://127.0.0.1:8000/items/?skip=20 この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 -!!! check "確認" - パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 +/// check | "確認" + +パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 + +/// ## クエリパラメータの型変換 @@ -189,6 +191,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`、デフォルト値を `0` とする `int` 。 * `limit`、オプショナルな `int` 。 -!!! tip "豆知識" +/// tip | "豆知識" + +[パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 - [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 +/// diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index 86913ccac..d8effc219 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -2,10 +2,13 @@ `File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 -!!! info "情報" - アップロードされたファイルやフォームデータを受信するには、まず<a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 +/// info | "情報" - 例えば、`pip install python-multipart`のように。 +アップロードされたファイルやフォームデータを受信するには、まず<a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 + +例えば、`pip install python-multipart`のように。 + +/// ## `File`と`Form`のインポート @@ -25,10 +28,13 @@ また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。 -!!! warning "注意" - *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 +/// warning | "注意" + +*path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 + +これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。 - これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index f90c49746..d04dc810b 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -2,10 +2,13 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 -!!! info "情報" - フォームを使うためには、まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 +/// info | "情報" - たとえば、`pip install python-multipart`のように。 +フォームを使うためには、まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 + +たとえば、`pip install python-multipart`のように。 + +/// ## `Form`のインポート @@ -29,11 +32,17 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。 -!!! info "情報" - `Form`は`Body`を直接継承するクラスです。 +/// info | "情報" + +`Form`は`Body`を直接継承するクラスです。 + +/// + +/// tip | "豆知識" -!!! tip "豆知識" - フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 +フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 + +/// ## 「フォームフィールド」について @@ -41,17 +50,23 @@ HTMLフォーム(`<form></form>`)がサーバにデータを送信する方 **FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。 -!!! note "技術詳細" - フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 +/// note | "技術詳細" + +フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 + +しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 + +これらのエンコーディングやフォームフィールドの詳細については、<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr>の<code>POST</code></a>のウェブドキュメントを参照してください。 + +/// - しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 +/// warning | "注意" - これらのエンコーディングやフォームフィールドの詳細については、<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr>の<code>POST</code></a>のウェブドキュメントを参照してください。 +*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 -!!! warning "注意" - *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 +これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 - これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index b8b6978d4..7bb5e2825 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -12,8 +12,11 @@ {!../../../docs_src/response_model/tutorial001.py!} ``` -!!! note "備考" - `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 +/// note | "備考" + +`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 + +/// Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。 @@ -28,8 +31,11 @@ FastAPIは`response_model`を使って以下のことをします: * 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 -!!! note "技術詳細" - レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 +/// note | "技術詳細" + +レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 + +/// ## 同じ入力データの返却 @@ -51,8 +57,11 @@ FastAPIは`response_model`を使って以下のことをします: しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 -!!! danger "危険" - ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 +/// danger | "危険" + +ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 + +/// ## 出力モデルの追加 @@ -121,16 +130,22 @@ FastAPIは`response_model`を使って以下のことをします: } ``` -!!! info "情報" - FastAPIはこれをするために、Pydanticモデルの`.dict()`を<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">その`exclude_unset`パラメータ</a>で使用しています。 +/// info | "情報" + +FastAPIはこれをするために、Pydanticモデルの`.dict()`を<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">その`exclude_unset`パラメータ</a>で使用しています。 + +/// -!!! info "情報" - 以下も使用することができます: +/// info | "情報" - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +以下も使用することができます: - `exclude_defaults`と`exclude_none`については、<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。 +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +`exclude_defaults`と`exclude_none`については、<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。 + +/// #### デフォルト値を持つフィールドの値を持つデータ @@ -165,9 +180,12 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d そのため、それらはJSONレスポンスに含まれることになります。 -!!! tip "豆知識" - デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 - 例えば、リスト(`[]`)や`10.5`の`float`などです。 +/// tip | "豆知識" + +デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 +例えば、リスト(`[]`)や`10.5`の`float`などです。 + +/// ### `response_model_include`と`response_model_exclude` @@ -177,21 +195,27 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 -!!! tip "豆知識" - それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 +/// tip | "豆知識" - これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 +それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 - 同様に動作する`response_model_by_alias`にも当てはまります。 +これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 + +同様に動作する`response_model_by_alias`にも当てはまります。 + +/// ```Python hl_lines="31 37" {!../../../docs_src/response_model/tutorial005.py!} ``` -!!! tip "豆知識" - `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 +/// tip | "豆知識" + +`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 + +これは`set(["name", "description"])`と同等です。 - これは`set(["name", "description"])`と同等です。 +/// #### `set`の代わりに`list`を使用する diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index ead2addda..945767894 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "備考" - `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 +/// note | "備考" + +`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 + +/// `status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 -!!! info "情報" - `status_code`は代わりに、Pythonの<a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>のように、`IntEnum`を受け取ることもできます。 +/// info | "情報" + +`status_code`は代わりに、Pythonの<a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>のように、`IntEnum`を受け取ることもできます。 + +/// これは: @@ -27,15 +33,21 @@ <img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image01.png"> -!!! note "備考" - いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 +/// note | "備考" + +いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 + +FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 - FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 +/// ## HTTPステータスコードについて -!!! note "備考" - すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 +/// note | "備考" + +すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 + +/// HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。 @@ -54,8 +66,11 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス * クライアントからの一般的なエラーについては、`400`を使用することができます。 * `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 -!!! tip "豆知識" - それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細は<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP レスポンスステータスコードについてのドキュメント</a>を参照してください。 +/// tip | "豆知識" + +それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細は<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP レスポンスステータスコードについてのドキュメント</a>を参照してください。 + +/// ## 名前を覚えるための近道 @@ -79,10 +94,13 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス <img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image02.png"> -!!! note "技術詳細" - また、`from starlette import status`を使うこともできます。 +/// note | "技術詳細" + +また、`from starlette import status`を使うこともできます。 + +**FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 - **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 +/// ## デフォルトの変更 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index d96163b82..a3cd5eb54 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -24,8 +24,11 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 {!../../../docs_src/schema_extra_example/tutorial002.py!} ``` -!!! warning "注意" - これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 +/// warning | "注意" + +これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 + +/// ## `Body`の追加引数 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index dc3267e62..c78a3755e 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -26,12 +26,15 @@ ## 実行 -!!! info "情報" - まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 +/// info | "情報" - 例えば、`pip install python-multipart`。 +まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。 - これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 +例えば、`pip install python-multipart`。 + +これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 + +/// 例を実行します: @@ -53,17 +56,23 @@ $ uvicorn main:app --reload <img src="/img/tutorial/security/image01.png"> -!!! check "Authorizeボタン!" - すでにピカピカの新しい「Authorize」ボタンがあります。 +/// check | "Authorizeボタン!" + +すでにピカピカの新しい「Authorize」ボタンがあります。 + +そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 - そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 +/// それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます: <img src="/img/tutorial/security/image02.png"> -!!! note "備考" - フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 +/// note | "備考" + +フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 + +/// もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。 @@ -105,14 +114,17 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。 -!!! info "情報" - 「bearer」トークンが、唯一の選択肢ではありません。 +/// info | "情報" + +「bearer」トークンが、唯一の選択肢ではありません。 - しかし、私たちのユースケースには最適です。 +しかし、私たちのユースケースには最適です。 - あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 +あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 - その場合、**FastAPI**はそれを構築するためのツールも提供します。 +その場合、**FastAPI**はそれを構築するためのツールも提供します。 + +/// `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 @@ -120,21 +132,27 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip "豆知識" - ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 +/// tip | "豆知識" + +ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 - 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。 +相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。 - 相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 +相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 + +/// このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。 実際のpath operationもすぐに作ります。 -!!! info "情報" - 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 +/// info | "情報" + +非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 - それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 +それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 + +/// 変数`oauth2_scheme`は`OAuth2PasswordBearer`のインスタンスですが、「呼び出し可能」です。 @@ -158,10 +176,13 @@ oauth2_scheme(some, parameters) **FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。 -!!! info "技術詳細" - **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 +/// info | "技術詳細" + +**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 + +OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 - OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 +/// ## どのように動作するか diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 7f8dcaad2..250f66b81 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -54,17 +54,21 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。 -!!! tip "豆知識" - リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 +/// tip | "豆知識" - ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 +リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 +ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 -!!! check "確認" - 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 +/// - 同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 +/// check | "確認" +依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 + +同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 + +/// ## 別のモデル diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md index 390f21047..c68e7e7f2 100644 --- a/docs/ja/docs/tutorial/security/index.md +++ b/docs/ja/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth 1というものもありましたが、これはOAuth2とは全く異な OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。 -!!! tip "豆知識" - **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 +/// tip | "豆知識" +**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPIでは、以下のセキュリティスキームを定義しています: * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。 -!!! tip "豆知識" - Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 +/// tip | "豆知識" + +Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 + +最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 - 最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 +/// ## **FastAPI** ユーティリティ diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index d5b179aa0..4f6aebd4c 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install python-jose[cryptography] ここでは、推奨されているものを使用します:<a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>。 -!!! tip "豆知識" - このチュートリアルでは以前、<a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>を使用していました。 +/// tip | "豆知識" - しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 +このチュートリアルでは以前、<a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>を使用していました。 + +しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 + +/// ## パスワードのハッシュ化 @@ -83,13 +86,15 @@ $ pip install passlib[bcrypt] </div> -!!! tip "豆知識" - `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 +/// tip | "豆知識" + +`passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 - 例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 +例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 - また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 +また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 +/// ## パスワードのハッシュ化と検証 @@ -97,12 +102,15 @@ $ pip install passlib[bcrypt] PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。 -!!! tip "豆知識" - PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 +/// tip | "豆知識" - 例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 +PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 - そして、同時にそれらはすべてに互換性があります。 +例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 + +そして、同時にそれらはすべてに互換性があります。 + +/// ユーザーから送られてきたパスワードをハッシュ化するユーティリティー関数を作成します。 @@ -114,8 +122,11 @@ PassLib の「context」を作成します。これは、パスワードのハ {!../../../docs_src/security/tutorial004.py!} ``` -!!! note "備考" - 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` +/// note | "備考" + +新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` + +/// ## JWTトークンの取り扱い @@ -208,8 +219,11 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す Username: `johndoe` Password: `secret` -!!! check "確認" - コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 +/// check | "確認" + +コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 + +/// <img src="/img/tutorial/security/image08.png"> @@ -230,8 +244,11 @@ Password: `secret` <img src="/img/tutorial/security/image10.png"> -!!! note "備考" - ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 +/// note | "備考" + +ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 + +/// ## `scopes` を使った高度なユースケース diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index 1d9c434c3..c9d95bc34 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "技術詳細" - `from starlette.staticfiles import StaticFiles` も使用できます。 +/// note | "技術詳細" - **FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 +`from starlette.staticfiles import StaticFiles` も使用できます。 + +**FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 + +/// ### 「マウント」とは diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 037e9628f..3ed03ebea 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -22,20 +22,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "豆知識" - テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 +/// tip | "豆知識" - また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 +テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 - これにより、煩雑にならずに、`pytest` を直接使用できます。 +また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 -!!! note "技術詳細" - `from starlette.testclient import TestClient` も使用できます。 +これにより、煩雑にならずに、`pytest` を直接使用できます。 - **FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 +/// -!!! tip "豆知識" - FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 +/// note | "技術詳細" + +`from starlette.testclient import TestClient` も使用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 + +/// + +/// tip | "豆知識" + +FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 + +/// ## テストの分離 @@ -74,17 +83,21 @@ これらの *path operation* には `X-Token` ヘッダーが必要です。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### 拡張版テストファイル @@ -108,10 +121,13 @@ (`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、<a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPXのドキュメント</a>を確認してください。 -!!! info "情報" - `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 +/// info | "情報" + +`TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 + +テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 - テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 +/// ## 実行 diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index d3227497b..e155f41f1 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -4,8 +4,11 @@ 이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. -!!! warning "경고" - 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. +/// warning | "경고" + +이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. + +/// ## `startup` 이벤트 @@ -31,15 +34,24 @@ 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. -!!! info "정보" - `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. +/// info | "정보" + +`open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. + +/// + +/// tip | "팁" + +이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. + +따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. + +그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. -!!! tip "팁" - 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. +/// - 따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. +/// info | "정보" - 그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. +이벤트 핸들러에 관한 내용은 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 이벤트 문서</a>에서 추가로 확인할 수 있습니다. -!!! info "정보" - 이벤트 핸들러에 관한 내용은 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 이벤트 문서</a>에서 추가로 확인할 수 있습니다. +/// diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md index 5fd1711a1..cb628fa10 100644 --- a/docs/ko/docs/advanced/index.md +++ b/docs/ko/docs/advanced/index.md @@ -6,10 +6,13 @@ 이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. -!!! tip "팁" - 다음 장들이 **반드시 "심화"**인 것은 아닙니다. +/// tip | "팁" - 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. +다음 장들이 **반드시 "심화"**인 것은 아닙니다. + +그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. + +/// ## 자습서를 먼저 읽으십시오 diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index 65ee124ec..dfc2caa78 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "참고" - `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. +/// note | "참고" + +`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. + +/// --- @@ -366,12 +369,15 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 <a href="https://anyi ## 매우 세부적인 기술적 사항 -!!! warning "경고" - 이 부분은 넘어가도 됩니다. +/// warning | "경고" + +이 부분은 넘어가도 됩니다. + +이것들은 **FastAPI**가 내부적으로 어떻게 동작하는지에 대한 매우 세부적인 기술사항입니다. - 이것들은 **FastAPI**가 내부적으로 어떻게 동작하는지에 대한 매우 세부적인 기술사항입니다. +만약 기술적 지식(코루틴, 스레드, 블록킹 등)이 있고 FastAPI가 어떻게 `async def` vs `def`를 다루는지 궁금하다면, 계속하십시오. - 만약 기술적 지식(코루틴, 스레드, 블록킹 등)이 있고 FastAPI가 어떻게 `async def` vs `def`를 다루는지 궁금하다면, 계속하십시오. +/// ### 경로 작동 함수 diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md index 0e8f85cae..edf10b318 100644 --- a/docs/ko/docs/deployment/docker.md +++ b/docs/ko/docs/deployment/docker.md @@ -4,8 +4,11 @@ FastAPI 어플리케이션을 배포할 때 일반적인 접근 방법은 **리 리눅스 컨테이너를 사용하는 데에는 **보안**, **반복 가능성**, **단순함** 등의 장점이 있습니다. -!!! tip "팁" - 시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다. +/// tip | "팁" + +시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다. + +/// <details> <summary>도커파일 미리보기 👀</summary> @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn </div> -!!! info "정보" - 패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. +/// info | "정보" + +패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. - 나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 +나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 + +/// ### **FastAPI** 코드 생성하기 @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다. -!!! tip "팁" - 각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 +/// tip | "팁" + +각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 + +/// 이제 여러분은 다음과 같은 디렉터리 구조를 가지고 있을 것입니다: @@ -293,10 +302,13 @@ $ docker build -t myimage . </div> -!!! tip "팁" - 맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. +/// tip | "팁" + +맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. + +이 경우에는 현재 디렉터리(`.`)와 같습니다. - 이 경우에는 현재 디렉터리(`.`)와 같습니다. +/// ### 도커 컨테이너 시작하기 @@ -394,8 +406,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] **HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>을 사용하는 것입니다. -!!! tip "팁" - Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. +/// tip | "팁" + +Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. + +/// 대안적으로, HTTPS는 클라우드 제공자에 의해 서비스의 일환으로 다루어질 수도 있습니다 (이때도 어플리케이션은 여전히 컨테이너에서 실행될 것입니다). @@ -423,8 +438,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다. -!!! tip "팁" - HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. +/// tip | "팁" + +HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. + +/// 또한 컨테이너로 작업할 때, 컨테이너를 시작하고 관리하기 위해 사용한 것과 동일한 시스템은 이미 해당 **로드 밸런서**로 부터 여러분의 앱에 해당하는 컨테이너로 **네트워크 통신**(예를 들어, HTTP 요청)을 전송하는 내부적인 도구를 가지고 있을 것입니다 (여기서도 로드 밸런서는 **TLS 종료 프록시**일 수 있습니다). @@ -503,8 +521,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다. -!!! info "정보" - 만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>일 것입니다. +/// info | "정보" + +만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>일 것입니다. + +/// 만약 여러분의 이용 사례에서 이전 단계들을 **병렬적으로 여러번** 수행하는데에 문제가 없다면 (예를 들어 데이터베이스 이전을 실행하지 않고 데이터베이스가 준비되었는지 확인만 하는 경우), 메인 프로세스를 시작하기 전에 이 단계들을 각 컨테이너에 넣을 수 있습니다. @@ -520,8 +541,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. -!!! warning "경고" - 여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. +/// warning | "경고" + +여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. + +/// 이 이미지는 가능한 CPU 코어에 기반한 **몇개의 워커 프로세스**를 설정하는 **자동-튜닝** 메커니즘을 포함하고 있습니다. @@ -529,8 +553,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 또한 스크립트를 통해 <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**시작하기 전 사전 단계**</a>를 실행하는 것을 지원합니다. -!!! tip "팁" - 모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +/// tip | "팁" + +모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +/// ### 공식 도커 이미지에 있는 프로세스 개수 @@ -657,8 +684,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다. -!!! tip "팁" - 버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. +/// tip | "팁" + +버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. + +/// **도커 스테이지**란 `Dockefile`의 일부로서 나중에 사용하기 위한 파일들을 생성하기 위한 **일시적인 컨테이너 이미지**로 작동합니다. diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md index f7ef96094..39976faf5 100644 --- a/docs/ko/docs/deployment/server-workers.md +++ b/docs/ko/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ 지금부터 <a href="https://gunicorn.org/" class="external-link" target="_blank">**구니콘**</a>을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. -!!! info "정보" - 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. +/// info | "정보" - 특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. +만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. + +특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. + +/// ## 구니콘과 유비콘 워커 diff --git a/docs/ko/docs/deployment/versions.md b/docs/ko/docs/deployment/versions.md index 074c15158..f3b3c2d7b 100644 --- a/docs/ko/docs/deployment/versions.md +++ b/docs/ko/docs/deployment/versions.md @@ -43,8 +43,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI는 오류를 수정하고, 일반적인 변경사항을 위해 "패치"버전의 관습을 따릅니다. -!!! tip "팁" - 여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. +/// tip | "팁" + +여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. + +/// 따라서 다음과 같이 버전을 표시할 수 있습니다: @@ -54,8 +57,11 @@ fastapi>=0.45.0,<0.46.0 수정된 사항과 새로운 요소들이 "마이너" 버전에 추가되었습니다. -!!! tip "팁" - "마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. +/// tip | "팁" + +"마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. + +/// ## FastAPI 버전의 업그레이드 diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index ca1940a21..b6f6f7af2 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "정보" - `**second_user_data`가 뜻하는 것: +/// info | "정보" - `second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data`가 뜻하는 것: + +`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 편집기 지원 diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 267ce6c7e..5c458e48d 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -12,8 +12,11 @@ 비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다. -!!! note "참고" - 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. +/// note | "참고" + +파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. + +/// ## 동기 부여 @@ -172,10 +175,13 @@ John Doe {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "팁" - 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. +/// tip | "팁" + +대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. + +이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. - 이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. +/// 이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다. @@ -281,9 +287,11 @@ Pydantic 공식 문서 예시: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info "정보" - Pydantic<에 대해 더 배우고 싶다면 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a> +/// info | "정보" +Pydantic<에 대해 더 배우고 싶다면 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a> + +/// **FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다. @@ -311,5 +319,8 @@ Pydantic 공식 문서 예시: 가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠. -!!! info "정보" - 만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`에서 제공하는 "cheat sheet"</a>이 좋은 자료가 될 겁니다. +/// info | "정보" + +만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`에서 제공하는 "cheat sheet"</a>이 좋은 자료가 될 겁니다. + +/// diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index ee83d6570..880a1c198 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -57,17 +57,21 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ **FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. -=== "Python 3.6 and above" +//// tab | Python 3.6 and above - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` + +//// -=== "Python 3.10 and above" +//// tab | Python 3.10 and above + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// 이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index c91d6130b..b74722e26 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ 먼저 이를 임포트해야 합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -!!! warning "경고" - `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "경고" + +`Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. + +/// ## 모델 어트리뷰트 선언 그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ Annotated가 없는 경우" +//// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// tab | Python 3.10+ Annotated가 없는 경우 - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip | "팁" -=== "Python 3.8+ Annotated가 없는 경우" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. -!!! note "기술적 세부사항" - 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. +/// note | "기술적 세부사항" - 그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. +실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. - `Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. +그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. - `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. +`Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. -!!! tip "팁" - 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. + +/// + +/// tip | "팁" + +주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + +/// ## 별도 정보 추가 @@ -105,9 +146,12 @@ 여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다. -!!! warning "경고" - 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. - 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. +/// warning | "경고" + +별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. +이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. + +/// ## 요약 diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 2cf5df7f3..023575e1b 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -14,8 +14,11 @@ {!../../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! note "참고" - 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. +/// note | "참고" + +이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. + +/// ## 다중 본문 매개변수 @@ -55,8 +58,11 @@ } ``` -!!! note "참고" - 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. +/// note | "참고" + +이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. + +/// FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 특별한 내용으로 받도록 할 것입니다. @@ -114,8 +120,11 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 q: Optional[str] = None ``` -!!! info "정보" - `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. +/// info | "정보" + +`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. + +/// ## 단일 본문 매개변수 삽입하기 diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index 10af0a062..4d785f64b 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -161,8 +161,11 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. } ``` -!!! info "정보" - `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. +/// info | "정보" + +`images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. + +/// ## 깊게 중첩된 모델 @@ -172,8 +175,11 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. {!../../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "정보" - `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 +/// info | "정보" + +`Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 + +/// ## 순수 리스트의 본문 @@ -221,14 +227,17 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 {!../../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "팁" - JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. +/// tip | "팁" + +JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. + +하지만 Pydantic은 자동 데이터 변환이 있습니다. - 하지만 Pydantic은 자동 데이터 변환이 있습니다. +즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. - 즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. +그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. - 그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 0ab8b7162..337218eb4 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -8,28 +8,35 @@ **요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 모델을 사용합니다. -!!! info "정보" - 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. +/// info | "정보" - `GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. +데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. - `GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. +`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. + +`GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. + +/// ## Pydantic의 `BaseModel` 임포트 먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// ## 여러분의 데이터 모델 만들기 @@ -37,17 +44,21 @@ 모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// 쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. @@ -75,17 +86,21 @@ 여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. @@ -134,32 +149,39 @@ <img src="/img/tutorial/body/image05.png"> -!!! tip "팁" - 만약 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>를 편집기로 사용한다면, <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>을 사용할 수 있습니다. +/// tip | "팁" + +만약 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>를 편집기로 사용한다면, <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>을 사용할 수 있습니다. - 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: +다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: - * 자동 완성 - * 타입 확인 - * 리팩토링 - * 검색 - * 점검 +* 자동 완성 +* 타입 확인 +* 리팩토링 +* 검색 +* 점검 + +/// ## 모델 사용하기 함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## 요청 본문 + 경로 매개변수 @@ -167,17 +189,21 @@ **FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## 요청 본문 + 경로 + 쿼리 매개변수 @@ -185,17 +211,21 @@ **FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` + +//// 함수 매개변수는 다음을 따라서 인지하게 됩니다: @@ -203,10 +233,13 @@ * 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. * 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. -!!! note "참고" - FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. +/// note | "참고" + +FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. + +`Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. - `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. +/// ## Pydantic없이 diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index d4f3d57a3..5f129b63f 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ 먼저 `Cookie`를 임포트합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## `Cookie` 매개변수 선언 @@ -48,49 +64,71 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ Annotated가 없는 경우 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip | "팁" -=== "Python 3.8+" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ Annotated가 없는 경우" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "기술 세부사항" -=== "Python 3.8+ Annotated가 없는 경우" +`Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +`Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "기술 세부사항" - `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. +/// info | "정보" - `Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. +쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. -!!! info "정보" - 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 39e9ea83f..312fdee1b 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -78,7 +78,10 @@ <abbr title="교차-출처 리소스 공유">CORS</abbr>에 대한 더 많은 정보를 알고싶다면, <a href="https://developer.mozilla.org/ko/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS 문서</a>를 참고하기 바랍니다. -!!! note "기술적 세부 사항" - `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. +/// note | "기술적 세부 사항" - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. +`from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. + +/// diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index c3e588537..cb45e5169 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app 은 실행되지 않습니다. -!!! info "정보" - 자세한 내용은 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">공식 Python 문서</a>를 확인하세요 +/// info | "정보" + +자세한 내용은 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">공식 Python 문서</a>를 확인하세요 + +/// ## 디버거로 코드 실행 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 38cdc2e1a..259fe4b6d 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ 이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다. @@ -77,45 +81,57 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// 클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// ...이전 `common_parameters`와 동일한 매개변수를 가집니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다 @@ -131,17 +147,21 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다. -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// **FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다. @@ -180,17 +200,21 @@ commons = Depends(CommonQueryParams) ..전체적인 코드는 아래와 같습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` + +//// 그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다. @@ -224,21 +248,28 @@ commons: CommonQueryParams = Depends() 아래에 같은 예제가 있습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` + +//// ...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. -!!! tip "팁" - 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. +/// tip | "팁" + +만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. + +이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. - 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. +/// diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 92b2c7d1c..bc8af488d 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,40 +14,55 @@ `Depends()`로 된 `list`이어야합니다: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 Annotated가 없는 경우" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// 이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. -!!! tip "팁" - 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. +/// tip | "팁" + +일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. - *경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. +*경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. - 또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. +또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. -!!! info "정보" - 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. +/// - 그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. +/// info | "정보" + +이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. + +그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. + +/// ## 의존성 오류와 값 반환하기 @@ -57,51 +72,69 @@ (헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 -=== "Python 3.8 Annotated가 없는 경우" +/// tip | "팁" - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### 오류 발생시키기 다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 Annotated가 없는 경우 - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip | "팁" -=== "Python 3.8 Annotated가 없는 경우" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### 값 반환하기 @@ -109,26 +142,35 @@ 그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 -=== "Python 3.8+" +/// tip | "팁" - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8 Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## *경로 작동* 모음에 대한 의존성 diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index 930f6e678..2ce2cf4f2 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ 그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 Annotated가 없는 경우" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial012.py!} +``` + +//// 그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index d06864ab8..361989e2b 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -31,41 +31,57 @@ *경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.10+ Annotated가 없는 경우 -=== "Python 3.10+ Annotated가 없는 경우" +/// tip | "팁" - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ Annotated가 없는 경우" +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// 이게 다입니다. @@ -85,90 +101,125 @@ 그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. -!!! info "정보" - FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. +/// info | "정보" + +FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. - 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. +옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. - `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요. +`Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요. + +/// ### `Depends` 불러오기 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ Annotated가 없는 경우 - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip | "팁" -=== "Python 3.8+" +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### "의존자"에 의존성 명시하기 *경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. @@ -180,8 +231,11 @@ 그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다. -!!! tip "팁" - 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. +/// tip | "팁" + +여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. + +/// 새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다: @@ -202,10 +256,13 @@ common_parameters --> read_users 이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다. -!!! check "확인" - 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. +/// check | "확인" + +특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. + +단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. - 단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. +/// ## `Annotated`인 의존성 공유하기 @@ -219,28 +276,37 @@ commons: Annotated[dict, Depends(common_parameters)] 하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip | "팁" -!!! tip "팁" - 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. +이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. - 하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 +하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 + +/// 이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다. @@ -256,8 +322,11 @@ commons: Annotated[dict, Depends(common_parameters)] 아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다. -!!! note "참고" - 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. +/// note | "참고" + +잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. + +/// ## OpenAPI와 통합 diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 8b5fdb8b7..b8e87449c 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -30,5 +30,8 @@ Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다. -!!! note "참고" - 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. +/// note | "참고" + +실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. + +/// diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md index 673cf5b73..df3c7a06e 100644 --- a/docs/ko/docs/tutorial/extra-data-types.md +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ 위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// 함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index bdec3a377..52e53fd89 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note "참고" - `uvicorn main:app` 명령은 다음을 의미합니다: +/// note | "참고" - * `main`: 파일 `main.py` (파이썬 "모듈"). - * `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. - * `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. +`uvicorn main:app` 명령은 다음을 의미합니다: + +* `main`: 파일 `main.py` (파이썬 "모듈"). +* `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. +* `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. + +/// 출력되는 줄들 중에는 아래와 같은 내용이 있습니다: @@ -136,10 +139,13 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. -!!! note "기술 세부사항" - `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. +/// note | "기술 세부사항" + +`FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. - `FastAPI`로 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>의 모든 기능을 사용할 수 있습니다. +`FastAPI`로 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>의 모든 기능을 사용할 수 있습니다. + +/// ### 2 단계: `FastAPI` "인스턴스" 생성 @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "정보" - "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. +/// info | "정보" + +"경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. + +/// API를 설계할 때 "경로"는 "관심사"와 "리소스"를 분리하기 위한 주요한 방법입니다. @@ -250,16 +259,19 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * 경로 `/` * <abbr title="HTTP GET 메소드"><code>get</code> 작동</abbr> 사용 -!!! info "`@decorator` 정보" - 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. +/// info | "`@decorator` 정보" - 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. +이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. - "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. +마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. - 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. +"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. - 이것이 "**경로 작동 데코레이터**"입니다. +우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. + +이것이 "**경로 작동 데코레이터**"입니다. + +/// 다른 작동도 사용할 수 있습니다: @@ -274,14 +286,17 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * `@app.patch()` * `@app.trace()` -!!! tip "팁" - 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. +/// tip | "팁" + +각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. - **FastAPI**는 특정 의미를 강제하지 않습니다. +**FastAPI**는 특정 의미를 강제하지 않습니다. - 여기서 정보는 지침서일뿐 강제사항이 아닙니다. +여기서 정보는 지침서일뿐 강제사항이 아닙니다. - 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. +예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. + +/// ### 4 단계: **경로 작동 함수** 정의 @@ -309,8 +324,11 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "참고" - 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. +/// note | "참고" + +차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. + +/// ### 5 단계: 콘텐츠 반환 diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 484554e97..d403b9175 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -20,13 +20,19 @@ {!../../../docs_src/header_params/tutorial001.py!} ``` -!!! note "기술 세부사항" - `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. +/// note | "기술 세부사항" - `Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. +`Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. -!!! info "정보" - 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. +`Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. + +/// + +/// info | "정보" + +헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. + +/// ## 자동 변환 @@ -48,8 +54,11 @@ {!../../../docs_src/header_params/tutorial002.py!} ``` -!!! warning "경고" - `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. +/// warning | "경고" + +`convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. + +/// ## 중복 헤더 diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index 94d6dfb92..d00a942f0 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -53,22 +53,25 @@ $ pip install "fastapi[all]" ...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다. -!!! note "참고" - 부분적으로 설치할 수도 있습니다. +/// note | "참고" - 애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: +부분적으로 설치할 수도 있습니다. - ``` - pip install fastapi - ``` +애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: - 추가로 서버 역할을 하는 `uvicorn`을 설치합니다: +``` +pip install fastapi +``` + +추가로 서버 역할을 하는 `uvicorn`을 설치합니다: + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +사용하려는 각 선택적인 의존성에 대해서도 동일합니다. - 사용하려는 각 선택적인 의존성에 대해서도 동일합니다. +/// ## 고급 사용자 안내서 diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index f35b446a6..84f67bd26 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다. * **응답**를 반환합니다. -!!! note "기술 세부사항" - 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. +/// note | "기술 세부사항" - 만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. +만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. + +만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. + +/// ## 미들웨어 만들기 @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "팁" - 사용자 정의 헤더는 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-' 접두사를 사용</a>하여 추가할 수 있습니다. +/// tip | "팁" + +사용자 정의 헤더는 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-' 접두사를 사용</a>하여 추가할 수 있습니다. + +그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette CORS 문서</a>에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. + +/// + +/// note | "기술적 세부사항" - 그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette CORS 문서</a>에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. +`from starlette.requests import request`를 사용할 수도 있습니다. -!!! note "기술적 세부사항" - `from starlette.requests import request`를 사용할 수도 있습니다. +**FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. - **FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. +/// ### `response`의 전과 후 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index 411c43493..b6608a14d 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ *경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다. -!!! warning "경고" - 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. +/// warning | "경고" + +아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. + +/// ## 응답 상태 코드 @@ -19,10 +22,13 @@ 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. -!!! note "기술적 세부사항" - 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. +/// note | "기술적 세부사항" + +다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. + +**FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. - **FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. +/// ## 태그 @@ -66,13 +72,19 @@ {!../../../docs_src/path_operation_configuration/tutorial005.py!} ``` -!!! info "정보" - `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. +/// info | "정보" + +`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. + +/// + +/// check | "확인" + +OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. -!!! check "확인" - OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. +따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. - 따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. +/// <img src="/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index cadf543fc..6d3215c24 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -20,12 +20,15 @@ {!../../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` -!!! note "참고" - 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. +/// note | "참고" - 즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. +경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. - 그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. +즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. + +그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. + +/// ## 필요한 경우 매개변수 정렬하기 @@ -105,18 +108,24 @@ * `lt`: 작거나(`l`ess `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -!!! info "정보" - `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. +/// info | "정보" + +`Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. + +그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. + +/// + +/// note | "기술 세부사항" - 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. +`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. -!!! note "기술 세부사항" - `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. +호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. - 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. +즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. - 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. +편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. - 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. +이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. - 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. +/// diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index a75c3cc8c..67a2d899d 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ 위의 예시에서, `item_id`는 `int`로 선언되었습니다. -!!! check "확인" - 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. +/// check | "확인" + +이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. + +/// ## 데이터 <abbr title="다음으로도 알려져 있습니다: 직렬화, 파싱, 마샬링">변환</abbr> @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check "확인" - 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. +/// check | "확인" + +함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. + +즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 <abbr title="HTTP 요청에서 전달되는 문자열을 파이썬 데이터로 변환">"파싱"</abbr>합니다. - 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 <abbr title="HTTP 요청에서 전달되는 문자열을 파이썬 데이터로 변환">"파싱"</abbr>합니다. +/// ## 데이터 검증 @@ -63,12 +69,15 @@ `int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! check "확인" - 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. +/// check | "확인" - 오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. +즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. - 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. +오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. + +이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. + +/// ## 문서화 @@ -76,10 +85,13 @@ <img src="/img/tutorial/path-params/image01.png"> -!!! check "확인" - 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. +/// check | "확인" + +그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. + +경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. - 경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. +/// ## 표준 기반의 이점, 대체 문서 @@ -131,11 +143,17 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "정보" - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">열거형(또는 enums)</a>은 파이썬 버전 3.4 이후로 사용 가능합니다. +/// info | "정보" -!!! tip "팁" - 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 <abbr title="기술적으로 정확히는 딥 러닝 모델 구조">모델</abbr>들의 이름입니다. +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">열거형(또는 enums)</a>은 파이썬 버전 3.4 이후로 사용 가능합니다. + +/// + +/// tip | "팁" + +혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 <abbr title="기술적으로 정확히는 딥 러닝 모델 구조">모델</abbr>들의 이름입니다. + +/// ### *경로 매개변수* 선언 @@ -171,8 +189,11 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "팁" - `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. +/// tip | "팁" + +`ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. + +/// #### *열거형 멤버* 반환 @@ -225,10 +246,13 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "팁" - 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. +/// tip | "팁" + +매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. + +이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. - 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index 2e6396ccc..11193950b 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,13 @@ 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. -!!! note "참고" - FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. +/// note | "참고" - `Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. +FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. + +`Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. + +/// ## 추가 검증 @@ -51,22 +54,25 @@ q: Optional[str] = None 하지만 명시적으로 쿼리 매개변수를 선언합니다. -!!! info "정보" - FastAPI는 다음 부분에 관심이 있습니다: +/// info | "정보" - ```Python - = None - ``` +FastAPI는 다음 부분에 관심이 있습니다: - 또는: +```Python += None +``` - ```Python - = Query(None) - ``` +또는: - 그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. +```Python += Query(None) +``` + +그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. - `Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. +`Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. + +/// 또한 `Query`로 더 많은 매개변수를 전달할 수 있습니다. 지금의 경우 문자열에 적용되는 `max_length` 매개변수입니다: @@ -112,8 +118,11 @@ q: str = Query(None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "참고" - 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. +/// note | "참고" + +기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. + +/// ## 필수로 만들기 @@ -141,8 +150,11 @@ q: Optional[str] = Query(None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "정보" - 이전에 `...`를 본적이 없다면: 특별한 단일값으로, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">파이썬의 일부이며 "Ellipsis"라 부릅니다</a>. +/// info | "정보" + +이전에 `...`를 본적이 없다면: 특별한 단일값으로, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">파이썬의 일부이며 "Ellipsis"라 부릅니다</a>. + +/// 이렇게 하면 **FastAPI**가 이 매개변수는 필수임을 알 수 있습니다. @@ -175,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "팁" - 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. +/// tip | "팁" + +위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. + +/// 대화형 API 문서는 여러 값을 허용하도록 수정 됩니다: @@ -215,10 +230,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "참고" - 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. +/// note | "참고" - 예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. +이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. + +예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. + +/// ## 더 많은 메타데이터 선언 @@ -226,10 +244,13 @@ http://localhost:8000/items/ 해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다. -!!! note "참고" - 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. +/// note | "참고" + +도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. + +일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. - 일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. +/// `title`을 추가할 수 있습니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index 43a6c1a36..e71444c18 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -69,13 +69,19 @@ http://127.0.0.1:8000/items/?skip=20 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. -!!! check "확인" - **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. +/// check | "확인" -!!! note "참고" - FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. +**FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. - `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. +/// + +/// note | "참고" + +FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. + +`Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. + +/// ## 쿼리 매개변수 형변환 @@ -194,5 +200,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, 기본값이 `0`인 `int`. * `limit`, 선택적인 `int`. -!!! tip "팁" - [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. +/// tip | "팁" + +[경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. + +/// diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index 468c46283..b7781ef5e 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -2,12 +2,15 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. -!!! info "정보" - 업로드된 파일을 전달받기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. +/// info | "정보" - 예시) `pip install python-multipart`. +업로드된 파일을 전달받기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. - 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. +예시) `pip install python-multipart`. + +업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. + +/// ## `File` 임포트 @@ -25,13 +28,19 @@ {!../../../docs_src/request_files/tutorial001.py!} ``` -!!! info "정보" - `File` 은 `Form` 으로부터 직접 상속된 클래스입니다. +/// info | "정보" + +`File` 은 `Form` 으로부터 직접 상속된 클래스입니다. + +하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. + +/// - 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. +/// tip | "팁" -!!! tip "팁" - File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. +File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. + +/// 파일들은 "폼 데이터"의 형태로 업로드 됩니다. @@ -89,11 +98,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 기술적 세부사항" - `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. +/// note | "`async` 기술적 세부사항" + +`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. + +/// + +/// note | "Starlette 기술적 세부사항" -!!! note "Starlette 기술적 세부사항" - **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. +**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. + +/// ## "폼 데이터"란 @@ -101,17 +116,23 @@ HTML의 폼들(`<form></form>`)이 서버에 데이터를 전송하는 방식은 **FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다. -!!! note "기술적 세부사항" - 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. +/// note | "기술적 세부사항" + +폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. + +하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. + +인코딩과 폼 필드에 대해 더 알고싶다면, <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><code>POST</code>에 관한<abbr title="Mozilla Developer Network">MDN</abbr>웹 문서</a> 를 참고하기 바랍니다,. + +/// - 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. +/// warning | "경고" - 인코딩과 폼 필드에 대해 더 알고싶다면, <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><code>POST</code>에 관한<abbr title="Mozilla Developer Network">MDN</abbr>웹 문서</a> 를 참고하기 바랍니다,. +다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. -!!! warning "경고" - 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 다중 파일 업로드 @@ -127,17 +148,23 @@ HTML의 폼들(`<form></form>`)이 서버에 데이터를 전송하는 방식은 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. -!!! note "참고" - 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, <a href="https://github.com/swagger-api/swagger-ui/issues/4276" class="external-link" target="_blank">#4276</a>과 <a href="https://github.com/swagger-api/swagger-ui/issues/3641" class="external-link" target="_blank">#3641</a>을 참고하세요. +/// note | "참고" + +2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, <a href="https://github.com/swagger-api/swagger-ui/issues/4276" class="external-link" target="_blank">#4276</a>과 <a href="https://github.com/swagger-api/swagger-ui/issues/3641" class="external-link" target="_blank">#3641</a>을 참고하세요. + +그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. + +따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. + +/// - 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. +/// note | "기술적 세부사항" - 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. +`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. -!!! note "기술적 세부사항" - `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index bd5f41918..0867414ea 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -2,10 +2,13 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. -!!! info "정보" - 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. +/// info | "정보" - 예 ) `pip install python-multipart`. +파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다. + +예 ) `pip install python-multipart`. + +/// ## `File` 및 `Form` 업로드 @@ -25,10 +28,13 @@ 어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다. -!!! warning "경고" - 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +/// warning | "경고" + +다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. + +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index feff88a42..fc74a60b3 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -12,8 +12,11 @@ {!../../../docs_src/response_model/tutorial001.py!} ``` -!!! note "참고" - `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. +/// note | "참고" + +`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. + +/// Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다. @@ -28,8 +31,11 @@ FastAPI는 이 `response_model`를 사용하여: * 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다. -!!! note "기술 세부사항" - 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 +/// note | "기술 세부사항" + +응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 + +/// ## 동일한 입력 데이터 반환 @@ -51,8 +57,11 @@ FastAPI는 이 `response_model`를 사용하여: 그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다. -!!! danger "위험" - 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. +/// danger | "위험" + +절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. + +/// ## 출력 모델 추가 @@ -121,16 +130,22 @@ FastAPI는 이 `response_model`를 사용하여: } ``` -!!! info "정보" - FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank"> `exclude_unset` 매개변수</a>를 사용합니다. +/// info | "정보" + +FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank"> `exclude_unset` 매개변수</a>를 사용합니다. + +/// -!!! info "정보" - 아래 또한 사용할 수 있습니다: +/// info | "정보" - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +아래 또한 사용할 수 있습니다: - <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 문서</a>에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 문서</a>에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. + +/// #### 기본값이 있는 필드를 갖는 값의 데이터 @@ -166,10 +181,13 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: 따라서 JSON 스키마에 포함됩니다. -!!! tip "팁" - `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. +/// tip | "팁" + +`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. + +리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. - 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. +/// ### `response_model_include` 및 `response_model_exclude` @@ -179,21 +197,27 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: Pydantic 모델이 하나만 있고 출력에서 일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다. -!!! tip "팁" - 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. +/// tip | "팁" - 이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. +하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. - 비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. +이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. + +비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. + +/// ```Python hl_lines="31 37" {!../../../docs_src/response_model/tutorial005.py!} ``` -!!! tip "팁" - 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. +/// tip | "팁" + +문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. + +이는 `set(["name", "description"])`과 동일합니다. - 이는 `set(["name", "description"])`과 동일합니다. +/// #### `set` 대신 `list` 사용하기 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index e6eed5120..48cb49cbf 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "참고" - `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. +/// note | "참고" + +`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. + +/// `status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다. -!!! info "정보" - `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. +/// info | "정보" + +`status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. + +/// `status_code` 매개변수는: @@ -27,15 +33,21 @@ <img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image01.png"> -!!! note "참고" - 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). +/// note | "참고" + +어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). + +이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. - 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. +/// ## HTTP 상태 코드에 대하여 -!!! note "참고" - 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. +/// note | "참고" + +만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. + +/// HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다. @@ -54,8 +66,11 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. * `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. -!!! tip "팁" - 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP 상태 코드에 관한 문서</a> 를 확인하십시오. +/// tip | "팁" + +각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP 상태 코드에 관한 문서</a> 를 확인하십시오. + +/// ## 이름을 기억하는 쉬운 방법 @@ -79,10 +94,13 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 <img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image02.png"> -!!! note "기술적 세부사항" - `from starlette import status` 역시 사용할 수 있습니다. +/// note | "기술적 세부사항" + +`from starlette import status` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. +/// ## 기본값 변경 diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index 4e319e075..7b5ccdd32 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -8,71 +8,93 @@ 생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다. -=== "Python 3.10+ Pydantic v2" +//// tab | Python 3.10+ Pydantic v2 - ```Python hl_lines="13-24" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-24" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.10+ Pydantic v1" +//// - ```Python hl_lines="13-23" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} - ``` +//// tab | Python 3.10+ Pydantic v1 -=== "Python 3.8+ Pydantic v2" +```Python hl_lines="13-23" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +``` - ```Python hl_lines="15-26" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// -=== "Python 3.8+ Pydantic v1" +//// tab | Python 3.8+ Pydantic v2 - ```Python hl_lines="15-25" - {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} - ``` +```Python hl_lines="15-26" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// + +//// tab | Python 3.8+ Pydantic v1 + +```Python hl_lines="15-25" +{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +``` + +//// 추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다. -=== "Pydantic v2" +//// tab | Pydantic v2 + +Pydantic 버전 2에서 <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic 공식 문서: Model Config</a>에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. + +`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. - Pydantic 버전 2에서 <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic 공식 문서: Model Config</a>에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. +//// - `"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. +//// tab | Pydantic v1 -=== "Pydantic v1" +Pydantic v1에서 <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic 공식 문서: Schema customization</a>에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. - Pydantic v1에서 <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic 공식 문서: Schema customization</a>에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. +`schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. - `schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. +//// -!!! tip "팁" - JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. +/// tip | "팁" - 예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. +JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. -!!! info "정보" - (FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. +예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. - 그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 +/// - 이 문서 끝에 더 많은 읽을거리가 있습니다. +/// info | "정보" + +(FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. + +그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 + +이 문서 끝에 더 많은 읽을거리가 있습니다. + +/// ## `Field` 추가 인자 Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// ## JSON Schema에서의 `examples` - OpenAPI @@ -92,41 +114,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` - ```Python hl_lines="23-30" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="23-30" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` - ```Python hl_lines="18-25" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="20-27" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="18-25" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="20-27" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### 문서 UI 예시 @@ -138,41 +176,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 물론 여러 `examples`를 넘길 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24-39" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` - ```Python hl_lines="24-39" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="19-34" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="19-34" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - ```Python hl_lines="21-36" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="21-36" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// 이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다. @@ -213,41 +267,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 이를 다음과 같이 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.10+ Annotated가 없는 경우 -=== "Python 3.8+" +/// tip | "팁" - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.10+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +``` - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.8+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial005.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +``` + +//// ### 문서 UI에서의 OpenAPI 예시 @@ -257,17 +327,23 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 ## 기술적 세부 사항 -!!! tip "팁" - 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. +/// tip | "팁" + +이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. + +세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. + +간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 - 세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. +/// - 간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 +/// warning | "경고" -!!! warning "경고" - 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. +표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. - 만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. +만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. + +/// OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다. @@ -285,8 +361,11 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 * `File()` * `Form()` -!!! info "정보" - 이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. +/// info | "정보" + +이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. + +/// ### JSON 스키마의 `examples` 필드 @@ -298,10 +377,13 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다. -!!! info "정보" - 더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). +/// info | "정보" + +더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). + +이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. - 이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. +/// ### Pydantic과 FastAPI `examples` diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index f4b6f9471..9bf3d4ee1 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -16,17 +16,21 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## `get_current_user` 의존성 생성하기 @@ -38,63 +42,81 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 유저 가져오기 `get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 현재 유저 주입하기 이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. 이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다. -!!! tip "팁" - 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. +/// tip | "팁" + +요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. + +여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. - 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. +/// -!!! check "확인" - 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. +/// check | "확인" - 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. +이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. + +해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. + +/// ## 다른 모델 @@ -128,17 +150,21 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 요약 diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index 1e33f5766..9593f96f5 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 * `instagram_basic`은 페이스북/인스타그램에서 사용합니다. * `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다. -!!! 정보 - OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. +/// 정보 - `:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다. +OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. - 이러한 세부 사항은 구현에 따라 다릅니다. +`:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다. - OAuth2의 경우 문자열일 뿐입니다. +이러한 세부 사항은 구현에 따라 다릅니다. + +OAuth2의 경우 문자열일 뿐입니다. + +/// ## `username`과 `password`를 가져오는 코드 @@ -49,17 +52,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "파이썬 3.10 이상" +//// - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// `OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: @@ -68,29 +75,38 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 * `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다. * `grant_type`(선택적으로 사용). -!!! 팁 - OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. +/// 팁 + +OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. - 사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다. +사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다. + +/// * `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다). * `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다). -!!! 정보 - `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. +/// 정보 + +`OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. - `OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다. +`OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다. - 그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다. +그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다. - 그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다. +그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다. + +/// ### 폼 데이터 사용하기 -!!! 팁 - 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. +/// 팁 + +종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. + +이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다. - 이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다. +/// 이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다. @@ -98,17 +114,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 오류의 경우 `HTTPException` 예외를 사용합니다: -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "파이썬 3.10 이상" +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// ### 패스워드 확인하기 @@ -134,17 +154,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다). -=== "P파이썬 3.7 이상" +//// tab | P파이썬 3.7 이상 + +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// #### `**user_dict`에 대해 @@ -162,8 +186,11 @@ UserInDB( ) ``` -!!! 정보 - `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. +/// 정보 + +`**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. + +/// ## 토큰 반환하기 @@ -175,31 +202,41 @@ UserInDB( 이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다. -!!! 팁 - 다음 장에서는 패스워드 해싱 및 <abbr title="JSON Web Tokens">JWT</abbr> 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. +/// 팁 + +다음 장에서는 패스워드 해싱 및 <abbr title="JSON Web Tokens">JWT</abbr> 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. + +하지만 지금은 필요한 세부 정보에 집중하겠습니다. + +/// + +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - 하지만 지금은 필요한 세부 정보에 집중하겠습니다. +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.7 이상" +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "파이썬 3.10 이상" +/// 팁 - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. -!!! 팁 - 사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. +이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다. - 이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다. +사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다. - 사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다. +나머지는 **FastAPI**가 처리합니다. - 나머지는 **FastAPI**가 처리합니다. +/// ## 의존성 업데이트하기 @@ -213,32 +250,39 @@ UserInDB( 따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="55-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "파이썬 3.10 이상" +/// 정보 - ```Python hl_lines="55-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. -!!! 정보 - 여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. +모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다. - 모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다. +베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다. - 베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다. +실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다. - 실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다. +그러나 여기에서는 사양을 준수하도록 제공됩니다. - 그러나 여기에서는 사양을 준수하도록 제공됩니다. +또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다. - 또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다. +그것이 표준의 이점입니다 ... - 그것이 표준의 이점입니다 ... +/// ## 확인하기 diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index fe1aa4e5e..360aaaa6b 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "기술적 세부사항" - `from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. +/// note | "기술적 세부사항" - **FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. +`from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. + +**FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. + +/// ### "마운팅" 이란 diff --git a/docs/missing-translation.md b/docs/missing-translation.md index 32b6016f9..c2882e90e 100644 --- a/docs/missing-translation.md +++ b/docs/missing-translation.md @@ -1,4 +1,7 @@ -!!! warning - The current page still doesn't have a translation for this language. +/// warning - But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. +The current page still doesn't have a translation for this language. + +But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. + +/// diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index a6435977c..80d3bdece 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` oznacza: +/// info - Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` oznacza: + +Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Wsparcie edytora diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index 00c99edfa..4daad5e90 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -170,12 +170,15 @@ A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sa * Następnie dodaj **komentarz** z informacją o tym, że sprawdziłeś kod, dzięki temu będę miał pewność, że faktycznie go sprawdziłeś. -!!! info - Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. +/// info - Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 +Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. - Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 +Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 + +Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 + +/// * Jeśli PR można uprościć w jakiś sposób, możesz o to poprosić, ale nie ma potrzeby być zbyt wybrednym, może być wiele subiektywnych punktów widzenia (a ja też będę miał swój 🙈), więc lepiej żebyś skupił się na kluczowych rzeczach. @@ -226,10 +229,13 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz Dołącz do 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">serwera czatu na Discordzie</a> 👥 i spędzaj czas z innymi w społeczności FastAPI. -!!! tip "Wskazówka" - Jeśli masz pytania, zadaj je w <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. +/// tip | "Wskazówka" + +Jeśli masz pytania, zadaj je w <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Używaj czatu tylko do innych ogólnych rozmów. - Używaj czatu tylko do innych ogólnych rozmów. +/// ### Nie zadawaj pytań na czacie diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index ce71f8b83..8f1b9b922 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note - Polecenie `uvicorn main:app` odnosi się do: +/// note - * `main`: plik `main.py` ("moduł" Python). - * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. - * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. +Polecenie `uvicorn main:app` odnosi się do: + +* `main`: plik `main.py` ("moduł" Python). +* `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. +* `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. + +/// Na wyjściu znajduje się linia z czymś w rodzaju: @@ -136,11 +139,13 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. -!!! note "Szczegóły techniczne" - `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. +/// note | "Szczegóły techniczne" + +`FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. - Oznacza to, że możesz korzystać ze wszystkich funkcjonalności <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> również w `FastAPI`. +Oznacza to, że możesz korzystać ze wszystkich funkcjonalności <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> również w `FastAPI`. +/// ### Krok 2: utwórz instancję `FastAPI` @@ -200,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. +/// info + +"Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. + +/// Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”. @@ -251,16 +259,19 @@ Będziemy je również nazywali "**operacjami**". * ścieżki `/` * używając <abbr title="metoda HTTP GET">operacji <code>get</code></abbr> -!!! info "`@decorator` Info" - Składnia `@something` jest w Pythonie nazywana "dekoratorem". +/// info | "`@decorator` Info" + +Składnia `@something` jest w Pythonie nazywana "dekoratorem". - Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). +Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). - "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. +"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. - W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`. +W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`. - Jest to "**dekorator operacji na ścieżce**". +Jest to "**dekorator operacji na ścieżce**". + +/// Możesz również użyć innej operacji: @@ -275,14 +286,17 @@ Oraz tych bardziej egzotycznych: * `@app.patch()` * `@app.trace()` -!!! tip - Możesz dowolnie używać każdej operacji (metody HTTP). +/// tip + +Możesz dowolnie używać każdej operacji (metody HTTP). + +**FastAPI** nie narzuca żadnego konkretnego znaczenia. - **FastAPI** nie narzuca żadnego konkretnego znaczenia. +Informacje tutaj są przedstawione jako wskazówka, a nie wymóg. - Informacje tutaj są przedstawione jako wskazówka, a nie wymóg. +Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`. - Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`. +/// ### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę** @@ -310,8 +324,11 @@ Możesz również zdefiniować to jako normalną funkcję zamiast `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Krok 5: zwróć zawartość diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md index f8c5c6022..66f7c6d62 100644 --- a/docs/pl/docs/tutorial/index.md +++ b/docs/pl/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...wliczając w to `uvicorn`, który będzie służył jako serwer wykonujacy Twój kod. -!!! note - Możesz również wykonać instalację "krok po kroku". +/// note - Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: +Możesz również wykonać instalację "krok po kroku". - ``` - pip install fastapi - ``` +Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: - Zainstaluj też `uvicorn`, który będzie służył jako serwer: +``` +pip install fastapi +``` + +Zainstaluj też `uvicorn`, który będzie służył jako serwer: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. - Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. +/// ## Zaawansowany poradnik diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md index 7c7d22611..c27301b61 100644 --- a/docs/pt/docs/advanced/additional-responses.md +++ b/docs/pt/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Retornos Adicionais no OpenAPI -!!! warning "Aviso" - Este é um tema bem avançado. +/// warning | "Aviso" - Se você está começando com o **FastAPI**, provavelmente você não precisa disso. +Este é um tema bem avançado. + +Se você está começando com o **FastAPI**, provavelmente você não precisa disso. + +/// Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc. @@ -27,20 +30,26 @@ Por exemplo, para declarar um outro retorno com o status code `404` e um modelo {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note "Nota" - Lembre-se que você deve retornar o `JSONResponse` diretamente. +/// note | "Nota" + +Lembre-se que você deve retornar o `JSONResponse` diretamente. + +/// + +/// info | "Informação" -!!! info "Informação" - A chave `model` não é parte do OpenAPI. +A chave `model` não é parte do OpenAPI. - O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto. +O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto. - O local correto é: +O local correto é: - * Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém: - * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo:: - * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto. - * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc. +* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém: + * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo:: + * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto. + * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc. + +/// O retorno gerado no OpenAI para esta *operação de caminho* será: @@ -172,13 +181,19 @@ Por exemplo, você pode adicionar um media type adicional de `image/png`, declar {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note "Nota" - Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. +/// note | "Nota" + +Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. + +/// + +/// info | "Informação" + +A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). -!!! info "Informação" - A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). +Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado. - Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado. +/// ## Combinando informações diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md index a7699b324..a0869f342 100644 --- a/docs/pt/docs/advanced/additional-status-codes.md +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -14,53 +14,75 @@ Mas você também deseja aceitar novos itens. E quando os itens não existiam, e Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip "Dica" - Faça uso da versão `Annotated` quando possível. +```Python hl_lines="4 26" +{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +``` - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip "Dica" - Faça uso da versão `Annotated` quando possível. +/// tip | "Dica" - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` +Faça uso da versão `Annotated` quando possível. -!!! warning "Aviso" - Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. +/// - Ele não será serializado com um modelo, etc. +```Python hl_lines="2 23" +{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` - Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`). +//// -!!! note "Detalhes técnicos" - Você também pode utilizar `from starlette.responses import JSONResponse`. +//// tab | Python 3.8+ non-Annotated - O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`. +/// tip | "Dica" + +Faça uso da versão `Annotated` quando possível. + +/// + +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning | "Aviso" + +Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. + +Ele não será serializado com um modelo, etc. + +Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`). + +/// + +/// note | "Detalhes técnicos" + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`. + +/// ## OpenAPI e documentação da API diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index 58887f9c8..5a7b921b2 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -18,26 +18,35 @@ Não propriamente a classe (que já é um chamável), mas a instância desta cla Para fazer isso, nós declaramos o método `__call__`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +Prefira utilizar a versão `Annotated` se possível. - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente. @@ -45,26 +54,35 @@ Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâm E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +Prefira utilizar a versão `Annotated` se possível. - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. @@ -72,26 +90,35 @@ Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós Nós poderíamos criar uma instância desta classe com: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. @@ -107,32 +134,44 @@ checker(q="somequery") ...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. -!!! tip "Dica" - Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. +Estes exemplos são intencionalmente simples, porém mostram como tudo funciona. - Estes exemplos são intencionalmente simples, porém mostram como tudo funciona. +Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira. - Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira. +Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos. - Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos. +/// diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index 4ccc0c452..ab5bfa648 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste dev {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip "Dica" - Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. +/// tip | "Dica" + +Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. + +/// Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. @@ -81,15 +84,24 @@ response = client.get('/') ...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`. -!!! tip "Dica" - Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. +/// tip | "Dica" + +Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. + +/// -!!! warning "Aviso" - Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. +/// 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 <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>. + +/// ## Outras Chamadas de Funções Assíncronas Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código. -!!! tip "Dica" - Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MotorClient do MongoDB</a>) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. +/// tip | "Dica" + +Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MotorClient do MongoDB</a>) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. + +/// diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md index 8ac9102a3..2dfc5ca25 100644 --- a/docs/pt/docs/advanced/behind-a-proxy.md +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -43,8 +43,11 @@ browser --> proxy proxy --> server ``` -!!! tip "Dica" - O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. +/// tip | "Dica" + +O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. + +/// A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo: @@ -81,10 +84,13 @@ $ fastapi run main.py --root-path /api/v1 Se você usar Hypercorn, ele também tem a opção `--root-path`. -!!! note "Detalhes Técnicos" - A especificação ASGI define um `root_path` para esse caso de uso. +/// note | "Detalhes Técnicos" + +A especificação ASGI define um `root_path` para esse caso de uso. + +E a opção de linha de comando `--root-path` fornece esse `root_path`. - E a opção de linha de comando `--root-path` fornece esse `root_path`. +/// ### Verificando o `root_path` atual @@ -172,8 +178,11 @@ Então, crie um arquivo `traefik.toml` com: Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`. -!!! tip "Dica" - Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). +/// tip | "Dica" + +Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). + +/// Agora crie esse outro arquivo `routes.toml`: @@ -239,8 +248,11 @@ Agora, se você for ao URL com a porta para o Uvicorn: <a href="http://127.0.0.1 } ``` -!!! tip "Dica" - Perceba que, mesmo acessando em `http://127.0.0.1:8000/app`, ele mostra o `root_path` de `/api/v1`, retirado da opção `--root-path`. +/// tip | "Dica" + +Perceba que, mesmo acessando em `http://127.0.0.1:8000/app`, ele mostra o `root_path` de `/api/v1`, retirado da opção `--root-path`. + +/// E agora abra o URL com a porta para o Traefik, incluindo o prefixo de caminho: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>. @@ -283,8 +295,11 @@ Isso porque o FastAPI usa esse `root_path` para criar o `server` padrão no Open ## Servidores adicionais -!!! warning "Aviso" - Este é um caso de uso mais avançado. Sinta-se à vontade para pular. +/// warning | "Aviso" + +Este é um caso de uso mais avançado. Sinta-se à vontade para pular. + +/// Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`. @@ -323,15 +338,21 @@ Gerará um OpenAPI schema como: } ``` -!!! tip "Dica" - Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`. +/// tip | "Dica" + +Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`. + +/// Na interface de documentação em <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> parecerá: <img src="/img/tutorial/behind-a-proxy/image03.png"> -!!! tip "Dica" - A interface de documentação interagirá com o servidor que você selecionar. +/// tip | "Dica" + +A interface de documentação interagirá com o servidor que você selecionar. + +/// ### Desabilitar servidor automático de `root_path` diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 12aa93f29..5f722763e 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -39,10 +39,13 @@ Aqui nós estamos simulando a *inicialização* custosa do carregamento do model E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU. -!!! tip "Dica" - O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. +/// tip | "Dica" - Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 +O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. + +Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 + +/// ### Função _lifespan_ @@ -92,10 +95,13 @@ O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Context ## Eventos alternativos (deprecados) -!!! warning "Aviso" - A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. +/// warning | "Aviso" + +A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. - Você provavelmente pode pular essa parte. +Você provavelmente pode pular essa parte. + +/// Existe uma forma alternativa para definir a execução dessa lógica durante *inicialização* e durante *encerramento*. @@ -127,17 +133,23 @@ Para adicionar uma função que deve ser executada quando a aplicação estiver Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. -!!! info "Informação" - Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. +/// info | "Informação" + +Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. -!!! tip "Dica" - Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. +/// - Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. +/// tip | "Dica" - Mas `open()` não usa `async` e `await`. +Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. - Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. +Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. + +Mas `open()` não usa `async` e `await`. + +Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. + +/// ### `startup` e `shutdown` juntos @@ -153,10 +165,13 @@ Só um detalhe técnico para nerds curiosos. 🤓 Por baixo, na especificação técnica ASGI, essa é a parte do <a href="https://asgi.readthedocs.io/en/latest/specs/lifespan.html" class="external-link" target="_blank">Protocolo Lifespan</a>, e define eventos chamados `startup` e `shutdown`. -!!! info "Informação" - Você pode ler mais sobre o manipulador `lifespan` do Starlette na <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Documentação do Lifespan Starlette</a>. +/// info | "Informação" + +Você pode ler mais sobre o manipulador `lifespan` do Starlette na <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Documentação do Lifespan Starlette</a>. + +Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. - Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. +/// ## Sub Aplicações diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md index 413d8815f..2569fc914 100644 --- a/docs/pt/docs/advanced/index.md +++ b/docs/pt/docs/advanced/index.md @@ -6,10 +6,13 @@ O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_bla Na próxima seção você verá outras opções, configurações, e recursos adicionais. -!!! tip "Dica" - As próximas seções **não são necessáriamente "avançadas"** +/// tip | "Dica" - E é possível que para seu caso de uso, a solução esteja em uma delas. +As próximas seções **não são necessáriamente "avançadas"** + +E é possível que para seu caso de uso, a solução esteja em uma delas. + +/// ## Leia o Tutorial primeiro diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 932fe0d9a..2ccd0e819 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -22,8 +22,11 @@ Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webh Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles. -!!! info "Informação" - Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. +/// info | "Informação" + +Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. + +/// ## Uma aplicação com webhooks @@ -35,8 +38,11 @@ Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. -!!! info "Informação" - O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. +/// info | "Informação" + +O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. + +/// Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`. diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index f6962831f..db2b4c9cc 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -8,44 +8,51 @@ Por isso é comum prover essas configurações como variáveis de ambiente que s ## Variáveis de Ambiente -!!! dica - Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. +/// dica + +Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. + +/// Uma <a href="https://pt.wikipedia.org/wiki/Variável_de_ambiente" class="external-link" target="_blank">variável de ambiente</a> (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas). Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - // Você pode criar uma env var MY_NAME usando - $ export MY_NAME="Wade Wilson" +```console +// Você pode criar uma env var MY_NAME usando +$ export MY_NAME="Wade Wilson" - // E utilizá-la em outros programas, como - $ echo "Hello $MY_NAME" +// E utilizá-la em outros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +</div> - Hello Wade Wilson - ``` +//// - </div> +//// tab | Windows PowerShell -=== "Windows PowerShell" +<div class="termy"> - <div class="termy"> +```console +// Criando env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Criando env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Usando em outros programas, como +$ echo "Hello $Env:MY_NAME" - // Usando em outros programas, como - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +</div> - </div> +//// ### Lendo variáveis de ambiente com Python @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! dica - O segundo parâmetro em <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> é o valor padrão para o retorno. +/// dica + +O segundo parâmetro em <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> é o valor padrão para o retorno. - Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado. +Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado. + +/// E depois você pode executar esse arquivo: @@ -114,8 +124,11 @@ Hello World from Python </div> -!!! dica - Você pode ler mais sobre isso em: <a href="https://12factor.net/pt_br/config" class="external-link" target="_blank">The Twelve-Factor App: Configurações</a>. +/// dica + +Você pode ler mais sobre isso em: <a href="https://12factor.net/pt_br/config" class="external-link" target="_blank">The Twelve-Factor App: Configurações</a>. + +/// ### Tipagem e Validação @@ -151,8 +164,11 @@ $ pip install "fastapi[all]" </div> -!!! info - Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade. +/// info + +Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade. + +/// ### Criando o objeto `Settings` @@ -162,23 +178,33 @@ Os atributos da classe são declarados com anotações de tipo, e possíveis val Você pode utilizar todas as ferramentas e funcionalidades de validação que são utilizadas nos modelos do Pydantic, como tipos de dados diferentes e validações adicionei com `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +/// info + +Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001_pv1.py!} +``` -=== "Pydantic v1" +//// - !!! Info - Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. +/// dica - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. -!!! dica - Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. +/// Portanto, quando você cria uma instância da classe `Settings` (nesse caso, o objeto `settings`), o Pydantic lê as variáveis de ambiente sem diferenciar maiúsculas e minúsculas, por isso, uma variável maiúscula `APP_NAME` será usada para o atributo `app_name`. @@ -206,8 +232,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p </div> -!!! dica - Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. +/// dica + +Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. + +/// Assim, o atributo `admin_email` seria definido como `"deadpool@example.com"`. @@ -231,8 +260,11 @@ E utilizar essa configuração em `main.py`: {!../../../docs_src/settings/app01/main.py!} ``` -!!! dica - Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. +/// dica + +Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +/// ## Configurações em uma dependência @@ -254,54 +286,75 @@ Perceba que dessa vez não criamos uma instância padrão `settings = Settings() Agora criamos a dependência que retorna um novo objeto `config.Settings()`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// - !!! dica - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +/// dica -!!! dica - Vamos discutir sobre `@lru_cache` logo mais. +Utilize a versão com `Annotated` se possível. - Por enquanto, você pode considerar `get_settings()` como uma função normal. +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// + +/// dica + +Vamos discutir sobre `@lru_cache` logo mais. + +Por enquanto, você pode considerar `get_settings()` como uma função normal. + +/// E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// dica -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! dica - Utilize a versão com `Annotated` se possível. +/// - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// ### Configurações e testes @@ -321,15 +374,21 @@ Se você tiver muitas configurações que variem bastante, talvez em ambientes d Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv". -!!! dica - Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. +/// dica + +Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. - Mas um arquivo dotenv não precisa ter esse nome exato. +Mas um arquivo dotenv não precisa ter esse nome exato. + +/// Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>. -!!! dica - Para que isso funcione você precisa executar `pip install python-dotenv`. +/// dica + +Para que isso funcione você precisa executar `pip install python-dotenv`. + +/// ### O arquivo `.env` @@ -344,26 +403,39 @@ APP_NAME="ChimichangApp" E então adicionar o seguinte código em `config.py`: -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/settings/app03_an/config.py!} +``` - !!! dica - O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. +/// dica -=== "Pydantic v1" +O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +/// - !!! dica - A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. +//// -!!! info - Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`. +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// dica + +A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. + +/// + +//// + +/// info + +Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`. + +/// Aqui definimos a configuração `env_file` dentro da classe `Settings` do Pydantic, e definimos o valor como o nome do arquivo dotenv que queremos utilizar. @@ -390,26 +462,35 @@ Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +/// dica -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! dica - Utilize a versão com `Annotated` se possível. +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo. diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 3bada5e43..6d231b3c2 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -29,20 +29,27 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note - Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. +/// note - Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. +Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. +Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. -!!! tip "Dica" - Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. +/// +/// tip | "Dica" -!!! note "Detalhes Técnicos" - Você também poderia usar `from starlette.templating import Jinja2Templates`. +Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. - **FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. +/// + +/// note | "Detalhes Técnicos" + +Você também poderia usar `from starlette.templating import Jinja2Templates`. + +**FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. + +/// ## Escrevendo Templates diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index 0e79c4f77..d3a304fa7 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -30,11 +30,17 @@ Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite. Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**. -!!! note "Nota" - Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. +/// note | "Nota" -!!! check "**FastAPI** inspirado para" - Ter uma documentação automática da API em interface web. +Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. + +/// + +/// check | "**FastAPI** inspirado para" + +Ter uma documentação automática da API em interface web. + +/// ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> @@ -50,10 +56,13 @@ Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendid Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask. -!!! check "**FastAPI** inspirado para" - Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. +/// check | "**FastAPI** inspirado para" - Ser simples e com sistema de roteamento fácil de usar. +Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. + +Ser simples e com sistema de roteamento fácil de usar. + +/// ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> @@ -89,10 +98,13 @@ def read_url(): Veja as similaridades em `requests.get(...)` e `@app.get(...)`. -!!! check "**FastAPI** inspirado para" - * Ter uma API simples e intuitiva. - * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. - * Ter padrões sensíveis, mas customizações poderosas. +/// check | "**FastAPI** inspirado para" + +* Ter uma API simples e intuitiva. +* Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. +* Ter padrões sensíveis, mas customizações poderosas. + +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -106,15 +118,18 @@ Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAP Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI". -!!! check "**FastAPI** inspirado para" - Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. +/// check | "**FastAPI** inspirado para" + +Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. + +E integrar ferramentas de interface para usuários baseado nos padrões: - E integrar ferramentas de interface para usuários baseado nos padrões: +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> +Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). - Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). +/// ### Flask REST frameworks @@ -132,8 +147,11 @@ Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o <abbr title="definição de como os dados devem ser formados">_schema_</abbr> você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow. -!!! check "**FastAPI** inspirado para" - Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. +/// check | "**FastAPI** inspirado para" + +Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -145,11 +163,17 @@ Ele utiliza Marshmallow por baixo para validação de dados. E ele foi criado pe Ele é uma grande ferramenta e eu também a utilizei muito, antes de ter o **FastAPI**. -!!! info - Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. -!!! check "**FastAPI** inspirado para" - Ter validação automática de dados vindos de requisições. +/// + +/// check | "**FastAPI** inspirado para" + +Ter validação automática de dados vindos de requisições. + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -169,11 +193,17 @@ Mas então, nós temos novamente o problema de ter uma micro-sintaxe, dentro de O editor não poderá ajudar muito com isso. E se nós modificarmos os parâmetros dos _schemas_ do Marshmallow e esquecer de modificar também aquela _docstring_ YAML, o _schema_ gerado pode ficar obsoleto. -!!! info - APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// + +/// check | "**FastAPI** inspirado para" -!!! check "**FastAPI** inspirado para" - Dar suporte a padrões abertos para APIs, OpenAPI. +Dar suporte a padrões abertos para APIs, OpenAPI. + +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -195,11 +225,17 @@ Usando essa combinação levou a criação de vários geradores Flask _full-stac E esses mesmos geradores _full-stack_ foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// -!!! check "**FastAPI** inspirado para" - Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. +/// check | "**FastAPI** inspirado para" + +Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (and <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) @@ -215,24 +251,33 @@ Mas como os dados TypeScript não são preservados após a compilação para o J Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente. -!!! check "**FastAPI** inspirado para" - Usar tipos Python para ter um ótimo suporte do editor. +/// check | "**FastAPI** inspirado para" + +Usar tipos Python para ter um ótimo suporte do editor. - Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. +Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. + +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask. -!!! note "Detalhes técnicos" - Ele utiliza <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. +/// note | "Detalhes técnicos" + +Ele utiliza <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. + +Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. + +/// - Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. +/// check | "**FastAPI** inspirado para" -!!! check "**FastAPI** inspirado para" - Achar um jeito de ter uma performance insana. +Achar um jeito de ter uma performance insana. - É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). +É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -244,12 +289,15 @@ Ele é projetado para ter funções que recebem dois parâmetros, uma "requisiç Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros. -!!! check "**FastAPI** inspirado para" - Achar jeitos de conseguir melhor performance. +/// check | "**FastAPI** inspirado para" + +Achar jeitos de conseguir melhor performance. + +Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções. - Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções. +Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. - Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -267,10 +315,13 @@ O sistema de injeção de dependência exige pré-registro das dependências e a Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas. -!!! check "**FastAPI** inspirado para" - Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. +/// check | "**FastAPI** inspirado para" - Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). +Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. + +Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). + +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -286,15 +337,21 @@ Hug tinha um incomum, interessante recurso: usando o mesmo framework, é possív Como é baseado nos padrões anteriores de frameworks web síncronos (WSGI), ele não pode controlar _Websockets_ e outras coisas, embora ele ainda tenha uma alta performance também. -!!! info - Hug foi criado por Timothy Crosley, o mesmo criador do <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. +/// info + +Hug foi criado por Timothy Crosley, o mesmo criador do <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. + +/// + +/// check | "Idéias inspiradas para o **FastAPI**" + +Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. -!!! check "Idéias inspiradas para o **FastAPI**" - Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. +Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. - Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. +Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. - Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5) @@ -320,23 +377,29 @@ Ele não era mais um framework web API, como o criador precisava focar no Starle Agora APIStar é um conjunto de ferramentas para validar especificações OpenAPI, não um framework web. -!!! info - APIStar foi criado por Tom Christie. O mesmo cara que criou: +/// info - * Django REST Framework - * Starlette (no qual **FastAPI** é baseado) - * Uvicorn (usado por Starlette e **FastAPI**) +APIStar foi criado por Tom Christie. O mesmo cara que criou: -!!! check "**FastAPI** inspirado para" - Existir. +* Django REST Framework +* Starlette (no qual **FastAPI** é baseado) +* Uvicorn (usado por Starlette e **FastAPI**) - A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. +/// - E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. +/// check | "**FastAPI** inspirado para" - Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. +Existir. - Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. +A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. + +E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. + +Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. + +Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. + +/// ## Usados por **FastAPI** @@ -348,10 +411,13 @@ Isso faz dele extremamente intuitivo. Ele é comparável ao Marshmallow. Embora ele seja mais rápido que Marshmallow em testes de performance. E ele é baseado nos mesmos Python _type hints_, o suporte ao editor é ótimo. -!!! check "**FastAPI** usa isso para" - Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). +/// check | "**FastAPI** usa isso para" + +Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). + +**FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. - **FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -381,17 +447,23 @@ Mas ele não fornece validação de dados automática, serialização e document Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado em Python _type hints_ (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de _schema_ OpenAPI, etc. -!!! note "Detalhes Técnicos" - ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. +/// note | "Detalhes Técnicos" - No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. +ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. -!!! check "**FastAPI** usa isso para" - Controlar todas as partes web centrais. Adiciona recursos no topo. +No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. - A classe `FastAPI` em si herda `Starlette`. +/// - Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. +/// check | "**FastAPI** usa isso para" + +Controlar todas as partes web centrais. Adiciona recursos no topo. + +A classe `FastAPI` em si herda `Starlette`. + +Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -401,12 +473,15 @@ Ele não é um framework web, mas sim um servidor. Por exemplo, ele não fornece Ele é o servidor recomendado para Starlette e **FastAPI**. -!!! check "**FastAPI** recomenda isso para" - O principal servidor web para rodar aplicações **FastAPI**. +/// check | "**FastAPI** recomenda isso para" + +O principal servidor web para rodar aplicações **FastAPI**. + +Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. - Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. +Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. - Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. +/// ## Performance e velocidade diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md index 1ec8f07c6..0d6bdbf0e 100644 --- a/docs/pt/docs/async.md +++ b/docs/pt/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - Você só pode usar `await` dentro de funções criadas com `async def`. +/// note + +Você só pode usar `await` dentro de funções criadas com `async def`. + +/// --- @@ -356,12 +359,15 @@ Tudo isso é o que deixa o FastAPI poderoso (através do Starlette) e que o faz ## Detalhes muito técnicos -!!! warning - Você pode provavelmente pular isso. +/// warning + +Você pode provavelmente pular isso. + +Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. - Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. +Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. - Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. +/// ### Funções de operação de rota diff --git a/docs/pt/docs/contributing.md b/docs/pt/docs/contributing.md index 7d8d1fd5e..bb518a2fa 100644 --- a/docs/pt/docs/contributing.md +++ b/docs/pt/docs/contributing.md @@ -24,72 +24,85 @@ Isso criará o diretório `./env/` com os binários Python e então você será Ative o novo ambiente com: -=== "Linux, macOS" +//// tab | Linux, macOS - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +<div class="termy"> - </div> +```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +</div> - Ou se você usa Bash para Windows (por exemplo <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): +//// - <div class="termy"> +//// tab | Windows Bash - ```console - $ source ./env/Scripts/activate - ``` +Ou se você usa Bash para Windows (por exemplo <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): - </div> +<div class="termy"> + +```console +$ source ./env/Scripts/activate +``` + +</div> + +//// Para verificar se funcionou, use: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ Get-Command pip +<div class="termy"> - some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip - </div> +some/directory/fastapi/env/bin/pip +``` + +</div> + +//// Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉 -!!! tip - Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. +/// tip + +Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. - Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. +Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. + +/// ### pip @@ -153,8 +166,11 @@ A documentação usa <a href="https://www.mkdocs.org/" class="external-link" tar 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. +/// 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/`. @@ -239,10 +255,13 @@ Aqui estão os passos para ajudar com as traduções. * Verifique sempre os <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">_pull requests_ existentes</a> para a sua linguagem e faça revisões das alterações e aprove elas. -!!! tip - Você pode <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">adicionar comentários com sugestões de alterações</a> para _pull requests_ existentes. +/// tip + +Você pode <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">adicionar comentários com sugestões de alterações</a> para _pull requests_ existentes. + +Verifique as documentações sobre <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adicionar revisão ao _pull request_</a> para aprovação ou solicitação de alterações. - Verifique as documentações sobre <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adicionar revisão ao _pull request_</a> para aprovação ou solicitação de alterações. +/// * Verifique em <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">_issues_</a> para ver se existe alguém coordenando traduções para a sua linguagem. @@ -264,8 +283,11 @@ Vamos dizer que você queira traduzir uma página para uma linguagem que já ten No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`. -!!! tip - A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. +/// tip + +A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. + +/// Agora rode o _servidor ao vivo_ para as documentações em Espanhol: @@ -302,8 +324,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. +/// tip + +Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. + +/// * Agora abra o arquivo de configuração MkDocs para Inglês em: @@ -374,10 +399,13 @@ Updating en Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`. -!!! tip - Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. +/// tip + +Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. + +Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 - Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 +/// Inicie traduzindo a página principal, `docs/ht/index.md`. diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md index d25ea79fd..6874a2529 100644 --- a/docs/pt/docs/deployment.md +++ b/docs/pt/docs/deployment.md @@ -50,8 +50,11 @@ Seguindo as convenções do Versionamento Semântico, qualquer versão abaixo de FastAPI também segue a convenção que qualquer versão de _"PATCH"_ seja para ajustes de _bugs_ e mudanças que não quebrem a aplicação. -!!! tip - O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`. +/// tip + +O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`. + +/// Então, você poderia ser capaz de fixar para uma versão como: @@ -61,8 +64,11 @@ fastapi>=0.45.0,<0.46.0 Mudanças que quebram e novos recursos são adicionados em versões _"MINOR"_. -!!! tip - O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`. +/// tip + +O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`. + +/// ### Atualizando as versões FastAPI @@ -113,8 +119,11 @@ Essa imagem tem um mecanismo incluído de "auto-ajuste", para que você possa ap Mas você pode ainda mudar e atualizar todas as configurações com variáveis de ambiente ou arquivos de configuração. -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem do Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +/// tip + +Para ver todas as configurações e opções, vá para a página da imagem do Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +/// ### Crie um `Dockerfile` @@ -248,8 +257,11 @@ Você verá a documentação automática alternativa (fornecida por <a href="htt 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. +/// 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 <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>. @@ -329,61 +341,69 @@ Você pode fazer o _deploy_ do **FastAPI** diretamente sem o Docker também. Você apenas precisa instalar um servidor ASGI compatível como: -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, um servidor ASGI peso leve, construído sobre uvloop e httptools. +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, um servidor ASGI peso leve, construído sobre uvloop e httptools. - <div class="termy"> +<div class="termy"> + +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +</div> - ---> 100% - ``` +//// - </div> +//// tab | Hypercorn -=== "Hypercorn" +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2. - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2. +<div class="termy"> - <div class="termy"> +```console +$ pip install hypercorn - ```console - $ pip install hypercorn +---> 100% +``` - ---> 100% - ``` +</div> - </div> +...ou qualquer outro servidor ASGI. - ...ou qualquer outro servidor ASGI. +//// E rode sua applicação do mesmo modo que você tem feito nos tutoriais, mas sem a opção `--reload`, por exemplo: -=== "Uvicorn" +//// tab | Uvicorn - <div class="termy"> +<div class="termy"> - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - </div> +</div> + +//// -=== "Hypercorn" +//// tab | Hypercorn - <div class="termy"> +<div class="termy"> - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +```console +$ hypercorn main:app --bind 0.0.0.0:80 - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +</div> - </div> +//// Você deve querer configurar mais algumas ferramentas para ter certeza que ele seja reinicializado automaticamante se ele parar. diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index 9ab8d38f0..fa1a6b9c2 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -4,9 +4,11 @@ Ao fazer o deploy de aplicações FastAPI uma abordagem comum é construir uma * Usando contêineres Linux você tem diversas vantagens incluindo **segurança**, **replicabilidade**, **simplicidade**, entre outras. -!!! tip "Dica" - Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). +/// tip | "Dica" +Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). + +/// <details> <summary>Visualização do Dockerfile 👀</summary> @@ -131,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn </div> -!!! info - Há outros formatos e ferramentas para definir e instalar dependências de pacote. +/// info + +Há outros formatos e ferramentas para definir e instalar dependências de pacote. + +Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 - Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 +/// ### Criando o Código do **FastAPI** @@ -223,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Porque o programa será iniciado em `/code` e dentro dele está o diretório `./app` com seu código, o **Uvicorn** será capaz de ver e **importar** `app` de `app.main`. -!!! tip - Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 +/// tip + +Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 + +/// Agora você deve ter uma estrutura de diretório como: @@ -294,10 +302,13 @@ $ docker build -t myimage . </div> -!!! tip - Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. +/// tip - Nesse caso, é o mesmo diretório atual (`.`). +Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. + +Nesse caso, é o mesmo diretório atual (`.`). + +/// ### Inicie o contêiner Docker @@ -395,8 +406,11 @@ Se nos concentrarmos apenas na **imagem do contêiner** para um aplicativo FastA Isso poderia ser outro contêiner, por exemplo, com <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, lidando com **HTTPS** e aquisição **automática** de **certificados**. -!!! tip - Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. +/// tip + +Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. + +/// Alternativamente, o HTTPS poderia ser tratado por um provedor de nuvem como um de seus serviços (enquanto ainda executasse o aplicativo em um contêiner). @@ -424,8 +438,11 @@ Quando usando contêineres, normalmente você terá algum componente **escutando Como esse componente assumiria a **carga** de solicitações e distribuiria isso entre os trabalhadores de uma maneira (esperançosamente) **balanceada**, ele também é comumente chamado de **Balanceador de Carga**. -!!! tip - O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. +/// tip + +O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. + +/// E quando trabalhar com contêineres, o mesmo sistema que você usa para iniciar e gerenciá-los já terá ferramentas internas para transmitir a **comunicação de rede** (por exemplo, solicitações HTTP) do **balanceador de carga** (que também pode ser um **Proxy de Terminação TLS**) para o(s) contêiner(es) com seu aplicativo. @@ -504,8 +521,11 @@ Se você estiver usando contêineres (por exemplo, Docker, Kubernetes), existem Se você tiver **múltiplos contêineres**, provavelmente cada um executando um **único processo** (por exemplo, em um cluster do **Kubernetes**), então provavelmente você gostaria de ter um **contêiner separado** fazendo o trabalho dos **passos anteriores** em um único contêiner, executando um único processo, **antes** de executar os contêineres trabalhadores replicados. -!!! info - Se você estiver usando o Kubernetes, provavelmente será um <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>. +/// info + +Se você estiver usando o Kubernetes, provavelmente será um <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>. + +/// Se no seu caso de uso não houver problema em executar esses passos anteriores **em paralelo várias vezes** (por exemplo, se você não estiver executando migrações de banco de dados, mas apenas verificando se o banco de dados está pronto), então você também pode colocá-los em cada contêiner logo antes de iniciar o processo principal. @@ -521,8 +541,11 @@ Essa imagem seria útil principalmente nas situações descritas acima em: [Cont * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. -!!! warning - Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi). +/// warning + +Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi). + +/// Essa imagem tem um mecanismo de **auto-ajuste** incluído para definir o **número de processos trabalhadores** com base nos núcleos de CPU disponíveis. @@ -530,8 +553,11 @@ Isso tem **padrões sensíveis**, mas você ainda pode alterar e atualizar todas Há também suporte para executar <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**passos anteriores antes de iniciar**</a> com um script. -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +/// tip + +Para ver todas as configurações e opções, vá para a página da imagem Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +/// ### Número de Processos na Imagem Oficial do Docker @@ -660,8 +686,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Execute o comando `uvicorn`, informando-o para usar o objeto `app` importado de `app.main`. -!!! tip - Clique nos números das bolhas para ver o que cada linha faz. +/// tip + +Clique nos números das bolhas para ver o que cada linha faz. + +/// Um **estágio do Docker** é uma parte de um `Dockerfile` que funciona como uma **imagem temporária do contêiner** que só é usada para gerar alguns arquivos para serem usados posteriormente. diff --git a/docs/pt/docs/deployment/https.md b/docs/pt/docs/deployment/https.md index f85861e92..6ccc875fd 100644 --- a/docs/pt/docs/deployment/https.md +++ b/docs/pt/docs/deployment/https.md @@ -4,8 +4,11 @@ Mas é bem mais complexo do que isso. -!!! tip "Dica" - Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. +/// tip | "Dica" + +Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. + +/// Para aprender o básico de HTTPS de uma perspectiva do usuário, verifique <a href="https://howhttps.works/pt-br/" class="external-link" target="_blank">https://howhttps.works/pt-br/</a>. diff --git a/docs/pt/docs/deployment/versions.md b/docs/pt/docs/deployment/versions.md index 77d9bab69..79243a014 100644 --- a/docs/pt/docs/deployment/versions.md +++ b/docs/pt/docs/deployment/versions.md @@ -42,8 +42,11 @@ Seguindo as convenções de controle de versão semântica, qualquer versão aba FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas. -!!! tip "Dica" - O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. +/// tip | "Dica" + +O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. + +/// Logo, você deveria conseguir fixar a versão, como: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Mudanças significativas e novos recursos são adicionados em versões "MINOR". -!!! tip "Dica" - O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. +/// tip | "Dica" + +O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. + +/// ## Atualizando as versões do FastAPI diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md index a4832804d..622ad5ab6 100644 --- a/docs/pt/docs/external-links.md +++ b/docs/pt/docs/external-links.md @@ -6,8 +6,11 @@ Existem muitas postagens, artigos, ferramentas e projetos relacionados ao **Fast Aqui tem uma lista, incompleta, de algumas delas. -!!! tip "Dica" - Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um <a href="https://github.com/fastapi/fastapi/edit/master/docs/external-links.md" class="external-link" target="_blank">_Pull Request_ adicionando ele</a>. +/// tip | "Dica" + +Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um <a href="https://github.com/fastapi/fastapi/edit/master/docs/external-links.md" class="external-link" target="_blank">_Pull Request_ adicionando ele</a>. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/pt/docs/fastapi-cli.md b/docs/pt/docs/fastapi-cli.md index a4dfda660..829686631 100644 --- a/docs/pt/docs/fastapi-cli.md +++ b/docs/pt/docs/fastapi-cli.md @@ -80,5 +80,8 @@ Isso irá escutar no endereço de IP `0.0.0.0`, o que significa todos os endere Em muitos casos você pode ter (e deveria ter) um "proxy de saída" tratando HTTPS no topo, isso dependerá de como você fará o deploy da sua aplicação, seu provedor pode fazer isso pra você ou talvez seja necessário fazer você mesmo. -!!! tip - Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}. +/// tip + +Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index 64efeeae1..a90a8094b 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` quer dizer: +/// info - Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` quer dizer: + +Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Suporte de editores diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index 0deef15b5..61eeac0dc 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -109,10 +109,13 @@ Assim podendo tentar ajudar a resolver essas questões. Entre no 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">server de conversa do Discord</a> 👥 e conheça novas pessoas da comunidade do FastAPI. -!!! tip "Dica" - Para perguntas, pergunte nas <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. +/// tip | "Dica" - Use o chat apenas para outro tipo de assunto. +Para perguntas, pergunte nas <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. + +Use o chat apenas para outro tipo de assunto. + +/// ### Não faça perguntas no chat diff --git a/docs/pt/docs/how-to/index.md b/docs/pt/docs/how-to/index.md index 664e89144..6747b01c7 100644 --- a/docs/pt/docs/how-to/index.md +++ b/docs/pt/docs/how-to/index.md @@ -6,6 +6,8 @@ A maioria dessas ideias será mais ou menos **independente**, e na maioria dos c Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo. -!!! tip +/// tip - Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso. +Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso. + +/// diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 52b2dad8e..86630cd2a 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -12,9 +12,11 @@ O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e ben Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles. -!!! note "Nota" - Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. +/// note | "Nota" +Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. + +/// ## Motivação @@ -173,10 +175,13 @@ Como a lista é um tipo que contém alguns tipos internos, você os coloca entre {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Dica" - Esses tipos internos entre colchetes são chamados de "parâmetros de tipo". +/// tip | "Dica" + +Esses tipos internos entre colchetes são chamados de "parâmetros de tipo". - Nesse caso, `str` é o parâmetro de tipo passado para `List`. +Nesse caso, `str` é o parâmetro de tipo passado para `List`. + +/// Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". @@ -282,8 +287,11 @@ Retirado dos documentos oficiais dos Pydantic: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info "Informação" - Para saber mais sobre o <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"> Pydantic, verifique seus documentos </a>. +/// info | "Informação" + +Para saber mais sobre o <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"> Pydantic, verifique seus documentos </a>. + +/// **FastAPI** é todo baseado em Pydantic. @@ -311,5 +319,8 @@ Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em aç O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você. -!!! info "Informação" - Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é <a href = "https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class = "external-link "target =" _ blank "> a "cheat sheet" do `mypy` </a>. +/// info | "Informação" + +Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é <a href = "https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class = "external-link "target =" _ blank "> a "cheat sheet" do `mypy` </a>. + +/// diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index 8f3313ae9..cce37cd55 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -10,8 +10,11 @@ Primeiro, você tem que importá-lo: {!../../../docs_src/body_fields/tutorial001.py!} ``` -!!! warning "Aviso" - Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). +/// warning | "Aviso" + +Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). + +/// ## Declare atributos do modelo @@ -23,17 +26,23 @@ Você pode então utilizar `Field` com atributos do modelo: `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. -!!! note "Detalhes técnicos" - Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. +/// note | "Detalhes técnicos" + +Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. + +E `Field` do Pydantic retorna uma instância de `FieldInfo` também. + +`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. + +Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. - E `Field` do Pydantic retorna uma instância de `FieldInfo` também. +/// - `Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. +/// tip | "Dica" - Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. +Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. -!!! tip "Dica" - Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. +/// ## Adicione informações extras diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 7d0435a6b..d36dd60b3 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -8,20 +8,27 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +//// -!!! note "Nota" - Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. +/// note | "Nota" + +Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. + +/// ## Múltiplos parâmetros de corpo @@ -38,17 +45,21 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic). @@ -69,9 +80,11 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo } ``` -!!! note "Nota" - Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. +/// note | "Nota" +Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. + +/// O **FastAPI** fará a conversão automática a partir da requisição, assim esse parâmetro `item` receberá seu respectivo conteúdo e o mesmo ocorrerá com `user`. @@ -87,17 +100,21 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` -=== "Python 3.10+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.10+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// Neste caso, o **FastAPI** esperará um corpo como: @@ -137,20 +154,27 @@ q: str | None = None Por exemplo: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="26" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +//// -=== "Python 3.8+" +/// info | "Informação" - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. -!!! info "Informação" - `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. +/// ## Declare um único parâmetro de corpo indicando sua chave @@ -166,17 +190,21 @@ item: Item = Body(embed=True) como em: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` + +//// - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// Neste caso o **FastAPI** esperará um corpo como: diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index c9d0b8bb6..7d933b27f 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -165,8 +165,11 @@ Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual: } ``` -!!! info "informação" - Note como o campo `images` agora tem uma lista de objetos de image. +/// info | "informação" + +Note como o campo `images` agora tem uma lista de objetos de image. + +/// ## Modelos profundamente aninhados @@ -176,8 +179,11 @@ Você pode definir modelos profundamente aninhados de forma arbitrária: {!../../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "informação" - Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s +/// info | "informação" + +Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s + +/// ## Corpos de listas puras @@ -226,14 +232,17 @@ Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com va {!../../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "Dica" - Leve em condideração que o JSON só suporta `str` como chaves. +/// tip | "Dica" + +Leve em condideração que o JSON só suporta `str` como chaves. + +Mas o Pydantic tem conversão automática de dados. - Mas o Pydantic tem conversão automática de dados. +Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los. - Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los. +E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`. - E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`. +/// ## Recapitulação diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 713bea2d1..f67687fb5 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -8,12 +8,15 @@ Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não Para declarar um corpo da **requisição**, você utiliza os modelos do <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> com todos os seus poderes e benefícios. -!!! info "Informação" - Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. +/// info | "Informação" - Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. +Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. - Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. +Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. + +Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. + +/// ## Importe o `BaseModel` do Pydantic @@ -110,16 +113,19 @@ Mas você terá o mesmo suporte do editor no <a href="https://www.jetbrains.com/ <img src="/img/tutorial/body/image05.png"> -!!! tip "Dica" - Se você utiliza o <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> como editor, você pode utilizar o <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Plugin do Pydantic para o PyCharm </a>. +/// tip | "Dica" + +Se você utiliza o <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> como editor, você pode utilizar o <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Plugin do Pydantic para o PyCharm </a>. - Melhora o suporte do editor para seus modelos Pydantic com:: +Melhora o suporte do editor para seus modelos Pydantic com:: - * completação automática - * verificação de tipos - * refatoração - * buscas - * inspeções +* completação automática +* verificação de tipos +* refatoração +* buscas +* inspeções + +/// ## Use o modelo @@ -155,10 +161,13 @@ Os parâmetros da função serão reconhecidos conforme abaixo: * Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**. * Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | "Observação" + +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. + +O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. - O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. +/// ## Sem o Pydantic diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index 1a60e3571..caed17632 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -20,13 +20,19 @@ O primeiro valor é o valor padrão, você pode passar todas as validações adi {!../../../docs_src/cookie_params/tutorial001.py!} ``` -!!! note "Detalhes Técnicos" - `Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. +/// note | "Detalhes Técnicos" - Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. +`Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. -!!! info "Informação" - Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. + +/// + +/// info | "Informação" + +Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. + +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index 1f434d324..e5e2f8c27 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -78,7 +78,10 @@ Qualquer solicitação com um cabeçalho `Origin`. Neste caso, o middleware pass Para mais informações <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, acesse <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS documentation</a>. -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. +/// note | "Detalhes técnicos" - **FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette. +Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette. + +/// diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index 028bf3d20..420503b87 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos me No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. @@ -103,123 +119,165 @@ Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +```Python hl_lines="12-16" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. +/// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// Observe o método `__init__` usado para criar uma instância da classe: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Dica" - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "Python 3.10+ non-Annotated" +/// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. +/// + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. @@ -235,43 +293,57 @@ Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc Agora você pode declarar sua dependência utilizando essa classe. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+" +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função. @@ -279,21 +351,27 @@ O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" des Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. +/// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// O último `CommonQueryParams`, em: @@ -309,81 +387,107 @@ O último `CommonQueryParams`, em: Nesse caso, o primeiro `CommonQueryParams`, em: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +```Python +commons: Annotated[CommonQueryParams, ... +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.8+ non-Annotated +/// tip | "Dica" - ```Python - commons: CommonQueryParams ... - ``` +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso). Na verdade você poderia escrever apenas: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python +commons = Depends(CommonQueryParams) +``` - ```Python - commons = Depends(CommonQueryParams) - ``` +//// ...como em: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+" +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`. @@ -393,20 +497,27 @@ Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto s Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe. @@ -414,84 +525,114 @@ Para esses casos específicos, você pode fazer o seguinte: Em vez de escrever: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ...escreva: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +//// -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" +Utilize a versão com `Annotated` se possível. - ```Python - commons: CommonQueryParams = Depends() - ``` +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`. O mesmo exemplo ficaria então dessa forma: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial004_an.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+" +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// ...e o **FastAPI** saberá o que fazer. -!!! tip "Dica" - Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. +/// tip | "Dica" + +Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. + +É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código. - É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código. +/// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4a297268c..4a7a29390 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,39 +14,55 @@ O *decorador da operação de rota* recebe um argumento opcional `dependencies`. Ele deve ser uma lista de `Depends()`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. -!!! tip "Dica" - Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. +/// tip | "Dica" + +Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. - Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas. +Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas. - Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário. +Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário. -!!! info "Informação" - Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. +/// - Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}. +/// info | "Informação" + +Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. + +Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}. + +/// ## Erros das dependências e valores de retorno @@ -56,51 +72,69 @@ Você pode utilizar as mesmas *funções* de dependências que você usaria norm Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 non-Annotated - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip | "Dica" -=== "Python 3.8 non-Annotated" +Utilize a versão com `Annotated` se possível - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +/// - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Levantando exceções Essas dependências podem levantar exceções, da mesma forma que dependências comuns: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 non-Annotated -=== "Python 3.8 non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +Utilize a versão com `Annotated` se possível - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Valores de retorno @@ -108,26 +142,37 @@ E elas também podem ou não retornar valores, eles não serão utilizados. Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | "Dica" - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` -=== "Python 3.8+" - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// -=== "Python 3.8 non-Annotated" + Utilize a versão com `Annotated` se possível - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## Dependências para um grupo de *operações de rota* diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index 8b4175fc5..16c2cf899 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ O FastAPI possui suporte para dependências que realizam <abbr title='também ch Para fazer isso, utilize `yield` em vez de `return`, e escreva os passos extras (código) depois. -!!! tip "Dica" - Garanta que `yield` é utilizado apenas uma vez. +/// tip | "Dica" -!!! note "Detalhes Técnicos" - Qualquer função que possa ser utilizada com: +Garanta que `yield` é utilizado apenas uma vez. - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +/// - pode ser utilizada como uma dependência do **FastAPI**. +/// note | "Detalhes Técnicos" - Na realidade, o FastAPI utiliza esses dois decoradores internamente. +Qualquer função que possa ser utilizada com: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + +pode ser utilizada como uma dependência do **FastAPI**. + +Na realidade, o FastAPI utiliza esses dois decoradores internamente. + +/// ## Uma dependência de banco de dados com `yield` @@ -39,10 +45,13 @@ O código após o `yield` é executado após a resposta ser entregue: {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip "Dica" - Você pode usar funções assíncronas (`async`) ou funções comuns. +/// tip | "Dica" - O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns. +Você pode usar funções assíncronas (`async`) ou funções comuns. + +O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns. + +/// ## Uma dependência com `yield` e `try` @@ -66,26 +75,35 @@ O **FastAPI** garantirá que o "código de saída" em cada dependência com `yie Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` depender de `dependency_a`: -=== "python 3.9+" +//// tab | python 3.9+ - ```python hl_lines="6 14 22" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +```python hl_lines="6 14 22" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` -=== "python 3.8+" +//// - ```python hl_lines="5 13 21" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// tab | python 3.8+ -=== "python 3.8+ non-annotated" +```python hl_lines="5 13 21" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// - ```python hl_lines="4 12 20" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// tab | python 3.8+ non-annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```python hl_lines="4 12 20" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` + +//// E todas elas podem utilizar `yield`. @@ -93,26 +111,35 @@ Neste caso, `dependency_c` precisa que o valor de `dependency_b` (nomeada de `de E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada de `dep_a`) continue disponível para executar seu código de saída. -=== "python 3.9+" +//// 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!} +``` + +//// - ```python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// tab | python 3.8+ non-annotated -=== "python 3.8+" +/// tip | "Dica" - ```python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "python 3.8+ non-annotated" +/// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +```python hl_lines="16-17 24-25" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` - ```python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// Da mesma forma, você pode ter algumas dependências com `yield` e outras com `return` e ter uma relação de dependência entre algumas dos dois tipos. @@ -122,10 +149,13 @@ Você pode ter qualquer combinação de dependências que você quiser. O **FastAPI** se encarrega de executá-las na ordem certa. -!!! note "Detalhes Técnicos" - Tudo isso funciona graças aos <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">gerenciadores de contexto</a> do Python. +/// note | "Detalhes Técnicos" + +Tudo isso funciona graças aos <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">gerenciadores de contexto</a> do Python. - O **FastAPI** utiliza eles internamente para alcançar isso. +O **FastAPI** utiliza eles internamente para alcançar isso. + +/// ## Dependências com `yield` e `httpexception` @@ -133,32 +163,43 @@ Você viu que dependências podem ser utilizadas com `yield` e podem incluir blo Da mesma forma, você pode lançar uma `httpexception` ou algo parecido no código de saída, após o `yield` -!!! tip "Dica" +/// tip | "Dica" + +Essa é uma técnica relativamente avançada, e na maioria dos casos você não precisa dela totalmente, já que você pode lançar exceções (incluindo `httpexception`) dentro do resto do código da sua aplicação, por exemplo, em uma *função de operação de rota*. + +Mas ela existe para ser utilizada caso você precise. 🤓 + +/// + +//// tab | python 3.9+ + +```python hl_lines="18-22 31" +{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +``` + +//// - Essa é uma técnica relativamente avançada, e na maioria dos casos você não precisa dela totalmente, já que você pode lançar exceções (incluindo `httpexception`) dentro do resto do código da sua aplicação, por exemplo, em uma *função de operação de rota*. +//// tab | python 3.8+ - Mas ela existe para ser utilizada caso você precise. 🤓 +```python hl_lines="17-21 30" +{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +``` -=== "python 3.9+" +//// - ```python hl_lines="18-22 31" - {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} - ``` +//// tab | python 3.8+ non-annotated -=== "python 3.8+" +/// tip | "Dica" - ```python hl_lines="17-21 30" - {!> ../../../docs_src/dependencies/tutorial008b_an.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "python 3.8+ non-annotated" +/// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +```python hl_lines="16-20 29" +{!> ../../../docs_src/dependencies/tutorial008b.py!} +``` - ```python hl_lines="16-20 29" - {!> ../../../docs_src/dependencies/tutorial008b.py!} - ``` +//// Uma alternativa que você pode utilizar para capturar exceções (e possivelmente lançar outra HTTPException) é criar um [Manipulador de Exceções Customizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. @@ -166,26 +207,35 @@ 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: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +``` + +//// - ```Python hl_lines="15-16" - {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="14-15" +{!> ../../../docs_src/dependencies/tutorial008c_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="14-15" - {!> ../../../docs_src/dependencies/tutorial008c_an.py!} - ``` +//// tab | Python 3.8+ non-annotated -=== "Python 3.8+ non-annotated" +/// tip | "dica" - !!! tip "dica" - utilize a versão com `Annotated` se possível. +utilize a versão com `Annotated` se possível. - ```Python hl_lines="13-14" - {!> ../../../docs_src/dependencies/tutorial008c.py!} - ``` +/// + +```Python hl_lines="13-14" +{!> ../../../docs_src/dependencies/tutorial008c.py!} +``` + +//// 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. 😱 @@ -195,26 +245,35 @@ 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`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial008d_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | python 3.8+ non-annotated - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial008d_an.py!} - ``` +/// tip | "Dica" -=== "python 3.8+ non-annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial008d.py!} +``` - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial008d.py!} - ``` +//// Agora o cliente irá receber a mesma resposta *HTTP 500 Internal Server Error*, mas o servidor terá nosso `InternalError` personalizado nos logs. 😎 @@ -257,22 +316,31 @@ participant tasks as Tarefas de Background end ``` -!!! info "Informação" - Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*. +/// info | "Informação" + +Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*. + +Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada + +/// + +/// tip | "Dica" - Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada +Esse diagrama mostra `HttpException`, mas você pode levantar qualquer outra exceção que você capture em uma dependência com `yield` ou um [Manipulador de exceções personalizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. -!!! tip "Dica" - Esse diagrama mostra `HttpException`, mas você pode levantar qualquer outra exceção que você capture em uma dependência com `yield` ou um [Manipulador de exceções personalizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. +Se você lançar qualquer exceção, ela será passada para as dependências com yield, inlcuindo a `HTTPException`. Na maioria dos casos você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente. - Se você lançar qualquer exceção, ela será passada para as dependências com yield, inlcuindo a `HTTPException`. Na maioria dos casos você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente. +/// ## Dependências com `yield`, `HTTPException`, `except` e Tarefas de Background -!!! warning "Aviso" - Você provavelmente não precisa desses detalhes técnicos, você pode pular essa seção e continuar na próxima seção abaixo. +/// warning | "Aviso" - Esses detalhes são úteis principalmente se você estiver usando uma versão do FastAPI anterior à 0.106.0 e utilizando recursos de dependências com `yield` em tarefas de background. +Você provavelmente não precisa desses detalhes técnicos, você pode pular essa seção e continuar na próxima seção abaixo. + +Esses detalhes são úteis principalmente se você estiver usando uma versão do FastAPI anterior à 0.106.0 e utilizando recursos de dependências com `yield` em tarefas de background. + +/// ### Dependências com `yield` e `except`, Detalhes Técnicos @@ -288,11 +356,13 @@ Isso foi implementado dessa forma principalmente para permitir que os mesmos obj Ainda assim, como isso exigiria esperar que a resposta navegasse pela rede enquanto mantia ativo um recurso desnecessário na dependência com yield (por exemplo, uma conexão com banco de dados), isso mudou na versão 0.106.0 do FastAPI. -!!! tip "Dica" +/// tip | "Dica" - Adicionalmente, uma tarefa de background é, normalmente, um conjunto de lógicas independentes que devem ser manipuladas separadamente, com seus próprios recursos (e.g. sua própria conexão com banco de dados). +Adicionalmente, uma tarefa de background é, normalmente, um conjunto de lógicas independentes que devem ser manipuladas separadamente, com seus próprios recursos (e.g. sua própria conexão com banco de dados). - Então, dessa forma você provavelmente terá um código mais limpo. +Então, dessa forma você provavelmente terá um código mais limpo. + +/// Se você costumava depender desse comportamento, agora você precisa criar os recursos para uma tarefa de background dentro dela mesma, e usar internamente apenas dados que não dependam de recursos de dependências com `yield`. @@ -320,10 +390,13 @@ Quando você cria uma dependência com `yield`, o **FastAPI** irá criar um gere ### Utilizando gerenciadores de contexto em dependências com `yield` -!!! warning "Aviso" - Isso é uma ideia mais ou menos "avançada". +/// warning | "Aviso" + +Isso é uma ideia mais ou menos "avançada". - Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto. +Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto. + +/// Em python, você pode criar Gerenciadores de Contexto ao <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank"> criar uma classe com dois métodos: `__enter__()` e `__exit__()`</a>. @@ -333,17 +406,20 @@ Você também pode usá-los dentro de dependências com `yield` do **FastAPI** a {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip "Dica" - Outra forma de criar um gerenciador de contexto é utilizando: +/// tip | "Dica" + +Outra forma de criar um gerenciador de contexto é utilizando: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +Para decorar uma função com um único `yield`. - Para decorar uma função com um único `yield`. +Isso é o que o **FastAPI** usa internamente para dependências com `yield`. - Isso é o que o **FastAPI** usa internamente para dependências com `yield`. +Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria). - Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria). +O FastAPI irá fazer isso para você internamente. - O FastAPI irá fazer isso para você internamente. +/// diff --git a/docs/pt/docs/tutorial/dependencies/global-dependencies.md b/docs/pt/docs/tutorial/dependencies/global-dependencies.md index 3eb5faa34..96dbaee5e 100644 --- a/docs/pt/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ De forma semelhante a [adicionar dependências (`dependencies`) em *decoradores Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicação: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.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!} +``` + +//// 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 3c0155a6e..f7b32966c 100644 --- a/docs/pt/docs/tutorial/dependencies/index.md +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -31,41 +31,57 @@ 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*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.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!} +``` + +//// E pronto. @@ -85,90 +101,125 @@ Neste caso, a dependência espera por: E então retorna um `dict` contendo esses valores. -!!! info "Informação" - FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0. +/// info | "Informação" + +FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0. - Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`. +Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`. - Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`. +Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`. + +/// ### Importando `Depends` -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+" +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "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!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### 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: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "Python 3.8+ 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!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 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. @@ -180,8 +231,11 @@ Você **não chama a função** diretamente (não adicione os parênteses no fin E essa função vai receber os parâmetros da mesma forma que uma *função de operação de rota*. -!!! tip "Dica" - Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo. +/// tip | "Dica" + +Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo. + +/// Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de: @@ -202,10 +256,13 @@ common_parameters --> read_users Assim, você escreve um código compartilhado apenas uma vez e o **FastAPI** se encarrega de chamá-lo em suas *operações de rota*. -!!! check "Checando" - Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar. +/// check | "Checando" + +Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar. + +Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto. - Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto. +/// ## Compartilhando dependências `Annotated` @@ -219,28 +276,37 @@ 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: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip | "Dica" -!!! tip "Dica" - Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**. +Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**. - Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎 +Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎 + +/// As dependências continuarão funcionando como esperado, e a **melhor parte** é que a **informação sobre o tipo é preservada**, o que signfica que seu editor de texto ainda irá incluir **preenchimento automático**, **visualização de erros**, etc. O mesmo vale para ferramentas como `mypy`. @@ -256,8 +322,11 @@ E você pode declarar dependências utilizando `async def` dentro de *funções Não faz diferença. O **FastAPI** sabe o que fazer. -!!! note "Nota" - Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação. +/// note | "Nota" + +Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação. + +/// ## Integrando com OpenAPI diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md index 189f196ab..279bf3339 100644 --- a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -10,41 +10,57 @@ O **FastAPI** se encarrega de resolver essas dependências. Você pode criar uma primeira dependência (injetável) dessa forma: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9-10" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.10 non-Annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="9-10" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "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!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro. @@ -54,41 +70,57 @@ 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): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 non-Annotated - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.9+" +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "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!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Vamos focar nos parâmetros declarados: @@ -101,46 +133,65 @@ Vamos focar nos parâmetros declarados: Então podemos utilizar a dependência com: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10 non-Annotated -=== "Python 3.9+" +/// tip | "Dica" - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "Python 3.8 non-Annotated" +/// + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +/// info | "Informação" -!!! info "Informação" - Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`. +Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`. - Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função. +Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função. + +/// ```mermaid graph TB @@ -161,22 +212,29 @@ E o valor retornado é salvo em um <abbr title="Um utilitário/sistema para arma Em um cenário avançado onde você precise que a dependência seja calculada em cada passo (possivelmente várias vezes) de uma requisição em vez de utilizar o valor em "cache", você pode definir o parâmetro `use_cache=False` em `Depends`: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` - ```Python hl_lines="1" - async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): - return {"fresh_value": fresh_value} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="1" - async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): - return {"fresh_value": fresh_value} - ``` +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// ## Recapitulando @@ -186,9 +244,12 @@ Consiste apenas de funções que parecem idênticas a *funções de operação d Mas ainda assim, é bastante poderoso, e permite que você declare grafos (árvores) de dependências com uma profundidade arbitrária. -!!! tip "Dica" - Tudo isso pode não parecer muito útil com esses exemplos. +/// tip | "Dica" + +Tudo isso pode não parecer muito útil com esses exemplos. + +Mas você verá o quão útil isso é nos capítulos sobre **segurança**. - Mas você verá o quão útil isso é nos capítulos sobre **segurança**. +E você também verá a quantidade de código que você não precisara escrever. - E você também verá a quantidade de código que você não precisara escrever. +/// diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index 7a8d20515..c104098ee 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ 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: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`. @@ -38,5 +42,8 @@ O resultado de chamar a função é algo que pode ser codificado com o padrão d A função não retorna um grande `str` contendo os dados no formato JSON (como uma string). Mas sim, retorna uma estrutura de dados padrão do Python (por exemplo, um `dict`) com valores e subvalores compatíveis com JSON. -!!! note "Nota" - `jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários. +/// note | "Nota" + +`jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários. + +/// diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 3b1f6ee54..564aeadca 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ Isso é especialmente o caso para modelos de usuários, porque: * O **modelo de saída** não deve ter uma senha. * O **modelo de banco de dados** provavelmente precisaria ter uma senha criptografada. -!!! danger - Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois. +/// danger - Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois. + +Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// ## Múltiplos modelos Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados: -=== "Python 3.8 and above" +//// 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!} - ``` +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` -=== "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!} - ``` +//// 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!} +``` + +//// ### Sobre `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning - As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real. +/// warning + +As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real. + +/// ## Reduzir duplicação @@ -158,17 +168,21 @@ 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): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` + +//// - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// ## `Union` ou `anyOf` @@ -178,20 +192,27 @@ Isso será definido no OpenAPI com `anyOf`. Para fazer isso, use a dica de tipo padrão do Python <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: -!!! note - Ao definir um <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. +/// note + +Ao definir um <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. -=== "Python 3.8 and above" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8 and above -=== "Python 3.10 and above" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.10 and above + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// ### `Union` no Python 3.10 @@ -213,17 +234,21 @@ 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): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` -=== "Python 3.9 and above" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9 and above + +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// ## Resposta com `dict` arbitrário @@ -233,17 +258,21 @@ 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): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` + +//// - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// ## Em resumo diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index 619a68601..4c2a8a8e3 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note "Nota" - O comando `uvicorn main:app` se refere a: +/// note | "Nota" - * `main`: o arquivo `main.py` (o "módulo" Python). - * `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`. - * `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento. +O comando `uvicorn main:app` se refere a: + +* `main`: o arquivo `main.py` (o "módulo" Python). +* `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`. +* `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento. + +/// Na saída, temos: @@ -136,10 +139,13 @@ Você também pode usá-lo para gerar código automaticamente para clientes que `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. -!!! note "Detalhes técnicos" - `FastAPI` é uma classe que herda diretamente de `Starlette`. +/// note | "Detalhes técnicos" + +`FastAPI` é uma classe que herda diretamente de `Starlette`. - Você pode usar todas as funcionalidades do <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> com `FastAPI` também. +Você pode usar todas as funcionalidades do <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> com `FastAPI` também. + +/// ### Passo 2: crie uma "instância" de `FastAPI` @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Informação" - Uma "rota" também é comumente chamada de "endpoint". +/// info | "Informação" + +Uma "rota" também é comumente chamada de "endpoint". + +/// Ao construir uma API, a "rota" é a principal forma de separar "preocupações" e "recursos". @@ -250,16 +259,19 @@ O `@app.get("/")` diz ao **FastAPI** que a função logo abaixo é responsável * a rota `/` * usando o <abbr title="o método HTTP GET">operador <code>get</code></abbr> -!!! info "`@decorador`" - Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador". +/// info | "`@decorador`" - Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo). +Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador". - Um "decorador" pega a função abaixo e faz algo com ela. +Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo). - Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`. +Um "decorador" pega a função abaixo e faz algo com ela. - É o "**decorador de rota**". +Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`. + +É o "**decorador de rota**". + +/// Você também pode usar as outras operações: @@ -274,14 +286,17 @@ E os mais exóticos: * `@app.patch()` * `@app.trace()` -!!! tip "Dica" - Você está livre para usar cada operação (método HTTP) como desejar. +/// tip | "Dica" + +Você está livre para usar cada operação (método HTTP) como desejar. - O **FastAPI** não impõe nenhum significado específico. +O **FastAPI** não impõe nenhum significado específico. - As informações aqui são apresentadas como uma orientação, não uma exigência. +As informações aqui são apresentadas como uma orientação, não uma exigência. - Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`. +Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`. + +/// ### Passo 4: defina uma **função de rota** @@ -309,8 +324,11 @@ Você também pode defini-la como uma função normal em vez de `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Nota" - Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}. +/// note | "Nota" + +Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}. + +/// ### Passo 5: retorne o conteúdo diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md index d9f3d6782..6bebf604e 100644 --- a/docs/pt/docs/tutorial/handling-errors.md +++ b/docs/pt/docs/tutorial/handling-errors.md @@ -66,12 +66,14 @@ Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou se } ``` -!!! tip "Dica" - Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`. +/// tip | "Dica" - Você pode passar um `dict` ou um `list`, etc. - Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON. +Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`. +Você pode passar um `dict` ou um `list`, etc. +Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON. + +/// ## Adicione headers customizados @@ -107,10 +109,13 @@ Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um J {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Detalhes Técnicos" - Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. +/// note | "Detalhes Técnicos" + +Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. + +**FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`. - **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`. +/// ## Sobrescreva o manipulador padrão de exceções @@ -157,8 +162,11 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -!!! warning "Aviso" - Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. +/// warning | "Aviso" + +Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. + +/// `RequestValidationError` é uma subclasse do <a href="https://docs.pydantic.dev/latest/#error-handling" class="external-link" target="_blank">`ValidationError`</a> existente no Pydantic. @@ -178,11 +186,13 @@ Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Detalhes Técnicos" - Você pode usar `from starlette.responses import PlainTextResponse`. +/// note | "Detalhes Técnicos" + +Você pode usar `from starlette.responses import PlainTextResponse`. - **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. +**FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. +/// ### Use o body do `RequestValidationError`. diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md index 4bdfb7e9c..809fb5cf1 100644 --- a/docs/pt/docs/tutorial/header-params.md +++ b/docs/pt/docs/tutorial/header-params.md @@ -6,17 +6,21 @@ Você pode definir parâmetros de Cabeçalho da mesma maneira que define paramê Primeiro importe `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// ## Declare parâmetros de `Header` @@ -24,25 +28,35 @@ 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: -=== "Python 3.10+" +//// 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!} +``` + +//// + +/// note | "Detalhes Técnicos" - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +`Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`. -=== "Python 3.8+" +Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// -!!! note "Detalhes Técnicos" - `Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`. +/// info - Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. +Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. -!!! info - Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +/// ## Conversão automática @@ -60,20 +74,27 @@ 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`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +```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!} +``` + +//// -=== "Python 3.8+" +/// warning | "Aviso" - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados. -!!! warning "Aviso" - Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados. +/// ## Cabeçalhos duplicados @@ -85,23 +106,29 @@ 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: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como: diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md index 60fc26ae0..a2f380284 100644 --- a/docs/pt/docs/tutorial/index.md +++ b/docs/pt/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código. -!!! note "Nota" - Você também pode instalar parte por parte. +/// note | "Nota" - Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção: +Você também pode instalar parte por parte. - ``` - pip install fastapi - ``` +Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção: - Também instale o `uvicorn` para funcionar como servidor: +``` +pip install fastapi +``` + +Também instale o `uvicorn` para funcionar como servidor: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +E o mesmo para cada dependência opcional que você quiser usar. - E o mesmo para cada dependência opcional que você quiser usar. +/// ## Guia Avançado de Usuário diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md index be2128981..1760246ee 100644 --- a/docs/pt/docs/tutorial/middleware.md +++ b/docs/pt/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ Um "middleware" é uma função que manipula cada **requisição** antes de ser * Ele pode fazer algo com essa **resposta** ou executar qualquer código necessário. * Então ele retorna a **resposta**. -!!! note "Detalhes técnicos" - Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware. +/// note | "Detalhes técnicos" - Se houver alguma tarefa em segundo plano (documentada posteriormente), ela será executada *depois* de todo o middleware. +Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware. + +Se houver alguma tarefa em segundo plano (documentada posteriormente), ela será executada *depois* de todo o middleware. + +/// ## Criar um middleware @@ -32,15 +35,21 @@ A função middleware recebe: {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "Dica" - Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">usando o prefixo 'X-'</a>. +/// tip | "Dica" + +Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">usando o prefixo 'X-'</a>. + +Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Documentos CORS da Starlette</a>. + +/// + +/// note | "Detalhes técnicos" - Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Documentos CORS da Starlette</a>. +Você também pode usar `from starlette.requests import Request`. -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.requests import Request`. +**FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. - **FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +/// ### Antes e depois da `response` diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 13a87240f..c57813780 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo. -!!! warning "Aviso" - Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. +/// warning | "Aviso" + +Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. + +/// ## Código de Status da Resposta @@ -13,52 +16,67 @@ Você pode passar diretamente o código `int`, como `404`. Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. -!!! note "Detalhes Técnicos" - Você também poderia usar `from starlette import status`. +/// note | "Detalhes Técnicos" + +Você também poderia usar `from starlette import status`. + +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. +/// ## Tags Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// -=== "Python 3.9 and above" +//// tab | Python 3.9 and above - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.10 and above" +//// - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +//// tab | Python 3.10 and above + +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática: @@ -80,23 +98,29 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. Você pode adicionar um `summary` e uma `description`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// ## Descrição do docstring @@ -104,23 +128,29 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec Você pode escrever <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring). -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.10 and above" +//// tab | Python 3.10 and above - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// Ela será usada nas documentações interativas: @@ -131,31 +161,43 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +//// + +//// tab | Python 3.9 and above + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.10 and above + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +//// -=== "Python 3.9 and above" +/// info | "Informação" - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. -=== "Python 3.10 and above" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info "Informação" - Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. +OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. -!!! check - OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. +Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". - Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". +/// <img src="/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index eb0d31dc3..08ed03f75 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,21 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme Primeiro, importe `Path` de `fastapi`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +//// ## Declare metadados @@ -24,24 +28,31 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`. Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -!!! note "Nota" - Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. +//// - Então, você deve declará-lo com `...` para marcá-lo como obrigatório. +/// note | "Nota" - Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. +Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. + +Então, você deve declará-lo com `...` para marcá-lo como obrigatório. + +Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. + +/// ## Ordene os parâmetros de acordo com sua necessidade @@ -121,18 +132,24 @@ E você também pode declarar validações numéricas: * `lt`: menor que (`l`ess `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -!!! info "Informação" - `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. +/// info | "Informação" + +`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. + +Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. + +/// + +/// note | "Detalhes Técnicos" - Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. +Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. -!!! note "Detalhes Técnicos" - Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. +Que quando chamadas, retornam instâncias de classes de mesmo nome. - Que quando chamadas, retornam instâncias de classes de mesmo nome. +Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. - Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. +Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. - Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. +Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. - Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. +/// diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index 27aa9dfcf..fb872e4f5 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -24,7 +24,12 @@ Você pode declarar o tipo de um parâmetro na função usando as anotações pa Nesse caso, `item_id` está sendo declarado como um `int`. -!!! check "Verifique" +/// check | "Verifique" + + + +/// + Isso vai dar à você suporte do seu editor dentro das funções, com verificações de erros, autocompletar, etc. ## Conversão de <abbr title="também conhecido como: serialização, parsing, marshalling">dados</abbr> @@ -35,7 +40,12 @@ Se você rodar esse exemplo e abrir o seu navegador em <a href="http://127.0.0.1 {"item_id":3} ``` -!!! check "Verifique" +/// check | "Verifique" + + + +/// + Observe que o valor recebido pela função (e também retornado por ela) é `3`, como um Python `int`, não como uma string `"3"`. Então, com essa declaração de tipo, o **FastAPI** dá pra você um <abbr title="convertendo a string que veio do request HTTP em um dado Python">"parsing"</abbr> automático no request . @@ -63,7 +73,12 @@ devido ao parâmetro da rota `item_id` ter um valor `"foo"`, que não é um `int O mesmo erro apareceria se você tivesse fornecido um `float` ao invés de um `int`, como em: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! check "Verifique" +/// check | "Verifique" + + + +/// + Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados. Observe que o erro também mostra claramente o ponto exato onde a validação não passou. @@ -76,7 +91,12 @@ Quando você abrir o seu navegador em <a href="http://127.0.0.1:8000/docs" class <img src="/img/tutorial/path-params/image01.png"> -!!! check "Verifique" +/// check | "Verifique" + + + +/// + Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI). Veja que o parâmetro de rota está declarado como sendo um inteiro (int). @@ -131,10 +151,18 @@ Assim, crie atributos de classe com valores fixos, que serão os valores válido {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "informação" - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (ou enums) estão disponíveis no Python</a> desde a versão 3.4. +/// info | "informação" + +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (ou enums) estão disponíveis no Python</a> desde a versão 3.4. + +/// + +/// tip | "Dica" + + + +/// -!!! tip "Dica" Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de <abbr title="técnicamente, modelos de arquitetura de Deep Learning">modelos</abbr> de Machine Learning (aprendizado de máquina). ### Declare um *parâmetro de rota* @@ -171,7 +199,12 @@ Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_na {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Dica" +/// tip | "Dica" + + + +/// + Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value` #### Retorne *membros de enumeration* @@ -225,7 +258,12 @@ Então, você poderia usar ele com: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Dica" +/// tip | "Dica" + + + +/// + Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`). Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`. diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index 9a9e071db..eac879593 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,13 @@ Vamos utilizar essa aplicação como exemplo: O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | "Observação" - O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. + +O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. + +/// ## Validação adicional @@ -51,22 +54,25 @@ q: Union[str, None] = None Mas o declara explicitamente como um parâmetro de consulta. -!!! info "Informação" - Tenha em mente que o FastAPI se preocupa com a parte: +/// info | "Informação" - ```Python - = None - ``` +Tenha em mente que o FastAPI se preocupa com a parte: - Ou com: +```Python += None +``` - ```Python - = Query(default=None) - ``` +Ou com: - E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. +```Python += Query(default=None) +``` + +E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. - O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. +O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. + +/// Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos: @@ -112,8 +118,11 @@ Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_leng {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "Observação" - O parâmetro torna-se opcional quando possui um valor padrão. +/// note | "Observação" + +O parâmetro torna-se opcional quando possui um valor padrão. + +/// ## Torne-o obrigatório @@ -141,8 +150,11 @@ Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Q {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "Informação" - Se você nunca viu os `...` antes: é um valor único especial, faz <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">parte do Python e é chamado "Ellipsis"</a>. +/// info | "Informação" + +Se você nunca viu os `...` antes: é um valor único especial, faz <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">parte do Python e é chamado "Ellipsis"</a>. + +/// Dessa forma o **FastAPI** saberá que o parâmetro é obrigatório. @@ -175,8 +187,11 @@ Assim, a resposta para essa URL seria: } ``` -!!! tip "Dica" - Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. +/// tip | "Dica" + +Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. + +/// A documentação interativa da API irá atualizar de acordo, permitindo múltiplos valores: @@ -215,10 +230,13 @@ Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "Observação" - Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. +/// note | "Observação" - Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. +Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. + +Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. + +/// ## Declarando mais metadados @@ -226,10 +244,13 @@ Você pode adicionar mais informações sobre o parâmetro. Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas. -!!! note "Observação" - Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. +/// note | "Observação" + +Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. + +Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. - Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. +/// Você pode adicionar um `title`: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index ff6f38fe5..78d54f09b 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -63,39 +63,49 @@ Os valores dos parâmetros na sua função serão: Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. -!!! check "Verificar" - Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// check | "Verificar" + +Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// ## Conversão dos tipos de parâmetros de consulta Você também pode declarar tipos `bool`, e eles serão convertidos: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Nesse caso, se você for para: @@ -137,17 +147,21 @@ E você não precisa declarar eles em nenhuma ordem específica. Eles serão detectados pelo nome: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` + +//// ## Parâmetros de consulta obrigatórios @@ -203,17 +217,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// Nesse caso, existem 3 parâmetros de consulta: @@ -221,5 +239,8 @@ Nesse caso, existem 3 parâmetros de consulta: * `skip`, um `int` com o valor padrão `0`. * `limit`, um `int` opcional. -!!! tip "Dica" - Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. +/// tip | "Dica" + +Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 22954761b..2cf406386 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -2,11 +2,13 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. -!!! info "Informação" - Para receber arquivos carregados e/ou dados de formulário, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info | "Informação" - Por exemplo: `pip install python-multipart`. +Para receber arquivos carregados e/ou dados de formulário, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +Por exemplo: `pip install python-multipart`. + +/// ## Importe `File` e `Form` @@ -26,10 +28,13 @@ Os arquivos e campos de formulário serão carregados como dados de formulário E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. +/// warning | "Aviso" + +Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. - Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 0eb67391b..fc8c7bbad 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -2,10 +2,13 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. -!!! info "Informação" - Para usar formulários, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info | "Informação" - Ex: `pip install python-multipart`. +Para usar formulários, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +Ex: `pip install python-multipart`. + +/// ## Importe `Form` @@ -29,11 +32,17 @@ A <abbr title="especificação">spec</abbr> exige que os campos sejam exatamente Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`). -!!! info "Informação" - `Form` é uma classe que herda diretamente de `Body`. +/// info | "Informação" + +`Form` é uma classe que herda diretamente de `Body`. + +/// + +/// tip | "Dica" -!!! tip "Dica" - Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). +Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// ## Sobre "Campos de formulário" @@ -41,17 +50,23 @@ A forma como os formulários HTML (`<form></form>`) enviam os dados para o servi O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON. -!!! note "Detalhes técnicos" - Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. +/// note | "Detalhes técnicos" + +Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. + + Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs para <code>POST</code></a>. + +/// - Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. +/// warning | "Aviso" - Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs para <code>POST</code></a>. +Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. +Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. - Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index 2df17d4ea..dc8e12048 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Nota" - Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. +/// note | "Nota" + +Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. + +/// O parâmetro `status_code` recebe um número com o código de status HTTP. -!!! info "Informação" - `status_code` também pode receber um `IntEnum`, como o do Python <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. +/// info | "Informação" + +`status_code` também pode receber um `IntEnum`, como o do Python <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>. + +/// Dessa forma: @@ -27,15 +33,21 @@ Dessa forma: <img src="/img/tutorial/response-status-code/image01.png"> -!!! note "Nota" - Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. +/// note | "Nota" + +Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. + +O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. - O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. +/// ## Sobre os códigos de status HTTP -!!! note "Nota" - Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. +/// note | "Nota" + +Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. + +/// Em HTTP, você envia um código de status numérico de 3 dígitos como parte da resposta. @@ -55,8 +67,11 @@ Resumidamente: * Para erros genéricos do cliente, você pode usar apenas `400`. * `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status. -!!! tip "Dica" - Para saber mais sobre cada código de status e qual código serve para quê, verifique o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentação sobre códigos de status HTTP</a>. +/// tip | "Dica" + +Para saber mais sobre cada código de status e qual código serve para quê, verifique o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentação sobre códigos de status HTTP</a>. + +/// ## Atalho para lembrar os nomes @@ -80,11 +95,13 @@ Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa form <img src="/img/tutorial/response-status-code/image02.png"> -!!! note "Detalhes técnicos" - Você também pode usar `from starlette import status`. +/// note | "Detalhes técnicos" + +Você também pode usar `from starlette import status`. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +/// ## Alterando o padrão diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index d04dc1a26..a291db045 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -14,10 +14,13 @@ Você pode declarar um `example` para um modelo Pydantic usando `Config` e `sche Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. -!!! tip "Dica" - Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. +/// tip | "Dica" - Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. +Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. + +Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. + +/// ## `Field` de argumentos adicionais @@ -29,8 +32,11 @@ Você pode usar isso para adicionar um `example` para cada campo: {!../../../docs_src/schema_extra_example/tutorial002.py!} ``` -!!! warning "Atenção" - Lembre-se de que esses argumentos extras passados não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. +/// warning | "Atenção" + +Lembre-se de que esses argumentos extras passados não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. + +/// ## `example` e `examples` no OpenAPI @@ -85,10 +91,13 @@ Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim: ## Detalhes técnicos -!!! warning "Atenção" - Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. +/// warning | "Atenção" + +Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. + +Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. - Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. +/// Quando você adiciona um exemplo dentro de um modelo Pydantic, usando `schema_extra` ou` Field(example="something") `esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 4331a0bc3..007fefcb9 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -25,7 +25,12 @@ Copie o exemplo em um arquivo `main.py`: ## Execute-o -!!! info "informação" +/// info | "informação" + + + +/// + Primeiro, instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. Ex: `pip install python-multipart`. @@ -52,7 +57,12 @@ Você verá algo deste tipo: <img src="/img/tutorial/security/image01.png"> -!!! check "Botão de Autorizar!" +/// check | "Botão de Autorizar!" + + + +/// + Você já tem um novo "botão de autorizar!". E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar. @@ -61,7 +71,12 @@ E se você clicar, você terá um pequeno formulário de autorização para digi <img src="/img/tutorial/security/image02.png"> -!!! note "Nota" +/// note | "Nota" + + + +/// + Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá. Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API. @@ -104,7 +119,12 @@ Então, vamos rever de um ponto de vista simplificado: Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`. -!!! info "informação" +/// info | "informação" + + + +/// + Um token "bearer" não é a única opção. Mas é a melhor no nosso caso. @@ -119,7 +139,12 @@ Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passam {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip "Dica" +/// tip | "Dica" + + + +/// + Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`. Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`. @@ -130,7 +155,12 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL Em breve também criaremos o atual path operation. -!!! info "informação" +/// info | "informação" + + + +/// + Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`. Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso. @@ -157,7 +187,12 @@ Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática). -!!! info "Detalhes técnicos" +/// info | "Detalhes técnicos" + + + +/// + **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`. Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI. diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md index f94a8ab62..2f23aa47e 100644 --- a/docs/pt/docs/tutorial/security/index.md +++ b/docs/pt/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Não é muito popular ou usado nos dias atuais. OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS. -!!! tip "Dica" - Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. +/// tip | "Dica" +Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI define os seguintes esquemas de segurança: * Essa descoberta automática é o que é definido na especificação OpenID Connect. -!!! tip "Dica" - Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. +/// tip | "Dica" + +Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. + +O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. - O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. +/// ## **FastAPI** utilitários diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index 009158fc6..efaf07dfb 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.staticfiles import StaticFiles`. +/// note | "Detalhes técnicos" - O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. +Você também pode usar `from starlette.staticfiles import StaticFiles`. + +O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. + +/// ### O que é "Montagem" diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index 24a45fa55..413bf70b2 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -33,12 +33,18 @@ DRF использовался многими компаниями, включа Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**. -!!! note "Заметка" - Django REST Framework был создан Tom Christie. - Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. +/// note | "Заметка" -!!! check "Идея для **FastAPI**" - Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. +Django REST Framework был создан Tom Christie. +Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. + +/// + +/// check | "Идея для **FastAPI**" + +Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. + +/// ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> @@ -56,11 +62,13 @@ Flask часто используется и для приложений, кот Простота Flask, показалась мне подходящей для создания API. Но ещё нужно было найти "Django REST Framework" для Flask. -!!! check "Идеи для **FastAPI**" - Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. +/// check | "Идеи для **FastAPI**" + +Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. - Должна быть простая и лёгкая в использовании система маршрутизации запросов. +Должна быть простая и лёгкая в использовании система маршрутизации запросов. +/// ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> @@ -100,11 +108,13 @@ def read_url(): Глядите, как похоже `requests.get(...)` и `@app.get(...)`. -!!! check "Идеи для **FastAPI**" - * Должен быть простой и понятный API. - * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. - * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// check | "Идеи для **FastAPI**" + +* Должен быть простой и понятный API. +* Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. +* Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -119,16 +129,19 @@ def read_url(): Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI". -!!! check "Идеи для **FastAPI**" - Использовать открытые стандарты для спецификаций API вместо самодельных схем. +/// check | "Идеи для **FastAPI**" - Совместимость с основанными на стандартах пользовательскими интерфейсами: +Использовать открытые стандарты для спецификаций API вместо самодельных схем. - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> +Совместимость с основанными на стандартах пользовательскими интерфейсами: - Они были выбраны за популярность и стабильность. - Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> + +Они были выбраны за популярность и стабильность. +Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. + +/// ### REST фреймворки для Flask @@ -152,8 +165,11 @@ def read_url(): Итак, чтобы определить каждую <abbr title="Формат данных">схему</abbr>, Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow. -!!! check "Идея для **FastAPI**" - Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. +/// check | "Идея для **FastAPI**" + +Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -165,11 +181,17 @@ Webargs - это инструмент, который был создан для Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**. -!!! info "Информация" - Webargs бы создан разработчиками Marshmallow. +/// info | "Информация" + +Webargs бы создан разработчиками Marshmallow. + +/// -!!! check "Идея для **FastAPI**" - Должна быть автоматическая проверка входных данных. +/// check | "Идея для **FastAPI**" + +Должна быть автоматическая проверка входных данных. + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -190,11 +212,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Редактор кода не особо может помочь в такой парадигме. А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной. -!!! info "Информация" - APISpec тоже был создан авторами Marshmallow. +/// info | "Информация" + +APISpec тоже был создан авторами Marshmallow. + +/// + +/// check | "Идея для **FastAPI**" + +Необходима поддержка открытого стандарта для API - OpenAPI. -!!! check "Идея для **FastAPI**" - Необходима поддержка открытого стандарта для API - OpenAPI. +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -218,11 +246,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info "Информация" - Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. +/// info | "Информация" -!!! check "Идея для **FastAPI**" - Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. +Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. + +/// + +/// check | "Идея для **FastAPI**" + +Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (и <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) @@ -242,25 +276,34 @@ Marshmallow и Webargs осуществляют проверку, анализ Кроме того, он не очень хорошо справляется с вложенными моделями. Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено. -!!! check "Идеи для **FastAPI** " - Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. +/// check | "Идеи для **FastAPI** " + +Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. + +Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. - Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`. Он был сделан очень похожим на Flask. -!!! note "Технические детали" - В нём использован <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. +/// note | "Технические детали" - Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. +В нём использован <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. -!!! check "Идеи для **FastAPI**" - Должна быть сумасшедшая производительность. +Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. - Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). +/// + +/// check | "Идеи для **FastAPI**" + +Должна быть сумасшедшая производительность. + +Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -275,12 +318,15 @@ Falcon - ещё один высокопроизводительный Python-ф Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug. Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа. -!!! check "Идея для **FastAPI**" - Найдите способы добиться отличной производительности. +/// check | "Идея для **FastAPI**" + +Найдите способы добиться отличной производительности. + +Объявлять параметры `ответа сервера` в функциях, как в Hug. - Объявлять параметры `ответа сервера` в функциях, как в Hug. +Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. - Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -302,11 +348,14 @@ Molten мне попался на начальной стадии написан Это больше похоже на Django, чем на Flask и Starlette. Он разделяет в коде вещи, которые довольно тесно связаны. -!!! check "Идея для **FastAPI**" - Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". - Это улучшает помощь редактора и раньше это не было доступно в Pydantic. +/// check | "Идея для **FastAPI**" - Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). +Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". +Это улучшает помощь редактора и раньше это не было доступно в Pydantic. + +Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). + +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -325,15 +374,21 @@ Hug был одним из первых фреймворков, реализов Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью. -!!! info "Информация" - Hug создан Timothy Crosley, автором <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, отличного инструмента для автоматической сортировки импортов в Python-файлах. +/// info | "Информация" + +Hug создан Timothy Crosley, автором <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, отличного инструмента для автоматической сортировки импортов в Python-файлах. + +/// + +/// check | "Идеи для **FastAPI**" + +Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. -!!! check "Идеи для **FastAPI**" - Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. +Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. - Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. +Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. - Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5) @@ -363,24 +418,30 @@ Hug был одним из первых фреймворков, реализов Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI. -!!! info "Информация" - APIStar был создан Tom Christie. Тот самый парень, который создал: +/// info | "Информация" - * Django REST Framework - * Starlette (на котором основан **FastAPI**) - * Uvicorn (используемый в Starlette и **FastAPI**) +APIStar был создан Tom Christie. Тот самый парень, который создал: -!!! check "Идеи для **FastAPI**" - Воплощение. +* Django REST Framework +* Starlette (на котором основан **FastAPI**) +* Uvicorn (используемый в Starlette и **FastAPI**) - Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. +/// - После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. +/// check | "Идеи для **FastAPI**" - Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. - Это была последняя капля, сподвигнувшая на создание **FastAPI**. +Воплощение. - Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. +Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. + +После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. + +Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. +Это была последняя капля, сподвигнувшая на создание **FastAPI**. + +Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. + +/// ## Что используется в **FastAPI** @@ -391,10 +452,13 @@ Pydantic - это библиотека для валидации данных, Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow. И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода. -!!! check "**FastAPI** использует Pydantic" - Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). +/// check | "**FastAPI** использует Pydantic" + +Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). + +Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. - Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -424,19 +488,25 @@ Starlette обеспечивает весь функционал микрофр **FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic. Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д. -!!! note "Технические детали" - ASGI - это новый "стандарт" разработанный участниками команды Django. - Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. +/// note | "Технические детали" - Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. - Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. +ASGI - это новый "стандарт" разработанный участниками команды Django. +Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. -!!! check "**FastAPI** использует Starlette" - В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. +Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. +Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. - Класс `FastAPI` наследуется напрямую от класса `Starlette`. +/// - Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. +/// check | "**FastAPI** использует Starlette" + +В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. + +Класс `FastAPI` наследуется напрямую от класса `Starlette`. + +Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -448,12 +518,15 @@ Uvicorn является сервером, а не фреймворком. Он рекомендуется в качестве сервера для Starlette и **FastAPI**. -!!! check "**FastAPI** рекомендует его" - Как основной сервер для запуска приложения **FastAPI**. +/// check | "**FastAPI** рекомендует его" + +Как основной сервер для запуска приложения **FastAPI**. + +Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. - Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. +Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. - Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. +/// ## Тестовые замеры и скорость diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md index 20dbb108b..6c5d982df 100644 --- a/docs/ru/docs/async.md +++ b/docs/ru/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - `await` можно использовать только внутри функций, объявленных с использованием `async def`. +/// note + +`await` можно использовать только внутри функций, объявленных с использованием `async def`. + +/// --- @@ -444,14 +447,17 @@ Starlette (и **FastAPI**) основаны на <a href="https://anyio.readthed ## Очень технические подробности -!!! warning - Этот раздел читать не обязательно. +/// warning + +Этот раздел читать не обязательно. + +Здесь приводятся подробности внутреннего устройства **FastAPI**. - Здесь приводятся подробности внутреннего устройства **FastAPI**. +Но если вы обладаете техническими знаниями (корутины, потоки, блокировка и т. д.) +и вам интересно, как FastAPI обрабатывает `async def` в отличие от обычных `def`, +читайте дальше. - Но если вы обладаете техническими знаниями (корутины, потоки, блокировка и т. д.) - и вам интересно, как FastAPI обрабатывает `async def` в отличие от обычных `def`, - читайте дальше. +/// ### Функции обработки пути diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md index c87916312..c4370f9bb 100644 --- a/docs/ru/docs/contributing.md +++ b/docs/ru/docs/contributing.md @@ -24,63 +24,73 @@ $ python -m venv env Активируйте виртуально окружение командой: -=== "Linux, macOS" +//// tab | Linux, macOS - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` + +</div> - </div> +//// -=== "Windows PowerShell" +//// tab | Windows PowerShell + +<div class="termy"> + +```console +$ .\env\Scripts\Activate.ps1 +``` - <div class="termy"> +</div> - ```console - $ .\env\Scripts\Activate.ps1 - ``` +//// - </div> +//// tab | Windows Bash -=== "Windows Bash" +Если Вы пользуетесь Bash для Windows (например: <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): - Если Вы пользуетесь Bash для Windows (например: <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): +<div class="termy"> - <div class="termy"> +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +</div> - </div> +//// Проверьте, что всё сработало: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash + +<div class="termy"> + +```console +$ which pip - <div class="termy"> +some/directory/fastapi/env/bin/pip +``` - ```console - $ which pip +</div> - some/directory/fastapi/env/bin/pip - ``` +//// - </div> +//// tab | Windows PowerShell -=== "Windows PowerShell" +<div class="termy"> - <div class="termy"> +```console +$ Get-Command pip - ```console - $ Get-Command pip +some/directory/fastapi/env/bin/pip +``` - some/directory/fastapi/env/bin/pip - ``` +</div> - </div> +//// Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip </div> -!!! tip "Подсказка" - Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. +/// tip | "Подсказка" + +Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. + +Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. - Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. +/// ### pip @@ -149,9 +162,11 @@ $ bash scripts/format.sh Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`. -!!! tip "Подсказка" +/// tip | "Подсказка" - Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. +Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. + +/// Вся документация имеет формат Markdown и расположена в директории `./docs/en/`. @@ -239,10 +254,13 @@ $ uvicorn tutorial001:app --reload * Проверьте <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">существующие пул-реквесты</a> для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. -!!! tip "Подсказка" - Вы можете <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">добавлять комментарии с предложениями по изменению</a> в существующие пул-реквесты. +/// tip | "Подсказка" + +Вы можете <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">добавлять комментарии с предложениями по изменению</a> в существующие пул-реквесты. + +Ознакомьтесь с документацией о <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">добавлении отзыва к пул-реквесту</a>, чтобы утвердить его или запросить изменения. - Ознакомьтесь с документацией о <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">добавлении отзыва к пул-реквесту</a>, чтобы утвердить его или запросить изменения. +/// * Проверьте <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">проблемы и вопросы</a>, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. @@ -264,8 +282,11 @@ $ uvicorn tutorial001:app --reload Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`. -!!! tip "Подсказка" - Главный ("официальный") язык - английский, директория для него `docs/en/`. +/// tip | "Подсказка" + +Главный ("официальный") язык - английский, директория для него `docs/en/`. + +/// Вы можете запустить сервер документации на испанском: @@ -304,8 +325,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "Подсказка" - Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. +/// tip | "Подсказка" + +Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. + +/// * Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут: @@ -376,10 +400,13 @@ Updating en После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`. -!!! tip "Подсказка" - Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. +/// tip | "Подсказка" + +Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. + +Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 - Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 +/// Начните перевод с главной страницы `docs/ht/index.md`. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index 26db356c1..c41025790 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -151,10 +151,13 @@ Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз... -!!! tip "Заметка" - ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. +/// tip | "Заметка" - Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. +... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. + +Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. + +/// Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе. @@ -238,10 +241,13 @@ * **Облачные сервисы**, которые позаботятся обо всём за Вас * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. -!!! tip "Заметка" - Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. +/// tip | "Заметка" + +Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. + +Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. - Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. +/// ## Шаги, предшествующие запуску @@ -257,10 +263,13 @@ Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще. -!!! tip "Заметка" - Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. +/// tip | "Заметка" - Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 +Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. + +Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 + +/// ### Примеры стратегий запуска предварительных шагов @@ -272,8 +281,11 @@ * Bash-скрипт, выполняющий предварительные шаги, а затем запускающий приложение. * При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п. -!!! tip "Заметка" - Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. +/// tip | "Заметка" + +Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. + +/// ## Утилизация ресурсов diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index ce4972c4f..e627d01fe 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -4,8 +4,11 @@ Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие. -!!! tip "Подсказка" - Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) +/// tip | "Подсказка" + +Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) + +/// <details> <summary>Развернуть Dockerfile 👀</summary> @@ -132,10 +135,13 @@ Successfully installed fastapi pydantic uvicorn </div> -!!! info "Информация" - Существуют и другие инструменты управления зависимостями. +/// info | "Информация" + +Существуют и другие инструменты управления зависимостями. - В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇 +В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇 + +/// ### Создать приложение **FastAPI** @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 +/// tip | "Подсказка" + +Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 + +/// На данном этапе структура проекта должны выглядеть так: @@ -294,10 +303,13 @@ $ docker build -t myimage . </div> -!!! tip "Подсказка" - Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. +/// tip | "Подсказка" + +Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. + +В данном случае это та же самая директория (`.`). - В данном случае это та же самая директория (`.`). +/// ### Запуск Docker-контейнера @@ -395,8 +407,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это может быть другой контейнер, в котором есть, например, <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**. -!!! tip "Подсказка" - Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. +/// tip | "Подсказка" + +Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. + +/// В качестве альтернативы, работу с HTTPS можно доверить облачному провайдеру, если он предоставляет такую услугу. @@ -424,8 +439,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**. -!!! tip "Подсказка" - **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. +/// tip | "Подсказка" + +**Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. + +/// Система оркестрации, которую вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). @@ -504,8 +522,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). -!!! info "Информация" - При использовании Kubernetes, это может быть <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Инициализирующий контейнер</a>. +/// info | "Информация" + +При использовании Kubernetes, это может быть <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Инициализирующий контейнер</a>. + +/// При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. @@ -521,8 +542,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. -!!! warning "Предупреждение" - Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). +/// warning | "Предупреждение" + +Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). + +/// В этом образе есть **автоматический** механизм подстройки для запуска **необходимого количества процессов** в соответствии с доступным количеством ядер процессора. @@ -530,8 +554,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Он также поддерживает прохождение <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**Подготовительных шагов при запуске контейнеров**</a> при помощи скрипта. -!!! tip "Подсказка" - Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +/// tip | "Подсказка" + +Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. + +/// ### Количество процессов в официальном Docker-образе @@ -659,8 +686,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. +/// tip | "Подсказка" + +Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. + +/// **Этапы сборки Docker-образа** являются частью `Dockerfile` и работают как **временные образы контейнеров**. Они нужны только для создания файлов, используемых в дальнейших этапах. diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index 5aa300331..3d487c465 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -4,8 +4,11 @@ Но всё несколько сложнее. -!!! tip "Заметка" - Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. +/// tip | "Заметка" + +Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. + +/// Чтобы **изучить основы HTTPS** для клиента, перейдите по ссылке <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>. @@ -75,8 +78,11 @@ Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера. -!!! tip "Заметка" - Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. +/// tip | "Заметка" + +Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. + +/// ### DNS @@ -122,8 +128,11 @@ DNS-сервера присылают браузеру определённый Таким образом, **HTTPS** это тот же **HTTP**, но внутри **безопасного TLS-соединения** вместо чистого (незашифрованного) TCP-соединения. -!!! tip "Заметка" - Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. +/// tip | "Заметка" + +Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. + +/// ### HTTPS-запрос diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index 0b24c0695..78363cef8 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -25,76 +25,89 @@ Вы можете установить сервер, совместимый с протоколом ASGI, так: -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools. +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools. - <div class="termy"> +<div class="termy"> - ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` - </div> +</div> + +/// tip | "Подсказка" - !!! tip "Подсказка" - С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. +С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. - В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. +В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. -=== "Hypercorn" +/// - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ASGI сервер, поддерживающий протокол HTTP/2. +//// - <div class="termy"> +//// tab | Hypercorn - ```console - $ pip install hypercorn +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ASGI сервер, поддерживающий протокол HTTP/2. - ---> 100% - ``` +<div class="termy"> - </div> +```console +$ pip install hypercorn + +---> 100% +``` + +</div> - ...или какой-либо другой ASGI сервер. +...или какой-либо другой ASGI сервер. + +//// ## Запуск серверной программы Затем запустите ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: -=== "Uvicorn" +//// tab | Uvicorn + +<div class="termy"> + +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - <div class="termy"> +</div> - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn - </div> +<div class="termy"> -=== "Hypercorn" +```console +$ hypercorn main:app --bind 0.0.0.0:80 - <div class="termy"> +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +</div> - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +//// - </div> +/// warning | "Предупреждение" -!!! warning "Предупреждение" +Не забудьте удалить опцию `--reload`, если ранее пользовались ею. - Не забудьте удалить опцию `--reload`, если ранее пользовались ею. +Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. - Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. +Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. - Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. +/// ## Hypercorn с Trio diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md index f410e3936..17b6446d9 100644 --- a/docs/ru/docs/deployment/versions.md +++ b/docs/ru/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений. -!!! tip "Подсказка" - "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. +/// tip | "Подсказка" + +"ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. + +/// Итак, вы можете закрепить версию следующим образом: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии. -!!! tip "Подсказка" - "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. +/// tip | "Подсказка" + +"МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. + +/// ## Обновление версий FastAPI diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md index 0a4cda27b..2c0e153e2 100644 --- a/docs/ru/docs/external-links.md +++ b/docs/ru/docs/external-links.md @@ -6,8 +6,11 @@ Вот неполный список некоторых из них. -!!! tip - Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>. +/// tip + +Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index baa4ec778..31f245e7a 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -66,10 +66,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "Информация" - `**second_user_data` означает: +/// info | "Информация" - Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . +`**second_user_data` означает: + +Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . + +/// ### Поддержка редакторов (IDE) diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index b007437bc..fa8200817 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -162,12 +162,15 @@ * Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код. -!!! info "Информация" - К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. +/// info | "Информация" - Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 +К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. - Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 +Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 + +Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 + +/// * Если Вы считаете, что пул-реквест можно упростить, то можете попросить об этом, но не нужно быть слишком придирчивым, может быть много субъективных точек зрения (и у меня тоже будет своя 🙈), поэтому будет лучше, если Вы сосредоточитесь на фундаментальных вещах. @@ -218,10 +221,13 @@ Подключайтесь к 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank"> чату в Discord</a> 👥 и общайтесь с другими участниками сообщества FastAPI. -!!! tip "Подсказка" - Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. +/// tip | "Подсказка" + +Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. + +Используйте этот чат только для бесед на отвлечённые темы. - Используйте этот чат только для бесед на отвлечённые темы. +/// ### Не использовать чаты для вопросов diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index 3c8492c67..c052bc675 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -12,8 +12,11 @@ Python имеет поддержку необязательных аннотац Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них. -!!! note - Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. +/// note + +Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. + +/// ## Мотивация @@ -172,10 +175,13 @@ John Doe {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip - Эти внутренние типы в квадратных скобках называются «параметрами типов». +/// tip + +Эти внутренние типы в квадратных скобках называются «параметрами типов». + +В этом случае `str` является параметром типа, передаваемым в `List`. - В этом случае `str` является параметром типа, передаваемым в `List`. +/// Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`". @@ -281,8 +287,11 @@ John Doe {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Чтобы узнать больше о <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, читайте его документацию</a>. +/// info + +Чтобы узнать больше о <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, читайте его документацию</a>. + +/// **FastAPI** целиком основан на Pydantic. @@ -310,5 +319,8 @@ John Doe Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы. -!!! info - Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">«шпаргалка» от `mypy`</a>. +/// info + +Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">«шпаргалка» от `mypy`</a>. + +/// diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 73ba860bc..073276848 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -57,17 +57,21 @@ **FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index 02a598004..f4db0e9ff 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -6,50 +6,67 @@ Сначала вы должны импортировать его: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// tab | Python 3.8+ -!!! warning "Внимание" - Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "Внимание" + +Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). + +/// ## Объявление атрибутов модели Вы можете использовать функцию `Field` с атрибутами модели: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. -!!! note "Технические детали" - На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. +/// note | "Технические детали" - И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. +На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. - У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. +И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. - Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. -!!! tip "Подсказка" - Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. +Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. + +/// + +/// tip | "Подсказка" + +Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. + +/// ## Добавление дополнительной информации @@ -58,9 +75,12 @@ Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных. -!!! warning "Внимание" - Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. - Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. +/// warning | "Внимание" + +Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. +Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. + +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index ffba1d0f4..107e6293b 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip | "Заметка" + +Рекомендуется использовать `Annotated` версию, если это возможно. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Заметка" - Рекомендуется использовать версию с `Annotated`, если это возможно. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip | "Заметка" -!!! note "Заметка" - Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note | "Заметка" + +Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. + +/// ## Несколько параметров тела запроса @@ -62,17 +81,21 @@ Но вы также можете объявить множество параметров тела запроса, например `item` и `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic). @@ -93,9 +116,11 @@ } ``` -!!! note "Внимание" - Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// note | "Внимание" + +Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// **FastAPI** сделает автоматические преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`. @@ -111,41 +136,57 @@ Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// tip | "Заметка" -=== "Python 3.8+" +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Заметка" - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +/// + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +//// В этом случае, **FastAPI** будет ожидать тело запроса в формате: @@ -185,44 +226,63 @@ q: str | None = None Например: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | "Заметка" + +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +/// tip | "Заметка" -=== "Python 3.10+ non-Annotated" +Рекомендуется использовать `Annotated` версию, если это возможно. - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +/// - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +/// info | "Информация" - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. -!!! info "Информация" - `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. +/// ## Добавление одного body-параметра @@ -238,41 +298,57 @@ item: Item = Body(embed=True) так же, как в этом примере: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip | "Заметка" -=== "Python 3.9+" +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +/// tip | "Заметка" - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Рекомендуется использовать `Annotated` версию, если это возможно. -=== "Python 3.8+ non-Annotated" +/// - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// В этом случае **FastAPI** будет ожидать тело запроса в формате: diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 51a32ba56..ecb8b92a7 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ Вы можете определять атрибут как подтип. Например, тип `list` в Python: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен. @@ -61,23 +65,29 @@ my_list: List[str] Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк": -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Типы множеств @@ -87,23 +97,29 @@ my_list: List[str] Тогда мы можем обьявить поле `tags` как множество строк: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов. @@ -125,45 +141,57 @@ my_list: List[str] Например, мы можем определить модель `Image`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### Использование вложенной модели в качестве типа Также мы можем использовать эту модель как тип атрибута: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому: @@ -196,23 +224,29 @@ my_list: List[str] Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI. @@ -220,23 +254,29 @@ my_list: List[str] Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате: @@ -264,33 +304,45 @@ my_list: List[str] } ``` -!!! info "Информация" - Заметьте, что теперь у ключа `images` есть список объектов изображений. +/// info | "Информация" + +Заметьте, что теперь у ключа `images` есть список объектов изображений. + +/// ## Глубоко вложенные модели Вы можете определять модели с произвольным уровнем вложенности: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info | "Информация" - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` -!!! info "Информация" - Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` +/// ## Тела с чистыми списками элементов @@ -308,17 +360,21 @@ images: list[Image] например так: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## Универсальная поддержка редактора @@ -348,26 +404,33 @@ images: list[Image] В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip | "Совет" - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Имейте в виду, что JSON поддерживает только ключи типа `str`. -!!! tip "Совет" - Имейте в виду, что JSON поддерживает только ключи типа `str`. +Но Pydantic обеспечивает автоматическое преобразование данных. - Но Pydantic обеспечивает автоматическое преобразование данных. +Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. - Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. +А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. - А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index 4998ab31a..c458329d8 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +//// `PUT` используется для получения данных, которые должны полностью заменить существующие данные. @@ -48,14 +54,17 @@ Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми. -!!! note "Технические детали" - `PATCH` менее распространен и известен, чем `PUT`. +/// note | "Технические детали" + +`PATCH` менее распространен и известен, чем `PUT`. + +А многие команды используют только `PUT`, даже для частичного обновления. - А многие команды используют только `PUT`, даже для частичного обновления. +Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. - Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. +Но в данном руководстве более или менее понятно, как они должны использоваться. - Но в данном руководстве более или менее понятно, как они должны использоваться. +/// ### Использование параметра `exclude_unset` в Pydantic @@ -65,23 +74,29 @@ В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// ### Использование параметра `update` в Pydantic @@ -89,23 +104,29 @@ Например, `stored_item_model.copy(update=update_data)`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | Python 3.9+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// ### Кратко о частичном обновлении @@ -122,32 +143,44 @@ * Сохранить данные в своей БД. * Вернуть обновленную модель. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +Эту же технику можно использовать и для операции HTTP `PUT`. -=== "Python 3.6+" +Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +/// -!!! tip "Подсказка" - Эту же технику можно использовать и для операции HTTP `PUT`. +/// note | "Технические детали" - Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. +Обратите внимание, что входная модель по-прежнему валидируется. -!!! note "Технические детали" - Обратите внимание, что входная модель по-прежнему валидируется. +Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). - Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). +Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. - Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 5d0e033fd..c3e6326da 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -8,12 +8,15 @@ Чтобы объявить тело **запроса**, необходимо использовать модели <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, со всей их мощью и преимуществами. -!!! info "Информация" - Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. +/// info | "Информация" - Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. +Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. - Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. +Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. + +Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. + +/// ## Импортирование `BaseModel` из Pydantic @@ -110,16 +113,19 @@ <img src="/img/tutorial/body/image05.png"> -!!! tip "Подсказка" - Если вы используете <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> в качестве редактора, то вам стоит попробовать плагин <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. +/// tip | "Подсказка" + +Если вы используете <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> в качестве редактора, то вам стоит попробовать плагин <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. - Он улучшает поддержку редактором моделей Pydantic в части: +Он улучшает поддержку редактором моделей Pydantic в части: - * автодополнения, - * проверки типов, - * рефакторинга, - * поиска, - * инспектирования. +* автодополнения, +* проверки типов, +* рефакторинга, +* поиска, +* инспектирования. + +/// ## Использование модели @@ -155,10 +161,13 @@ * Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**. * Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**. -!!! note "Заметка" - FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. +/// note | "Заметка" + +FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. + +Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. - Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. +/// ## Без Pydantic diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 5f99458b6..e88b9d7ee 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -6,17 +6,21 @@ Сначала импортируйте `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Объявление параметров `Cookie` @@ -24,25 +28,35 @@ Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +/// note | "Технические детали" - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. -=== "Python 3.8+" +Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Технические детали" - `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. +/// info | "Дополнительная информация" - Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. -!!! info "Дополнительная информация" - Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 8c7fbc046..852833208 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -78,7 +78,10 @@ Для получения более подробной информации о <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, обратитесь к <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Документации CORS от Mozilla</a>. -!!! note "Технические детали" - Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. +/// note | "Технические детали" - **FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. +Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. + +/// diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 5fc6a2c1f..685fb7356 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app не будет выполнена. -!!! info "Информация" - Для получения дополнительной информации, ознакомьтесь с <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">официальной документацией Python</a>. +/// info | "Информация" + +Для получения дополнительной информации, ознакомьтесь с <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">официальной документацией Python</a>. + +/// ## Запуск вашего кода с помощью отладчика diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index b6ad25daf..d0471baca 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ В предыдущем примере мы возвращали `словарь` из нашей зависимости: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.10+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. @@ -101,117 +117,165 @@ fluffy = Cat(name="Mr Fluffy") Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.6+" +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.10+ без Annotated" +```Python hl_lines="12-16" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +/// + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.6+" +/// - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.6+ без Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...имеет те же параметры, что и ранее используемая функция `common_parameters`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. @@ -227,41 +291,57 @@ fluffy = Cat(name="Mr Fluffy") Теперь вы можете объявить свою зависимость, используя этот класс. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. @@ -269,20 +349,27 @@ fluffy = Cat(name="Mr Fluffy") Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`: -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// Последний параметр `CommonQueryParams`, в: @@ -298,77 +385,107 @@ fluffy = Cat(name="Mr Fluffy") В этом случае первый `CommonQueryParams`, в: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python - commons: CommonQueryParams ... - ``` +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`). На самом деле можно написать просто: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python - commons = Depends(CommonQueryParams) - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// ...как тут: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` + +//// Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: @@ -378,101 +495,141 @@ fluffy = Cat(name="Mr Fluffy") Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`: -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись. Вместо того чтобы писать: -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ...следует написать: -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` -=== "Python 3.6 без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.6 без Annotated - ```Python - commons: CommonQueryParams = Depends() - ``` +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`. Аналогичный пример будет выглядеть следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.9+" +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` + +//// ...и **FastAPI** будет знать, что делать. -!!! tip "Подсказка" - Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. +/// tip | "Подсказка" + +Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. + +Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. - Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. +/// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 2bd096189..11df4b474 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,40 +14,55 @@ Это должен быть `list` состоящий из `Depends()`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 без Annotated" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 без Annotated + +/// подсказка + +Рекомендуется использовать версию с Annotated, если возможно. + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. -!!! Подсказка - Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. +/// подсказка + +Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. - Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов. +Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов. - Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости. +Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости. -!!! Дополнительная информация - В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. +/// - Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}. +/// дополнительная | информация + +В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. + +Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}. + +/// ## Исключения в dependencies и возвращаемые значения @@ -57,51 +72,69 @@ Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 без Annotated -=== "Python 3.8 без Annotated" +/// подсказка - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +Рекомендуется использовать версию с Annotated, если возможно. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Вызов исключений Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 без Annotated - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// подсказка -=== "Python 3.8 без Annotated" +Рекомендуется использовать версию с Annotated, если возможно. - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Возвращаемые значения @@ -109,26 +142,35 @@ Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 без Annotated -=== "Python 3.8+" +/// подсказка - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +Рекомендуется использовать версию с Annotated, если возможно. -=== "Python 3.8 без Annotated" +/// - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## Dependencies для группы *операций путей* diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index cd524cf66..ece7ef8e3 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI поддерживает зависимости, которые выпо Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него. -!!! tip "Подсказка" - Обязательно используйте `yield` один-единственный раз. +/// tip | "Подсказка" -!!! note "Технические детали" - Любая функция, с которой может работать: +Обязательно используйте `yield` один-единственный раз. - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +/// - будет корректно использоваться в качестве **FastAPI**-зависимости. +/// note | "Технические детали" - На самом деле, FastAPI использует эту пару декораторов "под капотом". +Любая функция, с которой может работать: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> + +будет корректно использоваться в качестве **FastAPI**-зависимости. + +На самом деле, FastAPI использует эту пару декораторов "под капотом". + +/// ## Зависимость базы данных с помощью `yield` @@ -39,10 +45,13 @@ FastAPI поддерживает зависимости, которые выпо {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip "Подсказка" - Можно использовать как `async` так и обычные функции. +/// tip | "Подсказка" + +Можно использовать как `async` так и обычные функции. - **FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями. +**FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями. + +/// ## Зависимость с `yield` и `try` одновременно @@ -66,26 +75,35 @@ FastAPI поддерживает зависимости, которые выпо Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 14 22" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` - ```Python hl_lines="6 14 22" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python hl_lines="5 13 21" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` - ```Python hl_lines="5 13 21" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="4 12 20" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="4 12 20" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` + +//// И все они могут использовать `yield`. @@ -93,26 +111,35 @@ FastAPI поддерживает зависимости, которые выпо И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +```Python hl_lines="18-19 26-27" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="17-18 25-26" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +/// + +```Python hl_lines="16-17 24-25" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` + +//// Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. @@ -122,8 +149,11 @@ FastAPI поддерживает зависимости, которые выпо **FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке. -!!! note "Технические детали" - Это работает благодаря <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Контекстным менеджерам</a> в Python. +/// note | "Технические детали" + +Это работает благодаря <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Контекстным менеджерам</a> в Python. + +/// **FastAPI** использует их "под капотом" с этой целью. @@ -147,8 +177,11 @@ FastAPI поддерживает зависимости, которые выпо Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. -!!! tip "Подсказка" - Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. +/// tip | "Подсказка" + +Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. + +/// Последовательность выполнения примерно такая, как на этой схеме. Время течет сверху вниз. А каждый столбец - это одна из частей, взаимодействующих с кодом или выполняющих код. @@ -192,22 +225,31 @@ participant tasks as Background tasks end ``` -!!! info "Дополнительная информация" - Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. +/// info | "Дополнительная информация" + +Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. + +После отправки одного из этих ответов никакой другой ответ не может быть отправлен. - После отправки одного из этих ответов никакой другой ответ не может быть отправлен. +/// -!!! tip "Подсказка" - На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. +/// tip | "Подсказка" - Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка. +На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка. + +/// ## Зависимости с `yield`, `HTTPException` и фоновыми задачами -!!! warning "Внимание" - Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. +/// warning | "Внимание" + +Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. - Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах. +Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах. + +/// До версии FastAPI 0.106.0 вызывать исключения после `yield` было невозможно, код выхода в зависимостях с `yield` выполнялся *после* отправки ответа, поэтому [Обработчик Ошибок](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже был бы запущен. @@ -215,10 +257,12 @@ participant tasks as Background tasks Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0. -!!! tip "Подсказка" +/// tip | "Подсказка" + +Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). +Таким образом, вы, вероятно, получите более чистый код. - Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). - Таким образом, вы, вероятно, получите более чистый код. +/// Если вы полагались на это поведение, то теперь вам следует создавать ресурсы для фоновых задач внутри самой фоновой задачи, а внутри использовать только те данные, которые не зависят от ресурсов зависимостей с `yield`. @@ -246,10 +290,13 @@ with open("./somefile.txt") as f: ### Использование менеджеров контекста в зависимостях с помощью `yield` -!!! warning "Внимание" - Это более или менее "продвинутая" идея. +/// warning | "Внимание" - Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт. +Это более или менее "продвинутая" идея. + +Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт. + +/// В Python для создания менеджеров контекста можно <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">создать класс с двумя методами: `__enter__()` и `__exit__()`</a>. @@ -260,16 +307,19 @@ with open("./somefile.txt") as f: {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip "Подсказка" - Другой способ создания контекстного менеджера - с помощью: +/// tip | "Подсказка" + +Другой способ создания контекстного менеджера - с помощью: + +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +используйте их для оформления функции с одним `yield`. - используйте их для оформления функции с одним `yield`. +Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`. - Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`. +Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит). - Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит). +FastAPI сделает это за вас на внутреннем уровне. - FastAPI сделает это за вас на внутреннем уровне. +/// diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index eb1b4d7c1..9e03e3723 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ В этом случае они будут применяться ко всем *операциям пути* в приложении: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 non-Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать 'Annotated' версию, если это возможно. + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial012.py!} +``` + +//// Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index 9fce46b97..b244b3fdc 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -29,42 +29,57 @@ Давайте для начала сфокусируемся на зависимостях. Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Подсказка" +/// tip | "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +/// + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// **И всё.** @@ -84,91 +99,125 @@ И в конце она возвращает `dict`, содержащий эти значения. -!!! info "Информация" +/// info | "Информация" + +**FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. - **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. + Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. - Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. +Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. - Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. +/// ### Import `Depends` -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +//// - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### Объявите зависимость в "зависимом" Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// `Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. @@ -176,8 +225,11 @@ И потом функция берёт параметры так же, как *функция обработки пути*. -!!! tip "Подсказка" - В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. +/// tip | "Подсказка" + +В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. + +/// Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о: @@ -198,10 +250,13 @@ common_parameters --> read_users Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. -!!! check "Проверка" - Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. +/// check | "Проверка" + +Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. + +Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. - Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. +/// ## Объединяем с `Annotated` зависимостями @@ -215,29 +270,37 @@ commons: Annotated[dict, Depends(common_parameters)] Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +//// -!!! tip "Подсказка" - Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. +//// tab | Python 3.8+ - Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` +//// + +/// tip | "Подсказка" + +Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. + +Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 + +/// Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`. @@ -253,8 +316,11 @@ commons: Annotated[dict, Depends(common_parameters)] Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 -!!! note "Информация" - Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. +/// note | "Информация" + +Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. + +/// ## Интеграция с OpenAPI diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index 31f9f43c6..332470396 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -10,41 +10,57 @@ Можно создать первую зависимость следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +//// + +//// tab | Python 3.6+ + +```Python hl_lines="9-10" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` -=== "Python 3.6+" +//// + +//// tab | Python 3.10 без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="9-10" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 без Annotated" +//// tab | Python 3.6 без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6 без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. @@ -54,41 +70,57 @@ Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="14" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 без Annotated - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.9+" +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.6+" +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 без Annotated" +//// tab | Python 3.6 без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6 без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Остановимся на объявленных параметрах: @@ -101,46 +133,65 @@ Затем мы можем использовать зависимость вместе с: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="24" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10 без Annotated -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "Python 3.10 без Annotated" +//// tab | Python 3.6 без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6 без Annotated" +/// + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +/// info | "Дополнительная информация" -!!! info "Дополнительная информация" - Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. +Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. - Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове. +Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове. + +/// ```mermaid graph TB @@ -161,22 +212,29 @@ query_extractor --> query_or_cookie_extractor --> read_query В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` - ```Python hl_lines="1" - async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): - return {"fresh_value": fresh_value} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="1" - async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): - return {"fresh_value": fresh_value} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// ## Резюме @@ -186,9 +244,12 @@ query_extractor --> query_or_cookie_extractor --> read_query Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко. -!!! tip "Подсказка" - Все это может показаться не столь полезным на этих простых примерах. +/// tip | "Подсказка" + +Все это может показаться не столь полезным на этих простых примерах. + +Но вы увидите как это пригодится в главах посвященных безопасности. - Но вы увидите как это пригодится в главах посвященных безопасности. +И вы также увидите, сколько кода это вам сэкономит. - И вы также увидите, сколько кода это вам сэкономит. +/// diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index c26b2c941..02c3587f3 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. @@ -38,5 +42,8 @@ Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON. -!!! note "Технические детали" - `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. +/// note | "Технические детали" + +`jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. + +/// diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index d4727e2d4..2650bb0af 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -55,28 +55,36 @@ Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -=== "Python 3.8 и выше" +//// tab | Python 3.8 и выше - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` -=== "Python 3.10 и выше" +//// - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 и выше + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -=== "Python 3.8 и выше" +//// tab | Python 3.8 и выше + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// tab | Python 3.10 и выше -=== "Python 3.10 и выше" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 78855313d..2aac76aa3 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ * **Модель для вывода** не должна содержать пароль. * **Модель для базы данных**, возможно, должна содержать хэшированный пароль. -!!! danger "Внимание" - Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. +/// danger | "Внимание" - Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. + +Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// ## Множественные модели Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` + +//// ### Про `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning "Предупреждение" - Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. +/// warning | "Предупреждение" + +Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. + +/// ## Сократите дублирование @@ -158,17 +168,21 @@ UserInDB( В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` или `anyOf` @@ -178,20 +192,27 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: -!!! note "Примечание" - При объявлении <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. +/// note | "Примечание" + +При объявлении <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. -=== "Python 3.10+" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.8+" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ### `Union` в Python 3.10 @@ -213,17 +234,21 @@ some_variable: PlaneItem | CarItem Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше): -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` + +//// ## Ответ с произвольным `dict` @@ -233,17 +258,21 @@ some_variable: PlaneItem | CarItem В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` + +//// - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index 8a0876bb4..e60d58823 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note "Технические детали" - Команда `uvicorn main:app` обращается к: +/// note | "Технические детали" - * `main`: файл `main.py` (модуль Python). - * `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. - * `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. +Команда `uvicorn main:app` обращается к: + +* `main`: файл `main.py` (модуль Python). +* `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. +* `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. + +/// В окне вывода появится следующая строка: @@ -136,10 +139,13 @@ OpenAPI описывает схему API. Эта схема содержит о `FastAPI` это класс в Python, который предоставляет всю функциональность для API. -!!! note "Технические детали" - `FastAPI` это класс, который наследуется непосредственно от `Starlette`. +/// note | "Технические детали" + +`FastAPI` это класс, который наследуется непосредственно от `Starlette`. - Вы можете использовать всю функциональность <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> в `FastAPI`. +Вы можете использовать всю функциональность <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> в `FastAPI`. + +/// ### Шаг 2: создайте экземпляр `FastAPI` @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Дополнительная иформация" - Термин "path" также часто называется "endpoint" или "route". +/// info | "Дополнительная иформация" + +Термин "path" также часто называется "endpoint" или "route". + +/// При создании API, "путь" является основным способом разделения "задач" и "ресурсов". @@ -250,16 +259,19 @@ https://example.com/items/foo * путь `/` * использующих <abbr title="HTTP GET метод"><code>get</code> операцию</abbr> -!!! info "`@decorator` Дополнительная информация" - Синтаксис `@something` в Python называется "декоратор". +/// info | "`@decorator` Дополнительная информация" - Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). +Синтаксис `@something` в Python называется "декоратор". - "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. +Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). - В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. +"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. - Это и есть "**декоратор операции пути**". +В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. + +Это и есть "**декоратор операции пути**". + +/// Можно также использовать операции: @@ -274,14 +286,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip "Подсказка" - Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. +/// tip | "Подсказка" + +Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. - **FastAPI** не навязывает определенного значения для каждого метода. +**FastAPI** не навязывает определенного значения для каждого метода. - Информация здесь представлена как рекомендация, а не требование. +Информация здесь представлена как рекомендация, а не требование. - Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. +Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. + +/// ### Шаг 4: определите **функцию операции пути** @@ -309,8 +324,11 @@ https://example.com/items/foo {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Технические детали" - Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. +/// note | "Технические детали" + +Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. + +/// ### Шаг 5: верните результат diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index 40b6f9bc4..028f3e0d2 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ } ``` -!!! tip "Подсказка" - При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. +/// tip | "Подсказка" - Вы можете передать `dict`, `list` и т.д. +При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. - Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. +Вы можете передать `dict`, `list` и т.д. + +Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. + +/// ## Добавление пользовательских заголовков @@ -106,10 +109,13 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Технические детали" - Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. +/// note | "Технические детали" + +Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. +/// ## Переопределение стандартных обработчиков исключений @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` или `ValidationError` -!!! warning "Внимание" - Это технические детали, которые можно пропустить, если они не важны для вас сейчас. +/// warning | "Внимание" + +Это технические детали, которые можно пропустить, если они не важны для вас сейчас. + +/// `RequestValidationError` является подклассом Pydantic <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>. @@ -183,10 +192,13 @@ path -> item_id {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Технические детали" - Можно также использовать `from starlette.responses import PlainTextResponse`. +/// note | "Технические детали" + +Можно также использовать `from starlette.responses import PlainTextResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. +/// ### Используйте тело `RequestValidationError` diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 1be4ac707..3b5e38328 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ Сперва импортируйте `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// ## Объявление параметров `Header` @@ -48,49 +64,71 @@ Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -!!! note "Технические детали" - `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. +/// - Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` -!!! info "Дополнительная информация" - Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. +//// + +/// note | "Технические детали" + +`Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. + +Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. + +/// + +/// info | "Дополнительная информация" + +Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. + +/// ## Автоматическое преобразование @@ -108,44 +146,63 @@ Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11" +{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/header_params/tutorial002_an.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -!!! warning "Внимание" - Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. +/// + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` + +//// + +/// warning | "Внимание" + +Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. + +/// ## Повторяющиеся заголовки @@ -157,50 +214,71 @@ Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ без Annotated" +//// tab | Python 3.9+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: diff --git a/docs/ru/docs/tutorial/index.md b/docs/ru/docs/tutorial/index.md index ea3a1c37a..4cf45c0ed 100644 --- a/docs/ru/docs/tutorial/index.md +++ b/docs/ru/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код. -!!! note "Технические детали" - Вы также можете установить его по частям. +/// note | "Технические детали" - Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: +Вы также можете установить его по частям. - ``` - pip install fastapi - ``` +Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: - Также установите `uvicorn` для работы в качестве сервера: +``` +pip install fastapi +``` + +Также установите `uvicorn` для работы в качестве сервера: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. - И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. +/// ## Продвинутое руководство пользователя diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 0c6940d0e..9799fe538 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -21,8 +21,11 @@ {!../../../docs_src/metadata/tutorial001.py!} ``` -!!! tip "Подсказка" - Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. +/// tip | "Подсказка" + +Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. + +/// С этой конфигурацией автоматическая документация API будут выглядеть так: @@ -54,8 +57,11 @@ Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). -!!! tip "Подсказка" - Вам необязательно добавлять метаданные для всех используемых тегов +/// tip | "Подсказка" + +Вам необязательно добавлять метаданные для всех используемых тегов + +/// ### Используйте собственные теги Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: @@ -64,8 +70,11 @@ {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info "Дополнительная информация" - Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. +/// info | "Дополнительная информация" + +Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. + +/// ### Проверьте документацию diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index db99409f4..26b1726ad 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки. -!!! warning "Внимание" - Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. +/// warning | "Внимание" + +Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. + +/// ## Коды состояния @@ -13,52 +16,67 @@ Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. -!!! note "Технические детали" - Вы также можете использовать `from starlette import status`. +/// note | "Технические детали" + +Вы также можете использовать `from starlette import status`. + +**FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. - **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. +/// ## Теги Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса: @@ -80,23 +98,29 @@ Вы можете добавить параметры `summary` и `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// ## Описание из строк документации @@ -104,23 +128,29 @@ Вы можете использовать <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// Он будет использован в интерактивной документации: @@ -130,31 +160,43 @@ Вы можете указать описание ответа с помощью параметра `response_description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+" +/// info | "Дополнительная информация" - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check | "Технические детали" -!!! info "Дополнительная информация" - Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. +OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. -!!! check "Технические детали" - OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. +Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". - Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". +/// <img src="/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index 0baf51fa9..ced12c826 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// info | "Информация" - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). -!!! info "Информация" - Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). +Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. - Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. +Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. - Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. +/// ## Определите метаданные @@ -55,53 +74,75 @@ Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -!!! note "Примечание" - Path-параметр всегда является обязательным, поскольку он составляет часть пути. +/// - Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note | "Примечание" + +Path-параметр всегда является обязательным, поскольку он составляет часть пути. + +Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. + +Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. + +/// ## Задайте нужный вам порядок параметров -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// tip | "Подсказка" + +Это не имеет большого значения, если вы используете `Annotated`. + +/// Допустим, вы хотите объявить query-параметр `q` как обязательный параметр типа `str`. @@ -117,33 +158,45 @@ Поэтому вы можете определить функцию так: -=== "Python 3.8 без Annotated" +//// tab | Python 3.8 без Annotated + +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` + +//// ## Задайте нужный вам порядок параметров, полезные приёмы -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// tip | "Подсказка" + +Это не имеет большого значения, если вы используете `Annotated`. + +/// Здесь описан **небольшой приём**, который может оказаться удобным, хотя часто он вам не понадобится. @@ -168,17 +221,21 @@ Python не будет ничего делать с `*`, но он будет з Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Валидация числовых данных: больше или равно @@ -186,26 +243,35 @@ Python не будет ничего делать с `*`, но он будет з В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual"). -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Валидация числовых данных: больше и меньше или равно @@ -214,26 +280,35 @@ Python не будет ничего делать с `*`, но он будет з * `gt`: больше (`g`reater `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Валидация числовых данных: числа с плавающей точкой, больше и меньше @@ -245,26 +320,35 @@ Python не будет ничего делать с `*`, но он будет з То же самое справедливо и для <abbr title="less than"><code>lt</code></abbr>. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Резюме @@ -277,16 +361,22 @@ Python не будет ничего делать с `*`, но он будет з * `lt`: меньше (`l`ess `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -!!! info "Информация" - `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. +/// info | "Информация" + +`Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. + +Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. + +/// + +/// note | "Технические детали" - Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. +`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. -!!! note "Технические детали" - `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. +Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. - Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. +Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. - Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. +Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. - Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. +/// diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index 1241e0919..dc3d64af4 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Здесь, `item_id` объявлен типом `int`. -!!! check "Заметка" - Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). +/// check | "Заметка" + +Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). + +/// ## <abbr title="Или сериализация, парсинг">Преобразование</abbr> данных @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check "Заметка" - Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. +/// check | "Заметка" + +Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. + +Используя определения типов, **FastAPI** выполняет автоматический <abbr title="преобразование строк из HTTP-запроса в типы данных Python">"парсинг"</abbr> запросов. - Используя определения типов, **FastAPI** выполняет автоматический <abbr title="преобразование строк из HTTP-запроса в типы данных Python">"парсинг"</abbr> запросов. +/// ## <abbr title="Или валидация">Проверка</abbr> данных @@ -63,12 +69,15 @@ Та же ошибка возникнет, если вместо `int` передать `float` , например: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -!!! check "Заметка" - **FastAPI** обеспечивает проверку типов, используя всё те же определения типов. +/// check | "Заметка" - Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. +**FastAPI** обеспечивает проверку типов, используя всё те же определения типов. - Это очень полезно при разработке и отладке кода, который взаимодействует с API. +Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. + +Это очень полезно при разработке и отладке кода, который взаимодействует с API. + +/// ## Документация @@ -76,10 +85,13 @@ <img src="/img/tutorial/path-params/image01.png"> -!!! check "Заметка" - Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). +/// check | "Заметка" + +Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). + +Обратите внимание, что параметр пути объявлен целочисленным. - Обратите внимание, что параметр пути объявлен целочисленным. +/// ## Преимущества стандартизации, альтернативная документация @@ -140,11 +152,17 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Дополнительная информация" - <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Перечисления (enum) доступны в Python</a> начиная с версии 3.4. +/// info | "Дополнительная информация" -!!! tip "Подсказка" - Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия <abbr title="Технически, это архитектуры моделей глубокого обучения">моделей</abbr> машинного обучения. +<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Перечисления (enum) доступны в Python</a> начиная с версии 3.4. + +/// + +/// tip | "Подсказка" + +Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия <abbr title="Технически, это архитектуры моделей глубокого обучения">моделей</abbr> машинного обучения. + +/// ### Определение *параметра пути* @@ -180,8 +198,11 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Подсказка" - Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. +/// tip | "Подсказка" + +Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. + +/// #### Возврат *элементов перечисления* @@ -233,10 +254,13 @@ OpenAPI не поддерживает способов объявления *п {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Подсказка" - Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). +/// tip | "Подсказка" + +Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). + +В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. - В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. +/// ## Резюме Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете: diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 108aefefc..e6653a837 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ Давайте рассмотрим следующий пример: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. -!!! note "Технические детали" - FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. +/// note | "Технические детали" - `Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. +FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. + +`Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. + +/// ## Расширенная валидация @@ -34,23 +41,27 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N * `Query` из пакета `fastapi`: * `Annotated` из пакета `typing` (или из `typing_extensions` для Python ниже 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ + +В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. + +```Python hl_lines="1 3" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` - В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. +//// - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. - В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. +Эта библиотека будет установлена вместе с FastAPI. - Эта библиотека будет установлена вместе с FastAPI. +```Python hl_lines="3-4" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// ## `Annotated` как тип для query-параметра `q` @@ -60,31 +71,39 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N У нас была аннотация следующего типа: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: str | None = None - ``` +```Python +q: str | None = None +``` -=== "Python 3.8+" +//// - ```Python - q: Union[str, None] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// Вот что мы получим, если обернём это в `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// - ```Python - q: Annotated[str | None] = None - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +q: Annotated[Union[str, None]] = None +``` - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// Обе эти версии означают одно и тоже. `q` - это параметр, который может быть `str` или `None`, и по умолчанию он будет принимать `None`. @@ -94,17 +113,21 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным. @@ -120,22 +143,29 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N В предыдущих версиях FastAPI (ниже <abbr title="ранее 2023-03">0.95.0</abbr>) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню. -!!! tip "Подсказка" - При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 +/// tip | "Подсказка" + +При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 + +/// Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +//// В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI). @@ -165,22 +195,25 @@ q: str | None = None Но он явно объявляет его как query-параметр. -!!! info "Дополнительная информация" - Запомните, важной частью объявления параметра как необязательного является: +/// info | "Дополнительная информация" + +Запомните, важной частью объявления параметра как необязательного является: - ```Python - = None - ``` +```Python += None +``` - или: +или: - ```Python - = Query(default=None) - ``` +```Python += Query(default=None) +``` - так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. +так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. - `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. +`Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. + +/// Теперь, мы можем указать больше параметров для `Query`. В данном случае, параметр `max_length` применяется к строкам: @@ -232,81 +265,113 @@ q: str = Query(default="rick") Вы также можете добавить параметр `min_length`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.9+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +//// ## Регулярные выражения Вы можете определить <abbr title="Регулярное выражение, regex или regexp - это последовательность символов, определяющая шаблон для строк.">регулярное выражение</abbr>, которому должен соответствовать параметр: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="12" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | "Подсказка" - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+" +/// - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +//// Данное регулярное выражение проверяет, что полученное значение параметра: @@ -324,29 +389,41 @@ q: str = Query(default="rick") Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +/// note | "Технические детали" -!!! note "Технические детали" - Наличие значения по умолчанию делает параметр необязательным. +Наличие значения по умолчанию делает параметр необязательным. + +/// ## Обязательный параметр @@ -364,75 +441,103 @@ q: Union[str, None] = None Но у нас query-параметр определён как `Query`. Например: -=== "Annotated" +//// tab | Annotated + +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` +//// tab | без Annotated -=== "без Annotated" +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` +//// В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ без Annotated" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` +/// tip | "Подсказка" - !!! tip "Подсказка" - Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. +Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. - Лучше будет использовать версию с `Annotated`. 😉 +Лучше будет использовать версию с `Annotated`. 😉 + +/// + +//// ### Обязательный параметр с Ellipsis (`...`) Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +/// -!!! info "Дополнительная информация" - Если вы ранее не сталкивались с `...`: это специальное значение, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">часть языка Python и называется "Ellipsis"</a>. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +``` - Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. +//// + +/// info | "Дополнительная информация" + +Если вы ранее не сталкивались с `...`: это специальное значение, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">часть языка Python и называется "Ellipsis"</a>. + +Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. + +/// Таким образом, **FastAPI** определяет, что параметр является обязательным. @@ -442,72 +547,103 @@ q: Union[str, None] = None Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -!!! tip "Подсказка" - Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Обязательные Опциональные поля</a>. +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// + +/// tip | "Подсказка" + +Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Обязательные Опциональные поля</a>. + +/// ### Использование Pydantic's `Required` вместо Ellipsis (`...`) Если вас смущает `...`, вы можете использовать `Required` из Pydantic: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 9" +{!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="4 10" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="2 9" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} - ``` +/// + +```Python hl_lines="2 8" +{!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="2 8" - {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} - ``` +Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. -!!! tip "Подсказка" - Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. +/// ## Множество значений для query-параметра @@ -515,50 +651,71 @@ q: Union[str, None] = None Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.10+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +/// -=== "Python 3.9+ без Annotated" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +//// Затем, получив такой URL: @@ -579,8 +736,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "Подсказка" - Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. +/// tip | "Подсказка" + +Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. + +/// Интерактивная документация API будет обновлена соответствующим образом, где будет разрешено множество значений: @@ -590,35 +750,49 @@ http://localhost:8000/items/?q=foo&q=bar Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+ без Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +//// Если вы перейдёте по ссылке: @@ -641,31 +815,43 @@ http://localhost:8000/items/ Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// note | "Технические детали" - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` +Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. -!!! note "Технические детали" - Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. +Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. - Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. +/// ## Больше метаданных @@ -673,86 +859,121 @@ http://localhost:8000/items/ Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах. -!!! note "Технические детали" - Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. +/// note | "Технические детали" - Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. +Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. + +Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. + +/// Вы можете указать название query-параметра, используя параметр `title`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+" +/// + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +//// Добавить описание, используя параметр `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +/// + +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +//// ## Псевдонимы параметров @@ -772,41 +993,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ без Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +//// ## Устаревшие параметры @@ -816,41 +1053,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда для `Query` укажите параметр `deprecated=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// В документации это будет отображено следующим образом: @@ -860,41 +1113,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index f6e18f971..061f9be04 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20 Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. -!!! check "Важно" - Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. +/// check | "Важно" + +Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. + +/// ## Преобразование типа параметра запроса Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// В этом случае, если вы сделаете запрос: @@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes Они будут обнаружены по именам: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Обязательные query-параметры @@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// В этом примере, у нас есть 3 параметра запроса: @@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, типа `int` и со значением по умолчанию `0`. * `limit`, необязательный `int`. -!!! tip "Подсказка" - Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. +/// tip | "Подсказка" + +Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 79b3bd067..1fbc4acc0 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -2,70 +2,97 @@ Используя класс `File`, мы можем позволить клиентам загружать файлы. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info | "Дополнительная информация" - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. - Это связано с тем, что загружаемые файлы передаются как данные формы. +Например: `pip install python-multipart`. + +Это связано с тем, что загружаемые файлы передаются как данные формы. + +/// ## Импорт `File` Импортируйте `File` и `UploadFile` из модуля `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// ## Определите параметры `File` Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +/// info | "Дополнительная информация" -=== "Python 3.6+ без Annotated" +`File` - это класс, который наследуется непосредственно от `Form`. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// -!!! info "Дополнительная информация" - `File` - это класс, который наследуется непосредственно от `Form`. +/// tip | "Подсказка" - Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. +Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). -!!! tip "Подсказка" - Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). +/// Файлы будут загружены как данные формы. @@ -79,26 +106,35 @@ Определите параметр файла с типом `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// Использование `UploadFile` имеет ряд преимуществ перед `bytes`: @@ -141,11 +177,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "Технические детали `async`" - При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. +/// note | "Технические детали `async`" + +При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. + +/// + +/// note | "Технические детали Starlette" -!!! note "Технические детали Starlette" - **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. +**FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. + +/// ## Про данные формы ("Form Data") @@ -153,82 +195,113 @@ contents = myfile.file.read() **FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. +/// note | "Технические детали" + +Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. + +Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. + +Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>. + +/// - Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. +/// warning | "Внимание" - Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>. +В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. -!!! warning "Внимание" - В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. +Это не является ограничением **FastAPI**, это часть протокола HTTP. - Это не является ограничением **FastAPI**, это часть протокола HTTP. +/// ## Необязательная загрузка файлов Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+" +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// ## `UploadFile` с дополнительными метаданными Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="8 14" - {!> ../../../docs_src/request_files/tutorial001_03_an.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +//// ## Загрузка нескольких файлов @@ -238,76 +311,107 @@ contents = myfile.file.read() Для этого необходимо объявить список `bytes` или `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` -=== "Python 3.9+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.9+ без Annotated - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Предпочтительнее использовать версию с аннотацией, если это возможно. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. -!!! note "Technical Details" - Можно также использовать `from starlette.responses import HTMLResponse`. +/// note | "Technical Details" + +Можно также использовать `from starlette.responses import HTMLResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. +/// ### Загрузка нескольких файлов с дополнительными метаданными Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.9+ без Annotated" +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index a08232ca7..b38962866 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,91 @@ Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы и/или данные форм, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info | "Дополнительная информация" - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы и/или данные форм, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +Например: `pip install python-multipart`. + +/// ## Импортируйте `File` и `Form` -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// ## Определите параметры `File` и `Form` Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10-12" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+ без Annotated" +```Python hl_lines="9-11" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +//// Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. -!!! warning "Внимание" - Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. +/// warning | "Внимание" + +Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. + +Это не ограничение **Fast API**, это часть протокола HTTP. - Это не ограничение **Fast API**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index fa2bcb7cb..3737f1347 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. -!!! info "Дополнительная информация" - Чтобы использовать формы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info | "Дополнительная информация" - Например, выполните команду `pip install python-multipart`. +Чтобы использовать формы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +Например, выполните команду `pip install python-multipart`. + +/// ## Импорт `Form` Импортируйте `Form` из `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Рекомендуется использовать 'Annotated' версию, если это возможно. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## Определение параметров `Form` Создайте параметры формы так же, как это делается для `Body` или `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Рекомендуется использовать 'Annotated' версию, если это возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. @@ -63,11 +84,17 @@ Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. -!!! info "Дополнительная информация" - `Form` - это класс, который наследуется непосредственно от `Body`. +/// info | "Дополнительная информация" + +`Form` - это класс, который наследуется непосредственно от `Body`. + +/// + +/// tip | "Подсказка" -!!! tip "Подсказка" - Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). +Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). + +/// ## О "полях формы" @@ -75,17 +102,23 @@ **FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON. -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. +/// note | "Технические детали" + +Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. + +Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. + +Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с <a href="https://developer.mozilla.org/ru/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> для `POST` на веб-сайте</a>. + +/// - Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. +/// warning | "Предупреждение" - Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с <a href="https://developer.mozilla.org/ru/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> для `POST` на веб-сайте</a>. +Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. -!!! warning "Предупреждение" - Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. +Это не ограничение **FastAPI**, это часть протокола HTTP. - Это не ограничение **FastAPI**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 9b9b60dd5..38d185b98 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +//// FastAPI будет использовать этот возвращаемый тип для: @@ -53,35 +59,47 @@ FastAPI будет использовать этот возвращаемый т * `@app.delete()` * и др. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note "Технические детали" - Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. +//// + +/// note | "Технические детали" + +Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. + +/// `response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`. FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип. -!!! tip "Подсказка" - Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. +/// tip | "Подсказка" + +Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. + +Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. - Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. +/// ### Приоритет `response_model` @@ -95,36 +113,47 @@ FastAPI будет использовать значение `response_model` д Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +/// info | "Информация" -!!! info "Информация" - Чтобы использовать `EmailStr`, прежде необходимо установить <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. - Используйте `pip install email-validator` - или `pip install pydantic[email]`. +Чтобы использовать `EmailStr`, прежде необходимо установить <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +Используйте `pip install email-validator` +или `pip install pydantic[email]`. + +/// Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. @@ -132,52 +161,67 @@ FastAPI будет использовать значение `response_model` д Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю. -!!! danger "Осторожно" - Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. +/// danger | "Осторожно" + +Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. + +/// ## Создание модели для ответа Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// ...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). @@ -201,17 +245,21 @@ FastAPI будет использовать значение `response_model` д И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` + +//// - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. @@ -277,17 +325,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма То же самое произошло бы, если бы у вас было что-то вроде <abbr title='Union разных типов буквально означает "любой из перечисленных типов".'>Union</abbr> различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` + +//// ...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. @@ -299,17 +351,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +//// Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 @@ -317,23 +373,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма Модель ответа может иметь значения по умолчанию, например: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// * `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. * `tax: float = 10.5`, где `10.5` является значением по умолчанию. @@ -347,23 +409,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` + +//// и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. @@ -376,16 +444,22 @@ FastAPI совместно с Pydantic выполнит некоторую ма } ``` -!!! info "Информация" - "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">с параметром `exclude_unset`</a>, чтобы достичь такого эффекта. +/// info | "Информация" + +"Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">с параметром `exclude_unset`</a>, чтобы достичь такого эффекта. + +/// + +/// info | "Информация" -!!! info "Информация" - Вы также можете использовать: +Вы также можете использовать: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - как описано в <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">документации Pydantic</a> для параметров `exclude_defaults` и `exclude_none`. +как описано в <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">документации Pydantic</a> для параметров `exclude_defaults` и `exclude_none`. + +/// #### Если значение поля отличается от значения по-умолчанию @@ -420,10 +494,13 @@ FastAPI достаточно умен (на самом деле, это засл И поэтому, они также будут включены в JSON ответа. -!!! tip "Подсказка" - Значением по умолчанию может быть что угодно, не только `None`. +/// tip | "Подсказка" + +Значением по умолчанию может быть что угодно, не только `None`. + +Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. - Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. +/// ### `response_model_include` и `response_model_exclude` @@ -433,45 +510,59 @@ FastAPI достаточно умен (на самом деле, это засл Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic. -!!! tip "Подсказка" - Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. +/// tip | "Подсказка" + +Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. + +Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. - Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. +То же самое применимо к параметру `response_model_by_alias`. - То же самое применимо к параметру `response_model_by_alias`. +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +/// tip | "Подсказка" -!!! tip "Подсказка" - При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. +При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. - Того же самого можно достичь используя `set(["name", "description"])`. +Того же самого можно достичь используя `set(["name", "description"])`. + +/// #### Что если использовать `list` вместо `set`? Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index b2f9b7704..a36c42d05 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Примечание" - Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. +/// note | "Примечание" + +Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. + +/// Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа. -!!! info "Информация" - В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a> в Python. +/// info | "Информация" + +В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a> в Python. + +/// Это позволит: @@ -27,15 +33,21 @@ <img src="/img/tutorial/response-status-code/image01.png"> -!!! note "Примечание" - Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. +/// note | "Примечание" + +Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. + +FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. - FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. +/// ## Об HTTP кодах статуса ответа -!!! note "Примечание" - Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. +/// note | "Примечание" + +Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. + +/// В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа. @@ -54,8 +66,11 @@ * Для общих ошибок со стороны клиента можно просто использовать код `400`. * `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов. -!!! tip "Подсказка" - Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> об HTTP кодах статуса ответа</a>. +/// tip | "Подсказка" + +Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> об HTTP кодах статуса ответа</a>. + +/// ## Краткие обозначения для запоминания названий кодов @@ -79,10 +94,13 @@ <img src="/img/tutorial/response-status-code/image02.png"> -!!! note "Технические детали" - Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. +/// note | "Технические детали" + +Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. + +**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. - **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. +/// ## Изменение кода статуса по умолчанию diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index e1011805a..1b216de3a 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -8,24 +8,31 @@ Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в <a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Pydantic документации: Настройка схемы</a>: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-21" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-23" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. -!!! tip Подсказка - Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. +/// tip | Подсказка + +Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. + +Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. - Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. +/// ## Дополнительные аргументы поля `Field` @@ -33,20 +40,27 @@ Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +/// warning | Внимание -!!! warning Внимание - Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. +Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. + +/// ## Использование `example` и `examples` в OpenAPI @@ -66,41 +80,57 @@ Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23-28" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | Заметка - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +Рекомендуется использовать версию с `Annotated`, если это возможно. -=== "Python 3.10+ non-Annotated" +/// - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +```Python hl_lines="18-23" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +/// tip | Заметка - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="20-25" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### Аргумент "example" в UI документации @@ -121,41 +151,57 @@ * `value`: Это конкретный пример, который отображается, например, в виде типа `dict`. * `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip | Заметка - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +Рекомендуется использовать версию с `Annotated`, если это возможно. - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +//// - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip | Заметка + +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// ### Аргумент "examples" в UI документации @@ -165,10 +211,13 @@ ## Технические Детали -!!! warning Внимание - Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. +/// warning | Внимание + +Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. + +Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. - Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. +/// Когда вы добавляете пример внутрь модели Pydantic, используя `schema_extra` или `Field(example="something")`, этот пример добавляется в **JSON Schema** для данной модели Pydantic. diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index fdeccc01a..444a06915 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -20,36 +20,47 @@ Скопируйте пример в файл `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ без Annotated - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+ без Annotated" +Предпочтительнее использовать версию с аннотацией, если это возможно. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` +//// ## Запуск -!!! info "Дополнительная информация" - Вначале, установите библиотеку <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. +/// info | "Дополнительная информация" - А именно: `pip install python-multipart`. +Вначале, установите библиотеку <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. - Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. +А именно: `pip install python-multipart`. + +Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. + +/// Запустите ваш сервер: @@ -71,17 +82,23 @@ $ uvicorn main:app --reload <img src="/img/tutorial/security/image01.png"> -!!! check "Кнопка авторизации!" - У вас уже появилась новая кнопка "Authorize". +/// check | "Кнопка авторизации!" + +У вас уже появилась новая кнопка "Authorize". - А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. +А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. + +/// При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля): <img src="/img/tutorial/security/image02.png"> -!!! note "Технические детали" - Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. +/// note | "Технические детали" + +Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. + +/// Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API. @@ -123,51 +140,69 @@ OAuth2 был разработан для того, чтобы бэкэнд ил В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`. -!!! info "Дополнительная информация" - Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. +/// info | "Дополнительная информация" + +Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. + +И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. - И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. +В этом случае **FastAPI** также предоставляет инструменты для его реализации. - В этом случае **FastAPI** также предоставляет инструменты для его реализации. +/// При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="7" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="6" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// + +/// tip | "Подсказка" - ```Python hl_lines="6" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. -!!! tip "Подсказка" - Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. +Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`. - Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`. +Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. - Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +/// Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` будет таким, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации API. Вскоре мы создадим и саму операцию пути. -!!! info "Дополнительная информация" - Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. +/// info | "Дополнительная информация" + +Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. + +Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. - Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. +/// Переменная `oauth2_scheme` является экземпляром `OAuth2PasswordBearer`, но она также является "вызываемой". @@ -183,35 +218,47 @@ oauth2_scheme(some, parameters) Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. **FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API). -!!! info "Технические детали" - **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. +/// info | "Технические детали" + +**FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. + +Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. - Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. +/// ## Что он делает diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md index d5fe4e76f..bd512fde3 100644 --- a/docs/ru/docs/tutorial/security/index.md +++ b/docs/ru/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2 включает в себя способы аутентификации OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS. -!!! tip "Подсказка" - В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) +/// tip | "Подсказка" +В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI может использовать следующие схемы авт * Это автоматическое обнаружение определено в спецификации OpenID Connect. -!!! tip "Подсказка" - Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. +/// tip | "Подсказка" + +Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. + +Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. - Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. +/// ## Преимущества **FastAPI** diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index afe2075d9..ccddae249 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Технические детали" - Вы также можете использовать `from starlette.staticfiles import StaticFiles`. +/// note | "Технические детали" - **FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. +Вы также можете использовать `from starlette.staticfiles import StaticFiles`. + +**FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. + +/// ### Что такое "Монтирование" diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index 4772660df..efefbfb01 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## Использование класса `TestClient` -!!! info "Информация" - Для использования класса `TestClient` необходимо установить библиотеку <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. +/// info | "Информация" - Например, так: `pip install httpx`. +Для использования класса `TestClient` необходимо установить библиотеку <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. + +Например, так: `pip install httpx`. + +/// Импортируйте `TestClient`. @@ -27,20 +30,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "Подсказка" - Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. +/// tip | "Подсказка" + +Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. + +И вызов клиента также осуществляется без `await`. + +Это позволяет вам использовать `pytest` без лишних усложнений. + +/// + +/// note | "Технические детали" + +Также можно написать `from starlette.testclient import TestClient`. - И вызов клиента также осуществляется без `await`. +**FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. - Это позволяет вам использовать `pytest` без лишних усложнений. +/// -!!! note "Технические детали" - Также можно написать `from starlette.testclient import TestClient`. +/// tip | "Подсказка" - **FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. +Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. -!!! tip "Подсказка" - Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. +/// ## Разделение тестов и приложения @@ -110,41 +122,57 @@ Обе *операции пути* требуют наличия в запросе заголовка `X-Token`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +По возможности используйте версию с `Annotated`. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +По возможности используйте версию с `Annotated`. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### Расширенный файл тестов @@ -168,10 +196,13 @@ Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с <a href="https://www.python-httpx.org" class="external-link" target="_blank">документацией HTTPX</a>. -!!! info "Информация" - Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. +/// info | "Информация" + +Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. + +Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. - Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. +/// ## Запуск тестов diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md index c0a566d12..6c057162e 100644 --- a/docs/tr/docs/advanced/index.md +++ b/docs/tr/docs/advanced/index.md @@ -6,10 +6,13 @@ İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz. -!!! tip "İpucu" - Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. +/// tip | "İpucu" - Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// ## Önce Öğreticiyi Okuyun diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md index 89a431687..227674bd4 100644 --- a/docs/tr/docs/advanced/security/index.md +++ b/docs/tr/docs/advanced/security/index.md @@ -4,10 +4,13 @@ [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır. -!!! tip "İpucu" - Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. +/// tip | "İpucu" - Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// ## Önce Öğreticiyi Okuyun diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index cdd5b7ae5..59a2499e2 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e ba {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "Not" - Daha fazla detay için Starlette'in <a href="https://www.starlette.io/staticfiles/" class="external-link" target="_blank">Websockets'i Test Etmek</a> dokümantasyonunu inceleyin. +/// note | "Not" + +Daha fazla detay için Starlette'in <a href="https://www.starlette.io/staticfiles/" class="external-link" target="_blank">Websockets'i Test Etmek</a> dokümantasyonunu inceleyin. + +/// diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md index 462d8b304..bd668ca45 100644 --- a/docs/tr/docs/alternatives.md +++ b/docs/tr/docs/alternatives.md @@ -30,11 +30,17 @@ Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka p **Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu. -!!! note "Not" - Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. +/// note | "Not" -!!! check "**FastAPI**'a nasıl ilham verdi?" - Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. +Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. + +/// + +/// check | "**FastAPI**'a nasıl ilham verdi?" + +Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. + +/// ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> @@ -50,10 +56,13 @@ Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle ge Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"! -!!! check "**FastAPI**'a nasıl ilham verdi?" - Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" - Basit ve kullanması kolay bir <abbr title="Yönlendirme: Routing">yönlendirme sistemine</abbr> sahip olmalı. +Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. + +Basit ve kullanması kolay bir <abbr title="Yönlendirme: Routing">yönlendirme sistemine</abbr> sahip olmalı. + +/// ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> @@ -89,10 +98,13 @@ def read_url(): `requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın. -!!! check "**FastAPI**'a nasıl ilham verdi?" - * Basit ve sezgisel bir API'ya sahip olmalı. - * HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. - * Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" + +* Basit ve sezgisel bir API'ya sahip olmalı. +* HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. +* Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. + +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -106,15 +118,18 @@ Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştir İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın. -!!! check "**FastAPI**'a nasıl ilham verdi?" - API spesifikasyonları için özel bir şema yerine bir <abbr title="Open Standard: Açık Standart, Açık kaynak olarak yayınlanan standart">açık standart</abbr> benimseyip kullanmalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" + +API spesifikasyonları için özel bir şema yerine bir <abbr title="Open Standard: Açık Standart, Açık kaynak olarak yayınlanan standart">açık standart</abbr> benimseyip kullanmalı. + +Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: - Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: +* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> +* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> +Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. - Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. +/// ### Flask REST framework'leri @@ -132,8 +147,11 @@ Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmiş Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her <abbr title="Verilerin nasıl oluşturulması gerektiğinin tanımı">şemayı</abbr> tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu. -!!! check "**FastAPI**'a nasıl ilham verdi?" - Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" + +Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -145,11 +163,17 @@ Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştir Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım. -!!! info "Bilgi" - Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. +/// info | "Bilgi" + +Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. -!!! check "**FastAPI**'a nasıl ilham verdi?" - Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. +/// + +/// check | "**FastAPI**'a nasıl ilham verdi?" + +Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -167,11 +191,17 @@ Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python m Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor. -!!! info "Bilgi" - APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. +/// info | "Bilgi" + +APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. + +/// + +/// check | "**FastAPI**'a nasıl ilham verdi?" -!!! check "**FastAPI**'a nasıl ilham verdi?" - API'lar için açık standart desteği olmalı (OpenAPI gibi). +API'lar için açık standart desteği olmalı (OpenAPI gibi). + +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -193,11 +223,17 @@ Bunu kullanmak, bir kaç <abbr title="full-stack: Hem ön uç hem de arka uç ge Aynı full-stack üreticiler [**FastAPI** Proje Üreticileri](project-generation.md){.internal-link target=_blank}'nin de temelini oluşturdu. -!!! info "Bilgi" - Flask-apispec de aynı Marshmallow geliştiricileri tarafından üretildi. +/// info | "Bilgi" + +Flask-apispec de aynı Marshmallow geliştiricileri tarafından üretildi. + +/// -!!! check "**FastAPI**'a nasıl ilham oldu?" - Veri dönüşümü ve veri doğrulamayı tanımlayan kodu kullanarak otomatik olarak OpenAPI şeması oluşturmalı. +/// check | "**FastAPI**'a nasıl ilham oldu?" + +Veri dönüşümü ve veri doğrulamayı tanımlayan kodu kullanarak otomatik olarak OpenAPI şeması oluşturmalı. + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (and <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) @@ -213,24 +249,33 @@ Ama TypeScript verileri kod JavaScript'e derlendikten sonra korunmadığından, İç içe geçen derin modelleri pek iyi işleyemiyor. Yani eğer istekteki JSON gövdesi derin bir JSON objesiyse düzgün bir şekilde dökümante edilip doğrulanamıyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Güzel bir editör desteği için Python tiplerini kullanmalı. +/// check | "**FastAPI**'a nasıl ilham oldu?" + +Güzel bir editör desteği için Python tiplerini kullanmalı. - Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. +Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. + +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> Sanic, `asyncio`'ya dayanan son derece hızlı Python kütüphanelerinden biriydi. Flask'a epey benzeyecek şekilde geliştirilmişti. -!!! note "Teknik detaylar" - İçerisinde standart Python `asyncio` döngüsü yerine <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> kullanıldı. Hızının asıl kaynağı buydu. +/// note | "Teknik detaylar" + +İçerisinde standart Python `asyncio` döngüsü yerine <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> kullanıldı. Hızının asıl kaynağı buydu. + +Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. - Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. +/// -!!! check "**FastAPI**'a nasıl ilham oldu?" - Uçuk performans sağlayacak bir yol bulmalı. +/// check | "**FastAPI**'a nasıl ilham oldu?" - Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) +Uçuk performans sağlayacak bir yol bulmalı. + +Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -240,12 +285,15 @@ Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Harika bir performans'a sahip olmanın yollarını bulmalı. +/// check | "**FastAPI**'a nasıl ilham oldu?" + +Harika bir performans'a sahip olmanın yollarını bulmalı. - Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. +Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. - FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. +FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. + +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -263,10 +311,13 @@ Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca <abbr title="ASGI (Async <abbr title="Route: HTTP isteğinin gittiği yol">Yol</abbr>'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. +/// check | "**FastAPI**'a nasıl ilham oldu?" + +Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. + +Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. - Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -282,15 +333,21 @@ Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü k Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip. -!!! info "Bilgi" - Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>'un geliştiricisi Timothy Crosley tarafından geliştirildi. +/// info | "Bilgi" + +Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>'un geliştiricisi Timothy Crosley tarafından geliştirildi. + +/// + +/// check | "**FastAPI**'a nasıl ilham oldu?" -!!! check "**FastAPI**'a nasıl ilham oldu?" - Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. +Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. - **FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. +**FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. - **FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. +**FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. + +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5) @@ -316,23 +373,29 @@ Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web f Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi. -!!! info "Bilgi" - APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: +/// info | "Bilgi" + +APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: + +* Django REST Framework +* **FastAPI**'ın da dayandığı Starlette +* Starlette ve **FastAPI** tarafından da kullanılan Uvicorn - * Django REST Framework - * **FastAPI**'ın da dayandığı Starlette - * Starlette ve **FastAPI** tarafından da kullanılan Uvicorn +/// -!!! check "**FastAPI**'a nasıl ilham oldu?" - Var oldu. +/// check | "**FastAPI**'a nasıl ilham oldu?" - Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. +Var oldu. - Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. +Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. - Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. +Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. - Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, <abbr title="Tip desteği (typing support): kod yapısında parametrelere, argümanlara ve objelerin özelliklerine veri tipi atamak">tip desteği</abbr> sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. +Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. + +Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, <abbr title="Tip desteği (typing support): kod yapısında parametrelere, argümanlara ve objelerin özelliklerine veri tipi atamak">tip desteği</abbr> sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. + +/// ## **FastAPI** Tarafından Kullanılanlar @@ -344,10 +407,13 @@ Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor. Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika. -!!! check "**FastAPI** nerede kullanıyor?" - Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! +/// check | "**FastAPI** nerede kullanıyor?" + +Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! - **FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. +**FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. + +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -376,18 +442,23 @@ Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyo Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor. -!!! note "Teknik Detaylar" - ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. +/// note | "Teknik Detaylar" + +ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. + +Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. - Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. +/// -!!! check "**FastAPI** nerede kullanıyor?" +/// check | "**FastAPI** nerede kullanıyor?" - Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. +Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. - `FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! +`FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! - Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. +Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -397,12 +468,15 @@ Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur. -!!! check "**FastAPI** neden tavsiye ediyor?" - **FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! +/// check | "**FastAPI** neden tavsiye ediyor?" + +**FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! + +Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! - Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! +Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. - Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. +/// ## Karşılaştırma ve Hız diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md index c7bedffd1..0d463a2f0 100644 --- a/docs/tr/docs/async.md +++ b/docs/tr/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "Not" - Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. +/// note | "Not" + +Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. + +/// --- @@ -363,12 +366,15 @@ FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir p ## Çok Teknik Detaylar -!!! warning - Muhtemelen burayı atlayabilirsiniz. +/// warning + +Muhtemelen burayı atlayabilirsiniz. + +Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. - Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. +Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. - Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. +/// ### Path fonksiyonu diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md index 209ab922c..6e8af4025 100644 --- a/docs/tr/docs/external-links.md +++ b/docs/tr/docs/external-links.md @@ -6,8 +6,11 @@ Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. -!!! tip "İpucu" - Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a> oluşturabilirsiniz. +/// tip | "İpucu" + +Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a> oluşturabilirsiniz. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index 1cda8c7fb..5d40b1086 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -67,10 +67,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` şu anlama geliyor: +/// info - Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` şu anlama geliyor: + +Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Editor desteği diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md index 8ece29515..798adca61 100644 --- a/docs/tr/docs/how-to/index.md +++ b/docs/tr/docs/how-to/index.md @@ -6,6 +6,8 @@ Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. -!!! tip "İpucu" +/// tip | "İpucu" - **FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. +**FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. + +/// diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index ac3111136..b8b880c6d 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -12,8 +12,11 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme **FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var. -!!! note "Not" - Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. +/// note | "Not" + +Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. + +/// ## Motivasyon @@ -172,10 +175,13 @@ Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli para {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Ipucu" - Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. +/// tip | "Ipucu" + +Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. + +Bu durumda `str`, `List`e iletilen tür parametresidir. - Bu durumda `str`, `List`e iletilen tür parametresidir. +/// Bunun anlamı şudur: "`items` değişkeni bir `list`tir ve bu listedeki öğelerin her biri bir `str`dir". @@ -281,8 +287,11 @@ Resmi Pydantic dokümanlarından alınmıştır: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Daha fazla şey öğrenmek için <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic'i takip edin</a>. +/// info + +Daha fazla şey öğrenmek için <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic'i takip edin</a>. + +/// **FastAPI** tamamen Pydantic'e dayanmaktadır. @@ -310,5 +319,8 @@ Bütün bunlar kulağa soyut gelebilir. Merak etme. Tüm bunları çalışırken Önemli olan, standart Python türlerini tek bir yerde kullanarak (daha fazla sınıf, dekoratör vb. eklemek yerine), **FastAPI**'nin bizim için işi yapmasını sağlamak. -!!! info - Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak:<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> the "cheat sheet" from `mypy`</a>. +/// info + +Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak:<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> the "cheat sheet" from `mypy`</a>. + +/// diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 4a66f26eb..807f85e8a 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ Öncelikle, `Cookie`'yi projenize dahil edin: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +/// tip | "İpucu" - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "İpucu" + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## `Cookie` Parametrelerini Tanımlayın @@ -48,49 +64,71 @@ İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | "İpucu" + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip | "İpucu" -=== "Python 3.8+" +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Teknik Detaylar" -=== "Python 3.8+ non-Annotated" +`Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Teknik Detaylar" - `Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. +/// info | "Bilgi" - Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur. +Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. -!!! info "Bilgi" - Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. +/// ## Özet diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index e66f73034..76c035992 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note "Not" - `uvicorn main:app` komutunu şu şekilde açıklayabiliriz: +/// note | "Not" - * `main`: dosya olan `main.py` (yani Python "modülü"). - * `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. - * `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. +`uvicorn main:app` komutunu şu şekilde açıklayabiliriz: + +* `main`: dosya olan `main.py` (yani Python "modülü"). +* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. +* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. + +/// Çıktı olarak şöyle bir satır ile karşılaşacaksınız: @@ -136,10 +139,13 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. -!!! note "Teknik Detaylar" - `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. +/// note | "Teknik Detaylar" + +`FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. - <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. +<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. + +/// ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Bilgi" - "Yol" genellikle "<abbr title="Endpoint: Bitim Noktası">endpoint</abbr>" veya "<abbr title="Route: Yönlendirme/Yön">route</abbr>" olarak adlandırılır. +/// info | "Bilgi" + +"Yol" genellikle "<abbr title="Endpoint: Bitim Noktası">endpoint</abbr>" veya "<abbr title="Route: Yönlendirme/Yön">route</abbr>" olarak adlandırılır. + +/// Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir. @@ -250,16 +259,19 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. * <abbr title="Bir HTTP GET metodu"><code>get</code> operasyonu</abbr> ile * `/` yoluna gelen istekler -!!! info "`@decorator` Bilgisi" - Python'da `@something` sözdizimi "<abbr title="Decorator">dekoratör</abbr>" olarak adlandırılır. +/// info | "`@decorator` Bilgisi" - Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. +Python'da `@something` sözdizimi "<abbr title="Decorator">dekoratör</abbr>" olarak adlandırılır. - Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. +Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. - Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. +Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. - Bu bir **yol operasyonu dekoratörüdür**. +Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. + +Bu bir **yol operasyonu dekoratörüdür**. + +/// Ayrıca diğer operasyonları da kullanabilirsiniz: @@ -274,14 +286,17 @@ Daha az kullanılanları da kullanabilirsiniz: * `@app.patch()` * `@app.trace()` -!!! tip "İpucu" - Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. +/// tip | "İpucu" + +Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. - **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. +**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. - Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. +Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. - Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. +Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. + +/// ### Adım 4: **Yol Operasyonu Fonksiyonunu** Tanımlayın @@ -309,8 +324,11 @@ Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirs {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Not" - Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. +/// note | "Not" + +Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. + +/// ### Adım 5: İçeriği Geri Döndürün diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index c19023645..d36242083 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Standart Python tip belirteçlerini kullanarak yol parametresinin tipini fonksiy Bu durumda, `item_id` bir `int` olarak tanımlanacaktır. -!!! check "Ek bilgi" - Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız. +/// check | "Ek bilgi" + +Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız. + +/// ## Veri <abbr title="Dönüşüm: serialization, parsing ve marshalling olarak da biliniyor">Dönüşümü</abbr> @@ -35,10 +38,13 @@ Eğer bu örneği çalıştırıp tarayıcınızda <a href="http://127.0.0.1:800 {"item_id":3} ``` -!!! check "Ek bilgi" - Dikkatinizi çekerim ki, fonksiyonunuzun aldığı (ve döndürdüğü) değer olan `3` bir string `"3"` değil aksine bir Python `int`'idir. +/// check | "Ek bilgi" + +Dikkatinizi çekerim ki, fonksiyonunuzun aldığı (ve döndürdüğü) değer olan `3` bir string `"3"` değil aksine bir Python `int`'idir. + +Bu tanımlamayla birlikte, **FastAPI** size otomatik istek <abbr title="HTTP isteği ile birlikte gelen string'i Python verisine dönüştürme">"ayrıştırma"</abbr> özelliği sağlar. - Bu tanımlamayla birlikte, **FastAPI** size otomatik istek <abbr title="HTTP isteği ile birlikte gelen string'i Python verisine dönüştürme">"ayrıştırma"</abbr> özelliği sağlar. +/// ## Veri Doğrulama @@ -65,12 +71,15 @@ Eğer tarayıcınızda <a href="http://127.0.0.1:8000/items/foo" class="external Aynı hata <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı. -!!! check "Ek bilgi" - Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. +/// check | "Ek bilgi" - Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. +Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. - Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. +Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. + +Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. + +/// ## Dokümantasyon @@ -78,10 +87,13 @@ Ayrıca, tarayıcınızı <a href="http://127.0.0.1:8000/docs" class="external-l <img src="/img/tutorial/path-params/image01.png"> -!!! check "Ek bilgi" - Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. +/// check | "Ek bilgi" + +Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. + +Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. - Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. +/// ## Standartlara Dayalı Avantajlar, Alternatif Dokümantasyon @@ -141,11 +153,17 @@ Sonrasında, sınıf içerisinde, mevcut ve geçerli değerler olacak olan sabit {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Bilgi" - 3.4 sürümünden beri <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">enumerationlar (ya da enumlar) Python'da mevcuttur</a>. +/// info | "Bilgi" -!!! tip "İpucu" - Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi <abbr title="Teknik olarak, Derin Öğrenme model mimarileri">modellerini</abbr> temsil eder. +3.4 sürümünden beri <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">enumerationlar (ya da enumlar) Python'da mevcuttur</a>. + +/// + +/// tip | "İpucu" + +Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi <abbr title="Teknik olarak, Derin Öğrenme model mimarileri">modellerini</abbr> temsil eder. + +/// ### Bir *Yol Parametresi* Tanımlayalım @@ -181,8 +199,11 @@ Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "İpucu" - `"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. +/// tip | "İpucu" + +`"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. + +/// #### *Enumeration Üyelerini* Döndürelim @@ -235,10 +256,13 @@ Böylece şunun gibi bir kullanım yapabilirsiniz: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "İpucu" - Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. +/// tip | "İpucu" + +Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. + +Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. - Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. +/// ## Özet diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md index 682f8332c..bf66dbe74 100644 --- a/docs/tr/docs/tutorial/query-params.md +++ b/docs/tr/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ Fonksiyonunuzdaki parametre değerleri aşağıdaki gibi olacaktır: Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. -!!! check "Ek bilgi" - Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. +/// check | "Ek bilgi" + +Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. + +/// ## Sorgu Parametresi Tip Dönüşümü Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Bu durumda, eğer şu adrese giderseniz: @@ -137,17 +148,21 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. İsimlerine göre belirleneceklerdir: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Zorunlu Sorgu Parametreleri @@ -205,17 +220,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// Bu durumda, 3 tane sorgu parametresi var olacaktır: @@ -223,5 +242,8 @@ Bu durumda, 3 tane sorgu parametresi var olacaktır: * `skip`, varsayılan değeri `0` olan bir `int`. * `limit`, isteğe bağlı bir `int`. -!!! tip "İpucu" - Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. +/// tip | "İpucu" + +Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. + +/// diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 2728b6164..8e8ccfba4 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz. -!!! info "Bilgi" - Formları kullanmak için öncelikle <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> paketini indirmeniz gerekmektedir. +/// info | "Bilgi" - Örneğin `pip install python-multipart`. +Formları kullanmak için öncelikle <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> paketini indirmeniz gerekmektedir. + +Örneğin `pip install python-multipart`. + +/// ## `Form` Sınıfını Projenize Dahil Edin `Form` sınıfını `fastapi`'den projenize dahil edin: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## `Form` Parametrelerini Tanımlayın Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak <abbr title="Kullanıcı Adı: Username">"username"</abbr> ve <abbr title="Şifre: Password">"password"</abbr> gönderilmesi gerekir. @@ -63,11 +84,17 @@ Bu <abbr title="Spesifikasyon: Specification">spesifikasyon</abbr> form alanlar `Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz. -!!! info "Bilgi" - `Form` doğrudan `Body` sınıfını miras alan bir sınıftır. +/// info | "Bilgi" + +`Form` doğrudan `Body` sınıfını miras alan bir sınıftır. + +/// + +/// tip | "İpucu" -!!! tip "İpucu" - Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. +Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. + +/// ## "Form Alanları" Hakkında @@ -75,17 +102,23 @@ HTML formlarının (`<form></form>`) verileri sunucuya gönderirken JSON'dan far **FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır. -!!! note "Teknik Detaylar" - Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. +/// note | "Teknik Detaylar" + +Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. + +Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz. + +Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a> sayfasını ziyaret edebilirsiniz. + +/// - Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz. +/// warning | "Uyarı" - Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a> sayfasını ziyaret edebilirsiniz. +*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. -!!! warning "Uyarı" - *Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. +Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır. - Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır. +/// ## Özet diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index 00c833686..b82be611f 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Teknik Detaylar" - Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. +/// note | "Teknik Detaylar" - **FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir. +Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. + +**FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir. + +/// ### Bağlama (Mounting) Nedir? diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index 16cc0d875..eb48d6be7 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -30,12 +30,17 @@ Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. -!!! note "Примітка" - Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. +/// note | "Примітка" +Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. -!!! check "Надихнуло **FastAPI** на" - Мати автоматичний веб-інтерфейс документації API. +/// + +/// check | "Надихнуло **FastAPI** на" + +Мати автоматичний веб-інтерфейс документації API. + +/// ### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> @@ -51,11 +56,13 @@ Flask — це «мікрофреймворк», він не включає ін Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. -!!! check "Надихнуло **FastAPI** на" - Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. +/// check | "Надихнуло **FastAPI** на" - Мати просту та легку у використанні систему маршрутизації. +Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. + Мати просту та легку у використанні систему маршрутизації. + +/// ### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> @@ -91,11 +98,13 @@ def read_url(): Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. -!!! check "Надихнуло **FastAPI** на" - * Майте простий та інтуїтивно зрозумілий API. - * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. - * Розумні параметри за замовчуванням, але потужні налаштування. +/// check | "Надихнуло **FastAPI** на" + +* Майте простий та інтуїтивно зрозумілий API. + * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. + * Розумні параметри за замовчуванням, але потужні налаштування. +/// ### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI /OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> @@ -109,15 +118,18 @@ def read_url(): Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». -!!! check "Надихнуло **FastAPI** на" - Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. +/// check | "Надихнуло **FastAPI** на" + +Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. - Інтегрувати інструменти інтерфейсу на основі стандартів: + Інтегрувати інструменти інтерфейсу на основі стандартів: - * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Інтерфейс Swagger</a> - * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> + * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Інтерфейс Swagger</a> + * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> - Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + +/// ### Фреймворки REST для Flask @@ -135,8 +147,11 @@ Marshmallow створено для забезпечення цих функці Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну <abbr title="визначення того, як дані повинні бути сформовані">схему</abbr>, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. -!!! check "Надихнуло **FastAPI** на" - Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. +/// check | "Надихнуло **FastAPI** на" + +Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. + +/// ### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> @@ -148,11 +163,17 @@ Webargs — це інструмент, створений, щоб забезпе Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. -!!! info "Інформація" - Webargs був створений тими ж розробниками Marshmallow. +/// info | "Інформація" + +Webargs був створений тими ж розробниками Marshmallow. + +/// + +/// check | "Надихнуло **FastAPI** на" -!!! check "Надихнуло **FastAPI** на" - Мати автоматичну перевірку даних вхідного запиту. +Мати автоматичну перевірку даних вхідного запиту. + +/// ### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> @@ -172,12 +193,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. -!!! info "Інформація" - APISpec був створений тими ж розробниками Marshmallow. +/// info | "Інформація" + +APISpec був створений тими ж розробниками Marshmallow. + +/// +/// check | "Надихнуло **FastAPI** на" -!!! check "Надихнуло **FastAPI** на" - Підтримувати відкритий стандарт API, OpenAPI. +Підтримувати відкритий стандарт API, OpenAPI. + +/// ### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> @@ -199,11 +225,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. -!!! info "Інформація" - Flask-apispec був створений тими ж розробниками Marshmallow. +/// info | "Інформація" + +Flask-apispec був створений тими ж розробниками Marshmallow. + +/// -!!! check "Надихнуло **FastAPI** на" - Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. +/// check | "Надихнуло **FastAPI** на" + +Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. + +/// ### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (та <a href="https://angular.io/ " class="external-link" target="_blank">Angular</a>) @@ -219,24 +251,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. -!!! check "Надихнуло **FastAPI** на" - Використовувати типи Python, щоб мати чудову підтримку редактора. +/// check | "Надихнуло **FastAPI** на" + +Використовувати типи Python, щоб мати чудову підтримку редактора. - Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + +/// ### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. -!!! note "Технічні деталі" - Він використовував <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. +/// note | "Технічні деталі" + +Він використовував <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. - Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. + Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. -!!! check "Надихнуло **FastAPI** на" - Знайти спосіб отримати божевільну продуктивність. +/// - Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). +/// check | "Надихнуло **FastAPI** на" + +Знайти спосіб отримати божевільну продуктивність. + + Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). + +/// ### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> @@ -246,12 +287,15 @@ Falcon — ще один високопродуктивний фреймворк Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. -!!! check "Надихнуло **FastAPI** на" - Знайти способи отримати чудову продуктивність. +/// check | "Надихнуло **FastAPI** на" - Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. +Знайти способи отримати чудову продуктивність. - Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. + + Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + +/// ### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> @@ -269,10 +313,13 @@ Falcon — ще один високопродуктивний фреймворк Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. -!!! check "Надихнуло **FastAPI** на" - Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. +/// check | "Надихнуло **FastAPI** на" + +Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. - Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). + Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). + +/// ### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a> @@ -288,15 +335,21 @@ Hug був одним із перших фреймворків, який реа Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. -!!! info "Інформація" - Hug створив Тімоті Крослі, той самий творець <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, чудовий інструмент для автоматичного сортування імпорту у файлах Python. +/// info | "Інформація" + +Hug створив Тімоті Крослі, той самий творець <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, чудовий інструмент для автоматичного сортування імпорту у файлах Python. + +/// -!!! check "Надихнуло **FastAPI** на" - Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. +/// check | "Надихнуло **FastAPI** на" - Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. +Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. - Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. + + Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + +/// ### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0,5) @@ -322,21 +375,27 @@ Hug був одним із перших фреймворків, який реа Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. -!!! info "Інформація" - APIStar створив Том Крісті. Той самий хлопець, який створив: +/// info | "Інформація" + +APIStar створив Том Крісті. Той самий хлопець, який створив: - * Django REST Framework - * Starlette (на якому базується **FastAPI**) - * Uvicorn (використовується Starlette і **FastAPI**) + * Django REST Framework + * Starlette (на якому базується **FastAPI**) + * Uvicorn (використовується Starlette і **FastAPI**) -!!! check "Надихнуло **FastAPI** на" - Існувати. +/// - Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. +/// check | "Надихнуло **FastAPI** на" - І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. +Існувати. - Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. + + І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. + + Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + +/// ## Використовується **FastAPI** @@ -348,10 +407,13 @@ Pydantic — це бібліотека для визначення переві Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. -!!! check "**FastAPI** використовує його для" - Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). +/// check | "**FastAPI** використовує його для" - Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. +Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). + + Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. + +/// ### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> @@ -380,17 +442,23 @@ Starlette надає всі основні функції веб-мікрофр Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. -!!! note "Технічні деталі" - ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. +/// note | "Технічні деталі" + +ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. - Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. + Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. -!!! check "**FastAPI** використовує його для" - Керування всіма основними веб-частинами. Додавання функцій зверху. +/// - Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. +/// check | "**FastAPI** використовує його для" - Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. +Керування всіма основними веб-частинами. Додавання функцій зверху. + + Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. + + Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. + +/// ### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> @@ -400,12 +468,15 @@ Uvicorn — це блискавичний сервер ASGI, побудован Це рекомендований сервер для Starlette і **FastAPI**. -!!! check "**FastAPI** рекомендує це як" - Основний веб-сервер для запуску програм **FastAPI**. +/// check | "**FastAPI** рекомендує це як" + +Основний веб-сервер для запуску програм **FastAPI**. + + Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. - Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. + Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. - Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. +/// ## Орієнтири та швидкість diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index d0adadff3..511a5264a 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -12,8 +12,11 @@ Python підтримує додаткові "підказки типу" ("type Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них. -!!! note - Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. +/// note + +Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. + +/// ## Мотивація @@ -164,45 +167,55 @@ John Doe Наприклад, давайте визначимо змінну, яка буде `list` із `str`. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +З модуля `typing`, імпортуємо `List` (з великої літери `L`): + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). - З модуля `typing`, імпортуємо `List` (з великої літери `L`): +Як тип вкажемо `List`, який ви імпортували з `typing`. - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +//// - Як тип вкажемо `List`, який ви імпортували з `typing`. +//// tab | Python 3.9 і вище - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Як тип вкажемо `list`. -=== "Python 3.9 і вище" +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` - Як тип вкажемо `list`. +//// - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +/// info - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +Ці внутрішні типи в квадратних дужках називаються "параметрами типу". -!!! info - Ці внутрішні типи в квадратних дужках називаються "параметрами типу". +У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). - У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). +/// Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`". -!!! tip - Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. +/// tip + +Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. + +/// Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку: @@ -218,17 +231,21 @@ John Doe Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// -=== "Python 3.9 і вище" +//// tab | Python 3.9 і вище - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// Це означає: @@ -243,17 +260,21 @@ John Doe Другий параметр типу для значення у `dict`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | Python 3.9 і вище -=== "Python 3.9 і вище" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// Це означає: @@ -269,17 +290,21 @@ John Doe У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою <abbr title='також називають «побітовим "або" оператором», але це значення тут не актуальне'>вертикальної смуги (`|`)</abbr>. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// В обох випадках це означає, що `item` може бути `int` або `str`. @@ -299,69 +324,81 @@ John Doe Це також означає, що в Python 3.10 ви можете використовувати `Something | None`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8 і вище - альтернатива -=== "Python 3.8 і вище - альтернатива" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### Generic типи Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...та інші. + +//// - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...та інші. +//// tab | Python 3.9 і вище -=== "Python 3.9 і вище" +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +І те саме, що й у Python 3.8, із модуля `typing`: - І те саме, що й у Python 3.8, із модуля `typing`: +* `Union` +* `Optional` +* ...та інші. - * `Union` - * `Optional` - * ...та інші. +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - І те саме, що й у Python 3.8, із модуля `typing`: +І те саме, що й у Python 3.8, із модуля `typing`: - * `Union` - * `Optional` (так само як у Python 3.8) - * ...та інші. +* `Union` +* `Optional` (так само як у Python 3.8) +* ...та інші. - У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати <abbr title='також називають «побітовим "або" оператором», але це значення тут не актуальне'>вертикальну смугу (`|`)</abbr> щоб оголосити об'єднання типів. +У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати <abbr title='також називають «побітовим "або" оператором», але це значення тут не актуальне'>вертикальну смугу (`|`)</abbr> щоб оголосити об'єднання типів. + +//// ### Класи як типи @@ -397,26 +434,35 @@ John Doe Приклад з документації Pydantic: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +//// tab | Python 3.9 і вище + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +//// -=== "Python 3.9 і вище" +//// tab | Python 3.10 і вище - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +/// info -!!! info - Щоб дізнатись більше про <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, перегляньте його документацію</a>. +Щоб дізнатись більше про <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, перегляньте його документацію</a>. + +/// **FastAPI** повністю базується на Pydantic. @@ -444,5 +490,8 @@ John Doe Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас. -!!! info - Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"шпаргалка" від `mypy`</a>. +/// info + +Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"шпаргалка" від `mypy`</a>. + +/// diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index eee993cbe..e4d5b1fad 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ Спочатку вам потрібно імпортувати це: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Варто користуватись `Annotated` версією, якщо це можливо. -!!! warning - Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Варто користуватись `Annotated` версією, якщо це можливо. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning + +Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). + +/// ## Оголошення атрибутів моделі Ви можете використовувати `Field` з атрибутами моделі: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Варто користуватись `Annotated` версією, якщо це можливо.. - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Варто користуватись `Annotated` версією, якщо це можливо.. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. -!!! note "Технічні деталі" - Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. +/// note | "Технічні деталі" - І `Field` від Pydantic також повертає екземпляр `FieldInfo`. +Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. - `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. +І `Field` від Pydantic також повертає екземпляр `FieldInfo`. - Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. +`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. -!!! tip - Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. +Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. + +/// + +/// tip + +Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. + +/// ## Додавання додаткової інформації @@ -105,9 +146,12 @@ Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів. -!!! warning - Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. - Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. +/// warning + +Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. +Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. + +/// ## Підсумок diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 11e94e929..50fd76f84 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -8,28 +8,35 @@ Щоб оголосити тіло **запиту**, ви використовуєте <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> моделі з усією їх потужністю та перевагами. -!!! info - Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. +/// info - Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. +Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. - Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. +Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. + +Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. + +/// ## Імпортуйте `BaseModel` від Pydantic Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// ## Створіть свою модель даних @@ -37,17 +44,21 @@ Використовуйте стандартні типи Python для всіх атрибутів: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 і вище + +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. @@ -75,17 +86,21 @@ Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 і вище + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// ...і вкажіть її тип як модель, яку ви створили, `Item`. @@ -134,32 +149,39 @@ <img src="/img/tutorial/body/image05.png"> -!!! tip - Якщо ви використовуєте <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> як ваш редактор, ви можете використати <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. +/// tip + +Якщо ви використовуєте <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> як ваш редактор, ви можете використати <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>. - Він покращує підтримку редакторів для моделей Pydantic за допомогою: +Він покращує підтримку редакторів для моделей Pydantic за допомогою: - * автозаповнення - * перевірки типу - * рефакторингу - * пошуку - * інспекції +* автозаповнення +* перевірки типу +* рефакторингу +* пошуку +* інспекції + +/// ## Використовуйте модель Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` + +//// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// ## Тіло запиту + параметри шляху @@ -167,17 +189,21 @@ **FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` + +//// ## Тіло запиту + шлях + параметри запиту @@ -185,17 +211,21 @@ **FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` + +//// Параметри функції будуть розпізнаватися наступним чином: @@ -203,10 +233,13 @@ * Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**. * Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту. -!!! note - FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". +/// note + +FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". + +`Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. - `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. +/// ## Без Pydantic diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 199b93839..4720a42ba 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ Спочатку імпортуйте `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Визначення параметрів `Cookie` @@ -48,48 +64,70 @@ Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Бажано використовувати `Annotated` версію, якщо це можливо. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Технічні Деталі" -=== "Python 3.8+ non-Annotated" +`Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. +Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// info -!!! note "Технічні Деталі" - `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. - Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. +Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. -!!! info - Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. +/// ## Підсумки diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 49321ff11..9ef8d5c5d 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. @@ -38,5 +42,8 @@ Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. -!!! note "Примітка" - `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. +/// note | "Примітка" + +`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. + +/// diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 01852803a..54cbd4b00 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Бажано використовувати `Annotated` версію, якщо це можливо. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 725677e42..784da65f5 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -163,10 +163,13 @@ OpenAPI описує схему для вашого API. І ця схема вк `FastAPI` це клас у Python, який надає всю функціональність для API. -!!! note "Технічні деталі" - `FastAPI` це клас, який успадковується безпосередньо від `Starlette`. +/// note | "Технічні деталі" - Ви також можете використовувати всю функціональність <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> у `FastAPI`. +`FastAPI` це клас, який успадковується безпосередньо від `Starlette`. + +Ви також можете використовувати всю функціональність <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> у `FastAPI`. + +/// ### Крок 2: створюємо екземпляр `FastAPI` @@ -195,8 +198,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Додаткова інформація" - "Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). +/// info | "Додаткова інформація" + +"Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). + +/// При створенні API, "шлях" є основним способом розділення "завдань" і "ресурсів". #### Operation @@ -244,16 +250,19 @@ https://example.com/items/foo * шлях `/` * використовуючи <abbr title="an HTTP GET method"><code>get</code> операцію</abbr> -!!! info "`@decorator` Додаткова інформація" - Синтаксис `@something` у Python називається "декоратором". +/// info | "`@decorator` Додаткова інформація" + +Синтаксис `@something` у Python називається "декоратором". - Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін). +Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін). - "Декоратор" приймає функцію нижче і виконує з нею якусь дію. +"Декоратор" приймає функцію нижче і виконує з нею якусь дію. - У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`. +У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`. - Це і є "декоратор операції шляху (path operation decorator)". +Це і є "декоратор операції шляху (path operation decorator)". + +/// Можна також використовувати операції: @@ -268,15 +277,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip "Порада" - Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. +/// tip | "Порада" + +Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. - **FastAPI** не нав'язує жодного певного значення для кожного методу. +**FastAPI** не нав'язує жодного певного значення для кожного методу. - Наведена тут інформація є рекомендацією, а не обов'язковою вимогою. +Наведена тут інформація є рекомендацією, а не обов'язковою вимогою. - Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій. +Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій. +/// ### Крок 4: визначте **функцію операції шляху (path operation function)** @@ -304,8 +315,11 @@ FastAPI викликатиме її щоразу, коли отримає зап {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Примітка" - Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note | "Примітка" + +Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Крок 5: поверніть результат diff --git a/docs/uk/docs/tutorial/index.md b/docs/uk/docs/tutorial/index.md index e5bae74bc..92c3e77a3 100644 --- a/docs/uk/docs/tutorial/index.md +++ b/docs/uk/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...який також включає `uvicorn`, який ви можете використовувати як сервер, який запускає ваш код. -!!! note - Ви також можете встановити його частина за частиною. +/// note - Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: +Ви також можете встановити його частина за частиною. - ``` - pip install fastapi - ``` +Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: - Також встановіть `uvicorn`, щоб він працював як сервер: +``` +pip install fastapi +``` + +Також встановіть `uvicorn`, щоб він працював як сервер: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +І те саме для кожної з опціональних залежностей, які ви хочете використовувати. - І те саме для кожної з опціональних залежностей, які ви хочете використовувати. +/// ## Розширений посібник користувача diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md index 9edb1c8fa..2220d9fa5 100644 --- a/docs/vi/docs/features.md +++ b/docs/vi/docs/features.md @@ -64,10 +64,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` nghĩa là: +/// info - Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` nghĩa là: + +Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Được hỗ trợ từ các trình soạn thảo diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 84d14de55..99d1d207f 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -12,8 +12,11 @@ Bằng việc khai báo kiểu dữ liệu cho các biến của bạn, các tr Nhưng thậm chí nếu bạn không bao giờ sử dụng **FastAPI**, bạn sẽ được lợi từ việc học một ít về chúng. -!!! note - Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. +/// note + +Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. + +/// ## Động lực @@ -170,45 +173,55 @@ Nếu bạn có thể sử dụng **phiên bản cuối cùng của Python**, s Ví dụ, hãy định nghĩa một biến là `list` các `str`. -=== "Python 3.9+" +//// tab | Python 3.9+ - Khai báo biến với cùng dấu hai chấm (`:`). +Khai báo biến với cùng dấu hai chấm (`:`). - Tương tự kiểu dữ liệu `list`. +Tương tự kiểu dữ liệu `list`. - Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: +Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - Từ `typing`, import `List` (với chữ cái `L` viết hoa): +//// tab | Python 3.8+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Từ `typing`, import `List` (với chữ cái `L` viết hoa): - Khai báo biến với cùng dấu hai chấm (`:`). +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Khai báo biến với cùng dấu hai chấm (`:`). - Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. +Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. - Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: +Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -!!! info - Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". +/// info - Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). +Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". + +Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). + +/// Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`". -!!! tip - Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. +/// tip + +Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. + +/// Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách: @@ -224,17 +237,21 @@ Và do vậy, trình soạn thảo biết nó là một `str`, và cung cấp s Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// Điều này có nghĩa là: @@ -249,17 +266,21 @@ Tham số kiểu dữ liệu đầu tiên dành cho khóa của `dict`. Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// Điều này có nghĩa là: @@ -278,17 +299,21 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu <abbr title='cũng được gọi là "toán tử nhị phân"'>sổ dọc (`|`)</abbr>. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`. @@ -308,23 +333,29 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ alternative" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### Sử dụng `Union` hay `Optional` @@ -372,47 +403,53 @@ Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optiona Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ: -=== "Python 3.10+" +//// tab | Python 3.10+ + +Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): - Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +Và tương tự với Python 3.6, từ mô đun `typing`: - Và tương tự với Python 3.6, từ mô đun `typing`: +* `Union` +* `Optional` (tương tự như Python 3.6) +* ...và các kiểu dữ liệu khác. - * `Union` - * `Optional` (tương tự như Python 3.6) - * ...và các kiểu dữ liệu khác. +Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng <abbr title='cũng gọi là "toán tử nhị phân", nhưng ý nghĩa không liên quan ở đây'>sổ dọc ('|')</abbr> để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. - Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng <abbr title='cũng gọi là "toán tử nhị phân", nhưng ý nghĩa không liên quan ở đây'>sổ dọc ('|')</abbr> để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): +Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - Và tương tự với Python 3.6, từ mô đun `typing`: +Và tương tự với Python 3.6, từ mô đun `typing`: - * `Union` - * `Optional` - * ...and others. +* `Union` +* `Optional` +* ...and others. -=== "Python 3.8+" +//// - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...và các kiểu khác. +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...và các kiểu khác. + +//// ### Lớp như kiểu dữ liệu @@ -452,56 +489,71 @@ Và bạn nhận được tất cả sự hỗ trợ của trình soạn thảo Một ví dụ từ tài liệu chính thức của Pydantic: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +Để học nhiều hơn về <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, tham khảo tài liệu của nó</a>. -!!! info - Để học nhiều hơn về <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, tham khảo tài liệu của nó</a>. +/// **FastAPI** được dựa hoàn toàn trên Pydantic. Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. +/// tip + +Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. +/// ## Type Hints với Metadata Annotations Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. - Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. +Nó đã được cài đặt sẵng cùng với **FastAPI**. - Nó đã được cài đặt sẵng cùng với **FastAPI**. +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`. @@ -514,10 +566,13 @@ Bây giờ, bạn chỉ cần biết rằng `Annotated` tồn tại, và nó là Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm. -!!! tip - Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ +/// tip - Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 +Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ + +Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 + +/// ## Các gợi ý kiểu dữ liệu trong **FastAPI** @@ -541,5 +596,8 @@ Với **FastAPI**, bạn khai báo các tham số với gợi ý kiểu và bạ Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn. -!!! info - Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" từ `mypy`</a>. +/// info + +Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" từ `mypy`</a>. + +/// diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index 712f00852..ce808eb91 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note - Câu lệnh `uvicorn main:app` được giải thích như sau: +/// note - * `main`: tệp tin `main.py` (một Python "mô đun"). - * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. - * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. +Câu lệnh `uvicorn main:app` được giải thích như sau: + +* `main`: tệp tin `main.py` (một Python "mô đun"). +* `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. +* `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. + +/// Trong output, có một dòng giống như: @@ -136,10 +139,13 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. -!!! note "Chi tiết kĩ thuật" - `FastAPI` là một class kế thừa trực tiếp `Starlette`. +/// note | "Chi tiết kĩ thuật" + +`FastAPI` là một class kế thừa trực tiếp `Starlette`. - Bạn cũng có thể sử dụng tất cả <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> chức năng với `FastAPI`. +Bạn cũng có thể sử dụng tất cả <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> chức năng với `FastAPI`. + +/// ### Bước 2: Tạo một `FastAPI` "instance" @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". +/// info + +Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". + +/// Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên". @@ -250,16 +259,19 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**". * đường dẫn `/` * sử dụng một <abbr title="an HTTP GET method">toán tử<code>get</code></abbr> -!!! info Thông tin về "`@decorator`" - Cú pháp `@something` trong Python được gọi là một "decorator". +/// info | Thông tin về "`@decorator`" - Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). +Cú pháp `@something` trong Python được gọi là một "decorator". - Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. +Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). - Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. +Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. - Nó là một "**decorator đường dẫn toán tử**". +Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. + +Nó là một "**decorator đường dẫn toán tử**". + +/// Bạn cũng có thể sử dụng với các toán tử khác: @@ -274,14 +286,17 @@ Và nhiều hơn với các toán tử còn lại: * `@app.patch()` * `@app.trace()` -!!! tip - Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. +/// tip + +Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. - **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. +**FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. - Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. +Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. - Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. +Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. + +/// ### Step 4: Định nghĩa **hàm cho đường dẫn toán tử** @@ -309,8 +324,11 @@ Bạn cũng có thể định nghĩa nó như là một hàm thông thường th {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Bước 5: Nội dung trả về diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md index e8a93fe40..dfeeed8c5 100644 --- a/docs/vi/docs/tutorial/index.md +++ b/docs/vi/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn. -!!! note - Bạn cũng có thể cài đặt nó từng phần. +/// note - Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: +Bạn cũng có thể cài đặt nó từng phần. - ``` - pip install fastapi - ``` +Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: - Cũng cài đặt `uvicorn` để làm việc như một server: +``` +pip install fastapi +``` + +Cũng cài đặt `uvicorn` để làm việc như một server: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. - Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. +/// ## Hướng dẫn nâng cao diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md index cbd5a6cde..c59e8e71c 100644 --- a/docs/zh-hant/docs/benchmarks.md +++ b/docs/zh-hant/docs/benchmarks.md @@ -1,34 +1,34 @@ -# 基準測試 - -由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 可用框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。 - -但是在查看基準得分和對比時,請注意以下幾點。 - -## 基準測試和速度 - -當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。 - -具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。 - -該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。 - -層次結構如下: - -* **Uvicorn**:ASGI 伺服器 - * **Starlette**:(使用 Uvicorn)一個網頁微框架 - * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。 - -* **Uvicorn**: - * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。 - * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。 - * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。 -* **Starlette**: - * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。 - * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。 - * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。 -* **FastAPI**: - * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。 - * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。 - * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。 - * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。 - * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。 +# 基準測試 + +由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 可用框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。 + +但是在查看基準得分和對比時,請注意以下幾點。 + +## 基準測試和速度 + +當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。 + +具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。 + +該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。 + +層次結構如下: + +* **Uvicorn**:ASGI 伺服器 + * **Starlette**:(使用 Uvicorn)一個網頁微框架 + * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。 + +* **Uvicorn**: + * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。 + * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。 + * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。 +* **Starlette**: + * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。 + * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。 + * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。 +* **FastAPI**: + * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。 + * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。 + * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。 + * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。 + * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。 diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md index cc671cacf..99277b419 100644 --- a/docs/zh-hant/docs/fastapi-people.md +++ b/docs/zh-hant/docs/fastapi-people.md @@ -45,10 +45,13 @@ FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨ -!!! 提示 - 你也可以成為官方的 FastAPI 專家! +/// 提示 - 只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 +你也可以成為官方的 FastAPI 專家! + +只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 + +/// 你可以查看這些期間的 **FastAPI 專家**: diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md index 2a1e1ed89..1fc634933 100644 --- a/docs/zh/docs/advanced/additional-responses.md +++ b/docs/zh/docs/advanced/additional-responses.md @@ -20,19 +20,23 @@ {!../../../docs_src/additional_responses/tutorial001.py!} ``` +/// note -!!! Note - 请记住,您必须直接返回 `JSONResponse` 。 +请记住,您必须直接返回 `JSONResponse` 。 -!!! Info - `model` 密钥不是OpenAPI的一部分。 - **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 - - 正确的位置是: - - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: - - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: - - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 - - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 +/// +/// info + +`model` 密钥不是OpenAPI的一部分。 +**FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 +- 正确的位置是: + - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: + - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: + - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 + - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 + +/// **在OpenAPI中为该路径操作生成的响应将是:** @@ -163,12 +167,18 @@ {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! Note - - 请注意,您必须直接使用 `FileResponse` 返回图像。 +/// note + +- 请注意,您必须直接使用 `FileResponse` 返回图像。 + +/// + +/// info + +- 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 +- 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 -!!! Info - - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 - - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 +/// ## 组合信息 您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。 diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index 54ec9775b..06320faad 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "警告" - 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 +/// warning | "警告" - FastAPI 不会用模型等对该响应进行序列化。 +当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 - 确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 +FastAPI 不会用模型等对该响应进行序列化。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。 +确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 - 出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 +/// + +/// note | "技术细节" + +你也可以使用 `from starlette.responses import JSONResponse`。 + +出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 + +/// ## OpenAPI 和 API 文档 diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md index b2f6e3559..3d8afbb62 100644 --- a/docs/zh/docs/advanced/advanced-dependencies.md +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -60,12 +60,14 @@ checker(q="somequery") {!../../../docs_src/dependencies/tutorial011.py!} ``` -!!! tip "提示" +/// tip | "提示" - 本章示例有些刻意,也看不出有什么用处。 +本章示例有些刻意,也看不出有什么用处。 - 这个简例只是为了说明高级依赖项的运作机制。 +这个简例只是为了说明高级依赖项的运作机制。 - 在有关安全的章节中,工具函数将以这种方式实现。 +在有关安全的章节中,工具函数将以这种方式实现。 - 只要能理解本章内容,就能理解安全工具背后的运行机制。 +只要能理解本章内容,就能理解安全工具背后的运行机制。 + +/// diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 17fc2830a..52f6acda1 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -37,9 +37,11 @@ browser --> proxy proxy --> server ``` -!!! tip "提示" +/// tip | "提示" - IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 +IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 + +/// API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如: @@ -76,11 +78,13 @@ $ uvicorn main:app --root-path /api/v1 Hypercorn 也支持 `--root-path `选项。 -!!! note "技术细节" +/// note | "技术细节" + +ASGI 规范定义的 `root_path` 就是为了这种用例。 - ASGI 规范定义的 `root_path` 就是为了这种用例。 +并且 `--root-path` 命令行选项支持 `root_path`。 - 并且 `--root-path` 命令行选项支持 `root_path`。 +/// ### 查看当前的 `root_path` @@ -168,9 +172,11 @@ Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶 这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。 -!!! tip "提示" +/// tip | "提示" - 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 +使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 + +/// 接下来,创建 `routes.toml`: @@ -236,9 +242,11 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip "提示" +/// tip | "提示" + +注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 - 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 +/// 打开含 Traefik 端口的 URL,包含路径前缀:<a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app。</a> @@ -281,9 +289,11 @@ $ uvicorn main:app --root-path /api/v1 ## 附加的服务器 -!!! warning "警告" +/// warning | "警告" - 此用例较难,可以跳过。 +此用例较难,可以跳过。 + +/// 默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。 @@ -322,17 +332,21 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip "提示" +/// tip | "提示" + +注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 - 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 +/// <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下:</a> <img src="/img/tutorial/behind-a-proxy/image03.png"> -!!! tip "提示" +/// tip | "提示" + +API 文档与所选的服务器进行交互。 - API 文档与所选的服务器进行交互。 +/// ### 从 `root_path` 禁用自动服务器 diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 155ce2882..9594c72ac 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ 并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。 -!!! note "说明" - 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 +/// note | "说明" + +如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 + +/// ## 使用 `ORJSONResponse` @@ -25,17 +28,21 @@ {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +/// info | "提示" + +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 -!!! tip "小贴士" - `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 +/// +/// tip | "小贴士" +`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 + +/// ## HTML 响应 @@ -48,12 +55,15 @@ {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +/// info | "提示" + +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 + +/// ### 返回一个 `Response` @@ -65,11 +75,17 @@ {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "警告" - *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 +/// warning | "警告" + +*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 + +/// + +/// info | "提示" -!!! info "提示" - 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 +当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 + +/// ### OpenAPI 中的文档和重载 `Response` @@ -99,10 +115,13 @@ 要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import HTMLResponse`。 +/// note | "技术细节" + +你也可以使用 `from starlette.responses import HTMLResponse`。 + +**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 - **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 +/// ### `Response` @@ -151,15 +170,21 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 `UJSONResponse` 是一个使用 <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a> 的可选 JSON 响应。 -!!! warning "警告" - 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 +/// warning | "警告" + +在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "小贴士" - `ORJSONResponse` 可能是一个更快的选择。 +/// tip | "小贴士" + +`ORJSONResponse` 可能是一个更快的选择。 + +/// ### `RedirectResponse` @@ -187,8 +212,11 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 {!../../../docs_src/custom_response/tutorial008.py!} ``` -!!! tip "小贴士" - 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 +/// tip | "小贴士" + +注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 + +/// ### `FileResponse` diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md index 5a93877cc..72567e245 100644 --- a/docs/zh/docs/advanced/dataclasses.md +++ b/docs/zh/docs/advanced/dataclasses.md @@ -20,13 +20,15 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 -!!! info "说明" +/// info | "说明" - 注意,数据类不支持 Pydantic 模型的所有功能。 +注意,数据类不支持 Pydantic 模型的所有功能。 - 因此,开发时仍需要使用 Pydantic 模型。 +因此,开发时仍需要使用 Pydantic 模型。 - 但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 +但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 + +/// ## `response_model` 使用数据类 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index 8e5fa7d12..c9389f533 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -4,9 +4,11 @@ 事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 -!!! warning "警告" +/// warning | "警告" - **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 +**FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 + +/// ## `startup` 事件 @@ -32,20 +34,26 @@ 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 -!!! info "说明" +/// info | "说明" + +`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 + +/// + +/// tip | "提示" - `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 +注意,本例使用 Python `open()` 标准函数与文件交互。 -!!! tip "提示" +这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 - 注意,本例使用 Python `open()` 标准函数与文件交互。 +但 `open()` 函数不支持使用 `async` 与 `await`。 - 这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 +因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 - 但 `open()` 函数不支持使用 `async` 与 `await`。 +/// - 因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 +/// info | "说明" -!!! info "说明" +有关事件处理器的详情,请参阅 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 官档 - 事件</a>。 - 有关事件处理器的详情,请参阅 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 官档 - 事件</a>。 +/// diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index c4ffcb46c..56aad3bd2 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -16,17 +16,21 @@ 让我们从一个简单的 FastAPI 应用开始: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +//// 请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 @@ -111,8 +115,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app <img src="/img/tutorial/generate-clients/image03.png"> -!!! tip - 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 +/// tip + +请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 + +/// 如果发送的数据字段不符,你也会看到编辑器的错误提示: @@ -128,17 +135,21 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### 生成带有标签的 TypeScript 客户端 @@ -185,17 +196,21 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### 使用自定义操作ID生成TypeScript客户端 diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md index e39eed805..6525802fc 100644 --- a/docs/zh/docs/advanced/index.md +++ b/docs/zh/docs/advanced/index.md @@ -6,10 +6,13 @@ 你会在接下来的章节中了解到其他的选项、配置以及额外的特性。 -!!! tip - 接下来的章节**并不一定是**「高级的」。 +/// tip - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节**并不一定是**「高级的」。 + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 06232fe17..764784ce3 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -43,11 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 -!!! note "技术细节" +/// note | "技术细节" - 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 +以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 - **FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 +**FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index e2dadbfb0..7c7323cb5 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -35,9 +35,11 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" - `callback_url` 查询参数使用 Pydantic 的 <a href="https://pydantic-docs.helpmanual.io/usage/types/#urls" class="external-link" target="_blank">URL</a> 类型。 +`callback_url` 查询参数使用 Pydantic 的 <a href="https://pydantic-docs.helpmanual.io/usage/types/#urls" class="external-link" target="_blank">URL</a> 类型。 + +/// 此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。 @@ -62,11 +64,13 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 本例没有实现回调本身(只是一行代码),只有文档部分。 -!!! tip "提示" +/// tip | "提示" + +实际的回调只是 HTTP 请求。 - 实际的回调只是 HTTP 请求。 +实现回调时,要使用 <a href="https://www.encode.io/httpx/" class="external-link" target="_blank">HTTPX</a> 或 <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>。 - 实现回调时,要使用 <a href="https://www.encode.io/httpx/" class="external-link" target="_blank">HTTPX</a> 或 <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>。 +/// ## 编写回调文档代码 @@ -76,11 +80,13 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 -!!! tip "提示" +/// tip | "提示" + +编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 - 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 +临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 - 临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 +/// ### 创建回调的 `APIRouter` @@ -157,9 +163,11 @@ JSON 请求体包含如下内容: } ``` -!!! tip "提示" +/// tip | "提示" - 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 +注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 + +/// ### 添加回调路由 @@ -171,9 +179,11 @@ JSON 请求体包含如下内容: {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" + +注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 - 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 +/// ### 查看文档 diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index 7da9f251e..c37846916 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI 的 operationId -!!! warning - 如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 +/// warning + +如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 + +/// 你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。 @@ -23,13 +26,19 @@ {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip - 如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 +/// tip + +如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 + +/// + +/// warning + +如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 -!!! warning - 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 +即使它们在不同的模块中(Python 文件)。 - 即使它们在不同的模块中(Python 文件)。 +/// ## 从 OpenAPI 中排除 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 3e53c5319..dd942a981 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -28,20 +28,26 @@ {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip - 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 +/// tip - 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 +需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 - 同时,你也应当仅反馈通过`response_model`过滤过的数据。 +所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 + +同时,你也应当仅反馈通过`response_model`过滤过的数据。 + +/// ### 更多信息 -!!! note "技术细节" - 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 +/// note | "技术细节" + +你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 + +为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 - 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 +因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 - 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 +/// 如果你想查看所有可用的参数和选项,可以参考 <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">Starlette帮助文档</a> diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 797a878eb..b2c7de8fd 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。 -!!! tip "小贴士" - `JSONResponse` 本身是一个 `Response` 的子类。 +/// tip | "小贴士" + +`JSONResponse` 本身是一个 `Response` 的子类。 + +/// 当你返回一个 `Response` 时,**FastAPI** 会直接传递它。 @@ -36,10 +39,13 @@ {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。 +/// note | "技术细节" + +你也可以使用 `from starlette.responses import JSONResponse`。 + +出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 - 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 +/// ## 返回自定义 `Response` diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index 229efffcb..e18d1620d 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -25,12 +25,15 @@ ``` -!!! note "技术细节" - 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 +/// note | "技术细节" - **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 +你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 - 由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 +**FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 + +由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 + +/// ## 自定义头部 diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index ab8961e7c..a76353186 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,35 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `password` -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` +```Python hl_lines="4 8 12" +{!> ../../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../../docs_src/security/tutorial006_an.py!} +``` - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="2 6 10" +{!> ../../../docs_src/security/tutorial006.py!} +``` + +//// 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -59,26 +68,36 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 11-21" +{!> ../../../docs_src/security/tutorial007.py!} +``` + +//// - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` 这类似于: ```Python @@ -141,23 +160,32 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="23-27" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md index e2bef4765..836086ae2 100644 --- a/docs/zh/docs/advanced/security/index.md +++ b/docs/zh/docs/advanced/security/index.md @@ -4,10 +4,13 @@ 除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. -!!! tip "小贴士" - 接下来的章节 **并不一定是 "高级的"**. +/// tip | "小贴士" - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节 **并不一定是 "高级的"**. + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index e5eeffb0a..b75ae11a4 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -10,19 +10,21 @@ OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证 本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 -!!! warning "警告" +/// warning | "警告" - 本章内容较难,刚接触 FastAPI 的新手可以跳过。 +本章内容较难,刚接触 FastAPI 的新手可以跳过。 - OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 +OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 - 但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 +但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 - 不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 +不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 - 很多情况下,OAuth2 作用域就像一把牛刀。 +很多情况下,OAuth2 作用域就像一把牛刀。 - 但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 +但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 + +/// ## OAuth2 作用域与 OpenAPI @@ -44,15 +46,17 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info "说明" +/// info | "说明" + +OAuth2 中,**作用域**只是声明特定权限的字符串。 - OAuth2 中,**作用域**只是声明特定权限的字符串。 +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 +这些细节只是特定的实现方式。 - 这些细节只是特定的实现方式。 +对 OAuth2 来说,它们都只是字符串而已。 - 对 OAuth2 来说,它们都只是字符串而已。 +/// ## 全局纵览 @@ -90,11 +94,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 这样,返回的 JWT 令牌中就包含了作用域。 -!!! danger "危险" +/// danger | "危险" - 为了简明起见,本例把接收的作用域直接添加到了令牌里。 +为了简明起见,本例把接收的作用域直接添加到了令牌里。 - 但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 +但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 + +/// ```Python hl_lines="153" {!../../../docs_src/security/tutorial005.py!} @@ -116,23 +122,27 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 本例要求使用作用域 `me`(还可以使用更多作用域)。 -!!! note "笔记" +/// note | "笔记" + +不必在不同位置添加不同的作用域。 - 不必在不同位置添加不同的作用域。 +本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 - 本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 +/// ```Python hl_lines="4 139 166" {!../../../docs_src/security/tutorial005.py!} ``` -!!! info "技术细节" +/// info | "技术细节" - `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 +`Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 - 但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 +但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 - 但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 +但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 + +/// ## 使用 `SecurityScopes` @@ -221,11 +231,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` -!!! tip "提示" +/// tip | "提示" + +此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 - 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 +所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 - 所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 +/// ## `SecurityScopes` 的更多细节 @@ -263,11 +275,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 -!!! note "笔记" +/// note | "笔记" + +每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 - 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 +但归根结底,它们使用的都是 OAuth2 标准。 - 但归根结底,它们使用的都是 OAuth2 标准。 +/// **FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index d793b9c7f..37a2d98d3 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -8,44 +8,51 @@ ## 环境变量 -!!! tip - 如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 +/// tip + +如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 + +/// 环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。 您可以在 shell 中创建和使用环境变量,而无需使用 Python: -=== "Linux、macOS、Windows Bash" +//// tab | Linux、macOS、Windows Bash + +<div class="termy"> + +```console +// 您可以创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" - <div class="termy"> +// 然后您可以与其他程序一起使用它,例如 +$ echo "Hello $MY_NAME" - ```console - // 您可以创建一个名为 MY_NAME 的环境变量 - $ export MY_NAME="Wade Wilson" +Hello Wade Wilson +``` - // 然后您可以与其他程序一起使用它,例如 - $ echo "Hello $MY_NAME" +</div> - Hello Wade Wilson - ``` +//// - </div> +//// tab | Windows PowerShell -=== "Windows PowerShell" +<div class="termy"> - <div class="termy"> +```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" - ```console - // 创建一个名为 MY_NAME 的环境变量 - $ $Env:MY_NAME = "Wade Wilson" +// 与其他程序一起使用它,例如 +$ echo "Hello $Env:MY_NAME" - // 与其他程序一起使用它,例如 - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +</div> - </div> +//// ### 在 Python 中读取环境变量 @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 的第二个参数是要返回的默认值。 +/// tip + +<a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 的第二个参数是要返回的默认值。 - 如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 +如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 + +/// 然后,您可以调用该 Python 程序: @@ -116,8 +126,11 @@ Hello World from Python </div> -!!! tip - 您可以在 <a href="https://12factor.net/config" class="external-link" target="_blank">Twelve-Factor App: Config</a> 中阅读更多相关信息。 +/// tip + +您可以在 <a href="https://12factor.net/config" class="external-link" target="_blank">Twelve-Factor App: Config</a> 中阅读更多相关信息。 + +/// ### 类型和验证 @@ -141,8 +154,11 @@ Hello World from Python {!../../../docs_src/settings/tutorial001.py!} ``` -!!! tip - 如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 +/// tip + +如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 + +/// 然后,当您创建该 `Settings` 类的实例(在此示例中是 `settings` 对象)时,Pydantic 将以不区分大小写的方式读取环境变量,因此,大写的变量 `APP_NAME` 仍将为属性 `app_name` 读取。 @@ -170,8 +186,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app </div> -!!! tip - 要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 +/// tip + +要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 + +/// 然后,`admin_email` 设置将为 `"deadpool@example.com"`。 @@ -194,8 +213,12 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app ```Python hl_lines="3 11-13" {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip - 您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 + +/// tip + +您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 + +/// ## 在依赖项中使用设置 @@ -217,54 +240,75 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 现在我们创建一个依赖项,返回一个新的 `config.Settings()`。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ 非注解版本 - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip -=== "Python 3.8+ 非注解版本" +如果可能,请尽量使用 `Annotated` 版本。 - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// -!!! tip - 我们稍后会讨论 `@lru_cache`。 +/// tip - 目前,您可以将 `get_settings()` 视为普通函数。 +我们稍后会讨论 `@lru_cache`。 + +目前,您可以将 `get_settings()` 视为普通函数。 + +/// 然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ 非注解版本 -=== "Python 3.8+ 非注解版本" +/// tip - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +如果可能,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// ### 设置和测试 @@ -284,15 +328,21 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 这种做法相当常见,有一个名称,这些环境变量通常放在一个名为 `.env` 的文件中,该文件被称为“dotenv”。 -!!! tip - 以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 +/// tip - 但是,dotenv 文件实际上不一定要具有确切的文件名。 +以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 + +但是,dotenv 文件实际上不一定要具有确切的文件名。 + +/// Pydantic 支持使用外部库从这些类型的文件中读取。您可以在<a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic 设置: Dotenv (.env) 支持</a>中阅读更多相关信息。 -!!! tip - 要使其工作,您需要执行 `pip install python-dotenv`。 +/// tip + +要使其工作,您需要执行 `pip install python-dotenv`。 + +/// ### `.env` 文件 @@ -313,8 +363,11 @@ APP_NAME="ChimichangApp" 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 -!!! tip - `Config` 类仅用于 Pydantic 配置。您可以在<a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic Model Config</a>中阅读更多相关信息。 +/// tip + +`Config` 类仅用于 Pydantic 配置。您可以在<a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic Model Config</a>中阅读更多相关信息。 + +/// ### 使用 `lru_cache` 仅创建一次 `Settings` @@ -339,26 +392,35 @@ def get_settings(): 但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +//// tab | Python 3.8+ 非注解版本 -=== "Python 3.8+ 非注解版本" +/// tip - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +如果可能,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// 然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index 612b69176..b09644e39 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -31,20 +31,26 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note "笔记" +/// note | "笔记" - 在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 - 并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 +在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 +并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 -!!! tip "提示" +/// - 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 +/// tip | "提示" -!!! note "技术细节" +通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 - 您还可以使用 `from starlette.templating import Jinja2Templates`。 +/// - **FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 +/// note | "技术细节" + +您还可以使用 `from starlette.templating import Jinja2Templates`。 + +**FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 + +/// ## 编写模板 diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md index 8dc95c25f..58bf9af8c 100644 --- a/docs/zh/docs/advanced/testing-database.md +++ b/docs/zh/docs/advanced/testing-database.md @@ -52,11 +52,13 @@ {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip "提示" +/// tip | "提示" - 为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 +为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 - 为了把注意力集中在测试代码上,本例只是复制了这段代码。 +为了把注意力集中在测试代码上,本例只是复制了这段代码。 + +/// ## 创建数据库 @@ -82,9 +84,11 @@ Base.metadata.create_all(bind=engine) {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip "提示" +/// tip | "提示" + +`overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 - `overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 +/// ## 测试应用 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index 487f5ebf5..cc9a38200 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -32,13 +32,15 @@ {!../../../docs_src/dependency_testing/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" - **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 +**FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 - 原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 +原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 - FastAPI 可以覆盖这些位置的依赖项。 +FastAPI 可以覆盖这些位置的依赖项。 + +/// 然后,使用 `app.dependency_overrides` 把覆盖依赖项重置为空**字典**: @@ -46,6 +48,8 @@ app.dependency_overrides = {} ``` -!!! tip "提示" +/// tip | "提示" + +如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 - 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 +/// diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index f303e1d67..795b73945 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -8,6 +8,8 @@ {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "笔记" +/// note | "笔记" - 更多细节详见 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Starlette 官档 - 测试 WebSockets</a>。 +更多细节详见 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Starlette 官档 - 测试 WebSockets</a>。 + +/// diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index 1842c2e27..bc9e898d9 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -35,20 +35,24 @@ 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 -!!! tip "提示" +/// tip | "提示" - 注意,本例除了声明请求参数之外,还声明了路径参数。 +注意,本例除了声明请求参数之外,还声明了路径参数。 - 因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 +因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 - 同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 +同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 + +/// ## `Request` 文档 更多细节详见 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette 官档 - `Request` 对象</a>。 -!!! note "技术细节" +/// note | "技术细节" + +您也可以使用 `from starlette.requests import Request`。 - 您也可以使用 `from starlette.requests import Request`。 +**FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 - **FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 +/// diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index a5cbdd965..3fcc36dfe 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -46,10 +46,13 @@ $ pip install websockets {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "技术细节" - 您也可以使用 `from starlette.websockets import WebSocket`。 +/// note | "技术细节" - **FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 +您也可以使用 `from starlette.websockets import WebSocket`。 + +**FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 + +/// ## 等待消息并发送消息 @@ -106,46 +109,65 @@ $ uvicorn main:app --reload 它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ 非带注解版本 -=== "Python 3.9+" +/// tip - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +如果可能,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ 非带注解版本" +//// tab | Python 3.8+ 非带注解版本 - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// tip - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +如果可能,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+ 非带注解版本" +/// + +```Python hl_lines="68-69 81" +{!> ../../../docs_src/websockets/tutorial002.py!} +``` - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - 由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 +由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 - 您可以使用<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">规范中定义的有效代码</a>。 +您可以使用<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">规范中定义的有效代码</a>。 + +/// ### 尝试带有依赖项的 WebSockets @@ -164,8 +186,11 @@ $ uvicorn main:app --reload * "Item ID",用于路径。 * "Token",作为查询参数。 -!!! tip - 注意,查询参数 `token` 将由依赖项处理。 +/// tip + +注意,查询参数 `token` 将由依赖项处理。 + +/// 通过这样,您可以连接 WebSocket,然后发送和接收消息: @@ -175,17 +200,21 @@ $ uvicorn main:app --reload 当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。 -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// 尝试以下操作: @@ -199,12 +228,15 @@ $ uvicorn main:app --reload Client #1596980209979 left the chat ``` -!!! tip - 上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 +/// tip + +上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 + +但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 - 但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 +如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 - 如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 +/// ## 更多信息 diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index b34ef63e0..822ceeee4 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - 你只能在被 `async def` 创建的函数内使用 `await` +/// note + +你只能在被 `async def` 创建的函数内使用 `await` + +/// --- @@ -136,8 +139,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 <img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration"> -!!! info - 漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -199,8 +205,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。 -!!! info - 漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 +/// info + +漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 + +/// --- @@ -392,12 +401,15 @@ Starlette (和 **FastAPI**) 是基于 <a href="https://anyio.readthedocs.io/ ## 非常技术性的细节 -!!! warning - 你可以跳过这里。 +/// warning + +你可以跳过这里。 + +这些都是 FastAPI 如何在内部工作的技术细节。 - 这些都是 FastAPI 如何在内部工作的技术细节。 +如果您有相当多的技术知识(协程、线程、阻塞等),并且对 FastAPI 如何处理 `async def` 与常规 `def` 感到好奇,请继续。 - 如果您有相当多的技术知识(协程、线程、阻塞等),并且对 FastAPI 如何处理 `async def` 与常规 `def` 感到好奇,请继续。 +/// ### 路径操作函数 diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md index 91be2edbb..85b341a8d 100644 --- a/docs/zh/docs/contributing.md +++ b/docs/zh/docs/contributing.md @@ -24,63 +24,73 @@ $ python -m venv env 使用以下方法激活新环境: -=== "Linux, macOS" +//// tab | Linux, macOS - <div class="termy"> +<div class="termy"> - ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +<div class="termy"> - </div> +```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +</div> + +//// + +//// tab | Windows Bash - Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): +Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): - <div class="termy"> +<div class="termy"> + +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +</div> - </div> +//// 要检查操作是否成功,运行: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash - <div class="termy"> +<div class="termy"> - ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` - </div> +</div> -=== "Windows PowerShell" +//// - <div class="termy"> +//// tab | Windows PowerShell - ```console - $ Get-Command pip +<div class="termy"> - some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` - </div> +</div> + +//// 如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip </div> -!!! tip - 每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 +/// tip + +每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 - 这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 +这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 + +/// ### pip @@ -125,10 +138,13 @@ $ pip install -r requirements.txt 这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 -!!! note "技术细节" - 仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 +/// note | "技术细节" + +仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 - 这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 +这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 + +/// ### 格式化 @@ -170,20 +186,23 @@ $ python ./scripts/docs.py live 这样,你可以编辑文档 / 源文件并实时查看更改。 -!!! tip - 或者你也可以手动执行和该脚本一样的操作 +/// tip - 进入语言目录,如果是英文文档,目录则是 `docs/en/`: +或者你也可以手动执行和该脚本一样的操作 - ```console - $ cd docs/en/ - ``` +进入语言目录,如果是英文文档,目录则是 `docs/en/`: - 在该目录执行 `mkdocs` 命令 +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +在该目录执行 `mkdocs` 命令 + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer CLI (可选) @@ -210,8 +229,11 @@ Completion will take effect once you restart the terminal. 在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。 -!!! tip - 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 +/// tip + +你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 + +/// 所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 @@ -256,10 +278,13 @@ $ uvicorn tutorial001:app --reload * 在当前 <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">已有的 pull requests</a> 中查找你使用的语言,添加要求修改或同意合并的评审意见。 -!!! tip - 你可以为已有的 pull requests <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">添加包含修改建议的评论</a>。 +/// tip + +你可以为已有的 pull requests <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">添加包含修改建议的评论</a>。 + +详情可查看关于 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">添加 pull request 评审意见</a> 以同意合并或要求修改的文档。 - 详情可查看关于 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">添加 pull request 评审意见</a> 以同意合并或要求修改的文档。 +/// * 检查在 <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 @@ -283,8 +308,11 @@ $ uvicorn tutorial001:app --reload 对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 -!!! tip - 默认语言是英语,位于 `docs/en/`目录。 +/// tip + +默认语言是英语,位于 `docs/en/`目录。 + +/// 现在为西班牙语文档运行实时服务器: @@ -301,20 +329,23 @@ $ python ./scripts/docs.py live es </div> -!!! tip - 或者你也可以手动执行和该脚本一样的操作 +/// tip + +或者你也可以手动执行和该脚本一样的操作 - 进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: +进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +在该目录执行 `mkdocs` 命令 - 在该目录执行 `mkdocs` 命令 +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// 现在你可以访问 <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> 实时查看你所做的更改。 @@ -334,8 +365,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - 注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 +/// tip + +注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 + +/// 回到浏览器你就可以看到刚刚更新的章节了。🎉 @@ -370,8 +404,11 @@ Successfully initialized: docs/ht INHERIT: ../en/mkdocs.yml ``` -!!! tip - 你也可以自己手动创建包含这些内容的文件。 +/// tip + +你也可以自己手动创建包含这些内容的文件。 + +/// 这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。 diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md index 86d995b75..7a0b6c3d2 100644 --- a/docs/zh/docs/deployment/concepts.md +++ b/docs/zh/docs/deployment/concepts.md @@ -154,11 +154,13 @@ 但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次...... -!!! tip +/// tip - ...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 +...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 - 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + +/// 您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。 @@ -245,11 +247,13 @@ -!!! tip +/// tip + +如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 - 如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 + 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 - 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +/// ## 启动之前的步骤 @@ -265,12 +269,13 @@ 当然,也有一些情况,多次运行前面的步骤也没有问题,这样的话就好办多了。 -!!! tip +/// tip - 另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 +另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 - 在这种情况下,您就不必担心这些。 🤷 + 在这种情况下,您就不必担心这些。 🤷 +/// ### 前面步骤策略的示例 @@ -282,9 +287,11 @@ * 一个 bash 脚本,运行前面的步骤,然后启动您的应用程序 * 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。 -!!! tip +/// tip + +我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 - 我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +/// ## 资源利用率 diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md index 782c6d578..e5f66dba1 100644 --- a/docs/zh/docs/deployment/docker.md +++ b/docs/zh/docs/deployment/docker.md @@ -4,9 +4,11 @@ 使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。 -!!! tip - 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。 +/// tip +赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。 + +/// <details> <summary>Dockerfile Preview 👀</summary> @@ -137,10 +139,13 @@ Successfully installed fastapi pydantic uvicorn </div> -!!! info - 还有其他文件格式和工具来定义和安装依赖项。 +/// info + +还有其他文件格式和工具来定义和安装依赖项。 + + 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 - 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 +/// ### 创建 **FastAPI** 代码 @@ -232,8 +237,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 因为程序将从`/code`启动,并且其中包含你的代码的目录`./app`,所以**Uvicorn**将能够从`app.main`中查看并**import**`app`。 -!!! tip - 通过单击代码中的每个数字气泡来查看每行的作用。 👆 +/// tip + +通过单击代码中的每个数字气泡来查看每行的作用。 👆 + +/// 你现在应该具有如下目录结构: ``` @@ -306,10 +314,13 @@ $ docker build -t myimage . </div> -!!! tip - 注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 +/// tip - 在本例中,它是相同的当前目录(`.`)。 +注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 + +在本例中,它是相同的当前目录(`.`)。 + +/// ### 启动 Docker 容器 @@ -409,8 +420,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 它可以是另一个容器,例如使用 <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>,处理 **HTTPS** 和 **自动**获取**证书**。 -!!! tip - Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 +/// tip + +Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 + +/// 或者,HTTPS 可以由云服务商作为其服务之一进行处理(同时仍在容器中运行应用程序)。 @@ -439,8 +453,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 由于该组件将接受请求的**负载**并(希望)以**平衡**的方式在worker之间分配该请求,因此它通常也称为**负载均衡器**。 -!!! tip - 用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 +/// tip + +用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 + +/// 当使用容器时,你用来启动和管理容器的同一系统已经具有内部工具来传输来自该**负载均衡器**(也可以是**TLS 终止代理**) 的**网络通信**(例如HTTP请求)到你的应用程序容器。 @@ -526,8 +543,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 如果你有 **多个容器**,可能每个容器都运行一个 **单个进程**(例如,在 **Kubernetes** 集群中),那么你可能希望有一个 **单独的容器** 执行以下操作: 在单个容器中运行单个进程执行**先前步骤**,即运行复制的worker容器之前。 -!!! info - 如果你使用 Kubernetes,这可能是 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>。 +/// info + +如果你使用 Kubernetes,这可能是 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>。 + +/// 如果在你的用例中,运行前面的步骤**并行多次**没有问题(例如,如果你没有运行数据库迁移,而只是检查数据库是否已准备好),那么你也可以将它们放在开始主进程之前在每个容器中。 @@ -546,8 +566,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. -!!! warning - 你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 +/// warning + +你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 + +/// 该镜像包含一个**自动调整**机制,用于根据可用的 CPU 核心设置**worker进程数**。 @@ -555,8 +578,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 它还支持通过一个脚本运行<a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**开始前的先前步骤** </a>。 -!!! tip - 要查看所有配置和选项,请转到 Docker 镜像页面: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank" >tiangolo/uvicorn-gunicorn-fastapi</a>。 +/// tip + +要查看所有配置和选项,请转到 Docker 镜像页面: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank" >tiangolo/uvicorn-gunicorn-fastapi</a>。 + +/// ### 官方 Docker 镜像上的进程数 @@ -686,8 +712,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. 运行`uvicorn`命令,告诉它使用从`app.main`导入的`app`对象。 -!!! tip - 单击气泡数字可查看每行的作用。 +/// tip + +单击气泡数字可查看每行的作用。 + +/// **Docker stage** 是 `Dockerfile` 的一部分,用作 **临时容器镜像**,仅用于生成一些稍后使用的文件。 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md index cf01a4585..e5d66482a 100644 --- a/docs/zh/docs/deployment/https.md +++ b/docs/zh/docs/deployment/https.md @@ -69,8 +69,11 @@ 这个操作一般只需要在最开始执行一次。 -!!! tip - 域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 +/// tip + +域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 + +/// ### DNS @@ -116,8 +119,11 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 这就是 **HTTPS**,它只是 **安全 TLS 连接** 内的普通 **HTTP**,而不是纯粹的(未加密的)TCP 连接。 -!!! tip - 请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 +/// tip + +请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 + +/// ### HTTPS 请求 diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md index ca7142613..30ee7a1e9 100644 --- a/docs/zh/docs/deployment/manually.md +++ b/docs/zh/docs/deployment/manually.md @@ -23,77 +23,89 @@ 您可以使用以下命令安装 ASGI 兼容服务器: -=== "Uvicorn" +//// tab | Uvicorn - * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 +* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 - <div class="termy"> +<div class="termy"> + +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` - ```console - $ pip install "uvicorn[standard]" +</div> + +/// tip - ---> 100% - ``` +通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 - </div> +其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 - !!! tip - 通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 +/// - 其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 +//// -=== "Hypercorn" +//// tab | Hypercorn - * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>,一个也与 HTTP/2 兼容的 ASGI 服务器。 +* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>,一个也与 HTTP/2 兼容的 ASGI 服务器。 - <div class="termy"> +<div class="termy"> - ```console - $ pip install hypercorn +```console +$ pip install hypercorn - ---> 100% - ``` +---> 100% +``` - </div> +</div> - ...或任何其他 ASGI 服务器。 +...或任何其他 ASGI 服务器。 +//// ## 运行服务器程序 您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如: -=== "Uvicorn" +//// tab | Uvicorn + +<div class="termy"> + +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - <div class="termy"> +</div> - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn - </div> +<div class="termy"> +```console +$ hypercorn main:app --bind 0.0.0.0:80 -=== "Hypercorn" +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - <div class="termy"> +</div> - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning - </div> +如果您正在使用`--reload`选项,请记住删除它。 -!!! warning - 如果您正在使用`--reload`选项,请记住删除它。 + `--reload` 选项消耗更多资源,并且更不稳定。 - `--reload` 选项消耗更多资源,并且更不稳定。 + 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 - 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 +/// ## Hypercorn with Trio diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md index 330ddb3d7..eb0252a5c 100644 --- a/docs/zh/docs/deployment/server-workers.md +++ b/docs/zh/docs/deployment/server-workers.md @@ -17,12 +17,13 @@ 在这里我将向您展示如何将 <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> 与 **Uvicorn worker 进程** 一起使用。 -!!! info - 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +/// info - 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +/// ## Gunicorn with Uvicorn Workers diff --git a/docs/zh/docs/deployment/versions.md b/docs/zh/docs/deployment/versions.md index 75b870139..228bb0765 100644 --- a/docs/zh/docs/deployment/versions.md +++ b/docs/zh/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI 还遵循这样的约定:任何`PATCH`版本更改都是为了bug修复和non-breaking changes。 -!!! tip - "PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 +/// tip + +"PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 + +/// 因此,你应该能够固定到如下版本: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 "MINOR"版本中会添加breaking changes和新功能。 -!!! tip - "MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 +/// tip + +"MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 + +/// ## 升级FastAPI版本 diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md index dd3914921..00235bd02 100644 --- a/docs/zh/docs/fastapi-cli.md +++ b/docs/zh/docs/fastapi-cli.md @@ -80,5 +80,8 @@ FastAPI CLI 接收你的 Python 程序路径,自动检测包含 FastAPI 的变 在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。 -!!! tip "提示" - 你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 +/// tip | "提示" + +你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 + +/// diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md index 87e6c8e6b..30a75240c 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -45,10 +45,13 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨ -!!! 小提示 - 你也可以成为认可的 FastAPI 专家! +/// 小提示 - 只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 +你也可以成为认可的 FastAPI 专家! + +只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 + +/// 你可以查看不同时期的 **FastAPI 专家**: diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index d8190032f..24dc3e8ce 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -65,10 +65,13 @@ my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` 意思是: +/// info - 直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` 意思是: + +直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 编辑器支持 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index e3aa5575c..fc47ed89d 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -108,11 +108,13 @@ 快加入 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord 聊天服务器</a> 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。 -!!! tip "提示" +/// tip | "提示" - 如有问题,请在 <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 +如有问题,请在 <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 - 聊天室仅供闲聊。 +聊天室仅供闲聊。 + +/// ### 别在聊天室里提问 diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md index c0688c72a..262dcfaee 100644 --- a/docs/zh/docs/how-to/index.md +++ b/docs/zh/docs/how-to/index.md @@ -6,6 +6,8 @@ 如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 -!!! 小技巧 +/// 小技巧 - 如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 +如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 + +/// diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index 214b47611..c78852539 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -12,8 +12,11 @@ 但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。 -!!! note - 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 +/// note + +如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 + +/// ## 动机 @@ -253,8 +256,11 @@ John Doe {!../../../docs_src/python_types/tutorial010.py!} ``` -!!! info - 想进一步了解 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic,请阅读其文档</a>. +/// info + +想进一步了解 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic,请阅读其文档</a>. + +/// 整个 **FastAPI** 建立在 Pydantic 的基础之上。 @@ -282,5 +288,8 @@ John Doe 最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。 -!!! info - 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">来自 `mypy` 的"速查表"</a>是不错的资源。 +/// info + +如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">来自 `mypy` 的"速查表"</a>是不错的资源。 + +/// diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index 94b75d4fd..95fd7b6b5 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -57,41 +57,57 @@ **FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="14 16 23 26" +{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ 没Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.10+ 没Annotated" +/// + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ 没Annotated -=== "Python 3.8+ 没Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// 该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 422cd7c16..a0c7095e9 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。 -!!! info - 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 +/// info + +如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 + +/// ## 一个文件结构示例 @@ -26,16 +29,19 @@ │ └── admin.py ``` -!!! tip - 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 +/// tip + +上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 - 这就是能将代码从一个文件导入到另一个文件的原因。 +这就是能将代码从一个文件导入到另一个文件的原因。 - 例如,在 `app/main.py` 中,你可以有如下一行: +例如,在 `app/main.py` 中,你可以有如下一行: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。 * 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。 @@ -99,8 +105,11 @@ 所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。 -!!! tip - 在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 +/// tip + +在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 + +/// 我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。 @@ -116,10 +125,13 @@ {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 我们正在使用虚构的请求首部来简化此示例。 +/// tip + +我们正在使用虚构的请求首部来简化此示例。 + +但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。 - 但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。 +/// ## 其他使用 `APIRouter` 的模块 @@ -163,8 +175,11 @@ async def read_item(item_id: str): 我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。 -!!! tip - 请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 +/// tip + +请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 + +/// 最终结果是项目相关的路径现在为: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。 * 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。 -!!! tip - 在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 +/// tip + +在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 + +/// + +/// check -!!! check - `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 +`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 + +/// ### 导入依赖项 @@ -201,8 +222,11 @@ async def read_item(item_id: str): #### 相对导入如何工作 -!!! tip - 如果你完全了解导入的工作原理,请从下面的下一部分继续。 +/// tip + +如果你完全了解导入的工作原理,请从下面的下一部分继续。 + +/// 一个单点 `.`,例如: @@ -269,10 +293,13 @@ from ...dependencies import get_token_header {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 最后的这个路径操作将包含标签的组合:`["items","custom"]`。 +/// tip + +最后的这个路径操作将包含标签的组合:`["items","custom"]`。 - 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 +并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 + +/// ## `FastAPI` 主体 @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 第一个版本是「相对导入」: +/// info + +第一个版本是「相对导入」: - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 第二个版本是「绝对导入」: +第二个版本是「绝对导入」: + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +要了解有关 Python 包和模块的更多信息,请查阅<a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">关于 Modules 的 Python 官方文档</a>。 - 要了解有关 Python 包和模块的更多信息,请查阅<a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">关于 Modules 的 Python 官方文档</a>。 +/// ### 避免名称冲突 @@ -372,26 +402,35 @@ from .routers.users import router {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 +/// info - `items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 +`users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 + +`items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 + +/// 使用 `app.include_router()`,我们可以将每个 `APIRouter` 添加到主 `FastAPI` 应用程序中。 它将包含来自该路由器的所有路由作为其一部分。 -!!! note "技术细节" - 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 +/// note | "技术细节" + +实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 + +所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 + +/// - 所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 +/// check -!!! check - 包含路由器时,你不必担心性能问题。 +包含路由器时,你不必担心性能问题。 - 这将花费几微秒时间,并且只会在启动时发生。 +这将花费几微秒时间,并且只会在启动时发生。 - 因此,它不会影响性能。⚡ +因此,它不会影响性能。⚡ + +/// ### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter` @@ -438,16 +477,19 @@ from .routers.users import router 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 -!!! info "特别的技术细节" - **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 +/// info | "特别的技术细节" + +**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 + +--- - --- +`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 - `APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 +这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 - 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 +由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 - 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 +/// ## 查看自动化的 API 文档 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index 6c68f1008..6e4c385dd 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -6,101 +6,139 @@ 首先,从 Pydantic 中导入 `Field`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -!!! warning "警告" +/// - 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "警告" + +注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 + +/// ## 声明模型属性 然后,使用 `Field` 定义模型的属性: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +/// + +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 -!!! note "技术细节" +/// note | "技术细节" + +实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 + +Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 - 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 +`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。 - Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 +注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。 - `Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。 +/// tip | "提示" -!!! tip "提示" +注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 - 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 +/// ## 添加更多信息 diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index c93ef2f5c..fe951e544 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// note - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 -!!! note - 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 +/// ## 多个请求体参数 @@ -62,17 +81,21 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -93,9 +116,11 @@ } ``` -!!! note - 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 +/// note +请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 + +/// **FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。 @@ -112,41 +137,57 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +//// 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -181,45 +222,63 @@ q: str = None 比如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.9+" +/// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +/// info -!!! info - `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +/// ## 嵌入单个请求体参数 @@ -235,41 +294,57 @@ item: Item = Body(embed=True) 比如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 3f519ae33..26837abc6 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -51,23 +55,29 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Set 类型 @@ -77,23 +87,29 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -115,45 +131,57 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -186,23 +214,29 @@ Pydantic 模型的每个属性都具有类型。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -210,23 +244,29 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -254,33 +294,45 @@ Pydantic 模型的每个属性都具有类型。 } ``` -!!! info - 请注意 `images` 键现在具有一组 image 对象是如何发生的。 +/// info + +请注意 `images` 键现在具有一组 image 对象是如何发生的。 + +/// ## 深度嵌套模型 你可以定义任意深度的嵌套模型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 -!!! info - 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 +/// ## 纯列表请求体 @@ -292,17 +344,21 @@ images: List[Image] 例如: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## 无处不在的编辑器支持 @@ -332,26 +388,33 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +请记住 JSON 仅支持将 `str` 作为键。 -!!! tip - 请记住 JSON 仅支持将 `str` 作为键。 +但是 Pydantic 具有自动转换数据的功能。 - 但是 Pydantic 具有自动转换数据的功能。 +这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 - 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 +然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 - 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 +/// ## 总结 diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index e529fc914..6c74d12e0 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -34,15 +34,17 @@ 即,只发送要更新的数据,其余数据保持不变。 -!!! note "笔记" +/// note | "笔记" - `PATCH` 没有 `PUT` 知名,也怎么不常用。 +`PATCH` 没有 `PUT` 知名,也怎么不常用。 - 很多人甚至只用 `PUT` 实现部分更新。 +很多人甚至只用 `PUT` 实现部分更新。 - **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 +**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 - 但本指南也会分别介绍这两种操作各自的用途。 +但本指南也会分别介绍这两种操作各自的用途。 + +/// ### 使用 Pydantic 的 `exclude_unset` 参数 @@ -87,15 +89,19 @@ {!../../../docs_src/body_updates/tutorial002.py!} ``` -!!! tip "提示" +/// tip | "提示" + +实际上,HTTP `PUT` 也可以完成相同的操作。 +但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 + +/// - 实际上,HTTP `PUT` 也可以完成相同的操作。 - 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 +/// note | "笔记" -!!! note "笔记" +注意,输入模型仍需验证。 - 注意,输入模型仍需验证。 +因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 - 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 +为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 - 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 +/// diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 65d459cd1..c47abec77 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -8,29 +8,35 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 模型声明**请求体**,能充分利用它的功能和优点。 -!!! info "说明" +/// info | "说明" - 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 +发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 - 规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。 +规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。 - 我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。 +我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。 + +/// ## 导入 Pydantic 的 `BaseModel` 从 `pydantic` 中导入 `BaseModel`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ## 创建数据模型 @@ -38,17 +44,21 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Python 标准类型声明所有属性: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// 与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 @@ -76,17 +86,21 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ……此处,请求体参数的类型为 `Item` 模型。 @@ -135,33 +149,39 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 <img src="/img/tutorial/body/image05.png"> -!!! tip "提示" +/// tip | "提示" + +使用 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 编辑器时,推荐安装 <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm 插件</a>。 - 使用 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 编辑器时,推荐安装 <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm 插件</a>。 +该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下: - 该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下: +* 自动补全 +* 类型检查 +* 代码重构 +* 查找 +* 代码审查 - * 自动补全 - * 类型检查 - * 代码重构 - * 查找 - * 代码审查 +/// ## 使用模型 在*路径操作*函数内部直接访问模型对象的属性: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## 请求体 + 路径参数 @@ -169,17 +189,21 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## 请求体 + 路径参数 + 查询参数 @@ -187,17 +211,21 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// 函数参数按如下规则进行识别: @@ -205,11 +233,13 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 - 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数 - 类型是 **Pydantic 模型**的参数,是**请求体** -!!! note "笔记" +/// note | "笔记" + +因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 - 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 +FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。 - FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。 +/// ## 不使用 Pydantic diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 8571422dd..7ca77696e 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ 首先,导入 `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## 声明 `Cookie` 参数 @@ -49,51 +65,71 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +尽可能选择使用 `Annotated` 的版本。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// note | "技术细节" - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +`Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 -!!! note "技术细节" +注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 - `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 +/// info | "说明" -!!! info "说明" +必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 - 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index ddd4e7682..de880f347 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -78,7 +78,10 @@ 更多关于 <abbr title="Cross-Origin Resource Sharing">CORS</abbr> 的信息,请查看 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS 文档</a>。 -!!! note "技术细节" - 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 +/// note | "技术细节" - 出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 +你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 + +出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 + +/// diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index 51801d498..945094207 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -70,8 +70,11 @@ from myapp import app uvicorn.run(app, host="0.0.0.0", port=8000) ``` -!!! info - 更多信息请检查 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python 官方文档</a>. +/// info + +更多信息请检查 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python 官方文档</a>. + +/// ## 使用你的调试器运行代码 diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 1866da298..9932f90fc 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ 在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。 @@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy") 所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// 注意用于创建类实例的 `__init__` 方法: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...它与我们以前的 `common_parameters` 具有相同的参数: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 这些参数就是 **FastAPI** 用来 "处理" 依赖项的。 @@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy") 现在,您可以使用这个类来声明你的依赖项了。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。 @@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams) ..就像: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` + +//// 但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等: @@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends() 同样的例子看起来像这样: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` + +//// ... **FastAPI** 会知道怎么处理。 -!!! tip - 如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 +/// tip + +如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 + +这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 - 这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 +/// diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 61ea371e5..e6bbd47c1 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,19 +20,23 @@ 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 -!!! tip "提示" +/// tip | "提示" - 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 +有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 - 在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 +在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 - 使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 +使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 -!!! info "说明" +/// - 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 +/// info | "说明" - 但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 +本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 + +但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 + +/// ## 依赖项错误和返回值 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index 4159d626e..beca95d45 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,20 +4,24 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” 为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 -!!! tip "提示" - 确保只使用一次 `yield` 。 +/// tip | "提示" -!!! note "技术细节" +确保只使用一次 `yield` 。 - 任何一个可以与以下内容一起使用的函数: +/// - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> 或者 - * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +/// note | "技术细节" - 都可以作为 **FastAPI** 的依赖项。 +任何一个可以与以下内容一起使用的函数: - 实际上,FastAPI内部就使用了这两个装饰器。 +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> 或者 +* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +都可以作为 **FastAPI** 的依赖项。 + +实际上,FastAPI内部就使用了这两个装饰器。 + +/// ## 使用 `yield` 的数据库依赖项 @@ -41,11 +45,13 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip "提示" +/// tip | "提示" - 您可以使用 `async` 或普通函数。 +您可以使用 `async` 或普通函数。 - **FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。 +**FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。 + +/// ## 同时包含了 `yield` 和 `try` 的依赖项 @@ -68,26 +74,35 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” 例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 14 22" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="6 14 22" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +```Python hl_lines="5 13 21" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="5 13 21" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +如果可能,请尽量使用“ Annotated”版本。 - !!! tip - 如果可能,请尽量使用“ Annotated”版本。 +/// + +```Python hl_lines="4 12 20" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` - ```Python hl_lines="4 12 20" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// 所有这些依赖都可以使用`yield`。 @@ -95,26 +110,35 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” 而`dependency_b` 反过来则需要`dependency_a`(此处称为 `dep_a`)的值在其退出代码中可用。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18-19 26-27" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// - ```Python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17-18 25-26" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 如果可能,请尽量使用“ Annotated”版本。 +如果可能,请尽量使用“ Annotated”版本。 - ```Python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +/// + +```Python hl_lines="16-17 24-25" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` + +//// 同样,你可以有混合了`yield`和`return`的依赖。 @@ -124,12 +148,13 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” **FastAPI** 将确保按正确的顺序运行所有内容。 -!!! note "技术细节" +/// note | "技术细节" - 这是由 Python 的<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">上下文管理器</a>完成的。 +这是由 Python 的<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">上下文管理器</a>完成的。 - **FastAPI** 在内部使用它们来实现这一点。 +**FastAPI** 在内部使用它们来实现这一点。 +/// ## 使用 `yield` 和 `HTTPException` 的依赖项 @@ -151,9 +176,11 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” 如果你有自定义异常,希望在返回响应之前处理,并且可能修改响应甚至触发`HTTPException`,可以创建[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。 -!!! tip +/// tip + +在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。 - 在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。 +/// 执行的顺序大致如下图所示。时间从上到下流动。每列都是相互交互或执行代码的其中一部分。 @@ -197,15 +224,21 @@ participant tasks as Background tasks end ``` -!!! info - 只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 +/// info + +只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 - 在发送了其中一个响应之后,就无法再发送其他响应了。 +在发送了其中一个响应之后,就无法再发送其他响应了。 -!!! tip - 这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 +/// - 如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 +/// tip + +这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 + +如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 + +/// ## 上下文管理器 @@ -229,10 +262,13 @@ with open("./somefile.txt") as f: ### 在依赖项中使用带有`yield`的上下文管理器 -!!! warning - 这是一个更为“高级”的想法。 +/// warning + +这是一个更为“高级”的想法。 - 如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 +如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 + +/// 在Python中,你可以通过<a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">创建一个带有`__enter__()`和`__exit__()`方法的类</a>来创建上下文管理器。 @@ -242,12 +278,15 @@ with open("./somefile.txt") as f: {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - 另一种创建上下文管理器的方法是: +/// tip + +另一种创建上下文管理器的方法是: + +* <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>或者 +* <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> - * <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>或者 - * <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> +使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 - 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 +但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 - 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 +/// diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md index 7a133061d..b360bf71e 100644 --- a/docs/zh/docs/tutorial/dependencies/index.md +++ b/docs/zh/docs/tutorial/dependencies/index.md @@ -75,9 +75,11 @@ FastAPI 提供了简单易用,但功能强大的**<abbr title="也称为组件 该函数接收的参数和*路径操作函数*的参数一样。 -!!! tip "提示" +/// tip | "提示" - 下一章介绍,除了函数还有哪些「对象」可以用作依赖项。 +下一章介绍,除了函数还有哪些「对象」可以用作依赖项。 + +/// 接收到新的请求时,**FastAPI** 执行如下操作: @@ -98,11 +100,13 @@ common_parameters --> read_users 这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。 -!!! check "检查" +/// check | "检查" + +注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 - 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 +只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 - 只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 +/// ## 要不要使用 `async`? @@ -114,9 +118,11 @@ common_parameters --> read_users 上述这些操作都是可行的,**FastAPI** 知道该怎么处理。 -!!! note "笔记" +/// note | "笔记" + +如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 - 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 +/// ## 与 OpenAPI 集成 diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md index 58377bbfe..d2a204c3d 100644 --- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md @@ -41,11 +41,13 @@ FastAPI 支持创建含**子依赖项**的依赖项。 {!../../../docs_src/dependencies/tutorial005.py!} ``` -!!! info "信息" +/// info | "信息" - 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 +注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 - 但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 +但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 + +/// ```mermaid graph TB @@ -79,10 +81,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False 但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。 -!!! tip "提示" +/// tip | "提示" + +这些简单的例子现在看上去虽然没有什么实用价值, - 这些简单的例子现在看上去虽然没有什么实用价值, +但在**安全**一章中,您会了解到这些例子的用途, - 但在**安全**一章中,您会了解到这些例子的用途, +以及这些例子所能节省的代码量。 - 以及这些例子所能节省的代码量。 +/// diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md index 859ebc2e8..8270a4093 100644 --- a/docs/zh/docs/tutorial/encoder.md +++ b/docs/zh/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ 它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// 在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。 @@ -38,5 +42,8 @@ 这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。 -!!! note - `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 +/// note + +`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 + +/// diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index cf39de0dd..3b50da01f 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ 下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// 注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 94d82c524..b23d4188f 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -8,27 +8,33 @@ * **输出模型**不应含密码 * **数据库模型**需要加密的密码 -!!! danger "危险" +/// danger | "危险" - 千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 +千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 - 如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 +如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 + +/// ## 多个模型 下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +//// ### `**user_in.dict()` 简介 @@ -140,9 +146,11 @@ UserInDB( ) ``` -!!! warning "警告" +/// warning | "警告" + +辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 - 辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 +/// ## 减少重复 @@ -162,17 +170,21 @@ FastAPI 可以做得更好。 通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` 或者 `anyOf` @@ -182,21 +194,27 @@ FastAPI 可以做得更好。 为此,请使用 Python 标准类型提示 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>: -!!! note "笔记" +/// note | "笔记" + +定义 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 - 定义 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ## 模型列表 @@ -204,17 +222,21 @@ FastAPI 可以做得更好。 为此,请使用标准的 Python `typing.List`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` + +//// ## 任意 `dict` 构成的响应 @@ -224,17 +246,21 @@ FastAPI 可以做得更好。 此时,可以使用 `typing.Dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## 小结 diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index 30fae99cf..779d1b8be 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -24,13 +24,15 @@ $ uvicorn main:app --reload </div> -!!! note - `uvicorn main:app` 命令含义如下: +/// note - * `main`:`main.py` 文件(一个 Python「模块」)。 - * `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 - * `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 +`uvicorn main:app` 命令含义如下: +* `main`:`main.py` 文件(一个 Python「模块」)。 +* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 +* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 + +/// 在输出中,会有一行信息像下面这样: @@ -138,10 +140,13 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 `FastAPI` 是一个为你的 API 提供了所有功能的 Python 类。 -!!! note "技术细节" - `FastAPI` 是直接从 `Starlette` 继承的类。 +/// note | "技术细节" + +`FastAPI` 是直接从 `Starlette` 继承的类。 + +你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 - 你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 +/// ### 步骤 2:创建一个 `FastAPI`「实例」 @@ -201,8 +206,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - 「路径」也通常被称为「端点」或「路由」。 +/// info + +「路径」也通常被称为「端点」或「路由」。 + +/// 开发 API 时,「路径」是用来分离「关注点」和「资源」的主要手段。 @@ -252,16 +260,19 @@ https://example.com/items/foo * 请求路径为 `/` * 使用 <abbr title="HTTP GET 方法"><code>get</code> 操作</abbr> -!!! info "`@decorator` Info" - `@something` 语法在 Python 中被称为「装饰器」。 +/// info | "`@decorator` Info" + +`@something` 语法在 Python 中被称为「装饰器」。 - 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 +像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 - 装饰器接收位于其下方的函数并且用它完成一些工作。 +装饰器接收位于其下方的函数并且用它完成一些工作。 - 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 +在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 - 它是一个「**路径操作装饰器**」。 +它是一个「**路径操作装饰器**」。 + +/// 你也可以使用其他的操作: @@ -276,14 +287,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 您可以随意使用任何一个操作(HTTP方法)。 +/// tip + +您可以随意使用任何一个操作(HTTP方法)。 + +**FastAPI** 没有强制要求操作有任何特定的含义。 - **FastAPI** 没有强制要求操作有任何特定的含义。 +此处提供的信息仅作为指导,而不是要求。 - 此处提供的信息仅作为指导,而不是要求。 +比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 - 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 +/// ### 步骤 4:定义**路径操作函数** @@ -311,8 +325,11 @@ https://example.com/items/foo {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 +/// note + +如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 + +/// ### 步骤 5:返回内容 diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index 701cd241e..b5c027d44 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -67,14 +67,15 @@ ``` -!!! tip "提示" +/// tip | "提示" - 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 +触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 - 还支持传递 `dict`、`list` 等数据结构。 +还支持传递 `dict`、`list` 等数据结构。 - **FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +**FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +/// ## 添加自定义响应头 @@ -115,12 +116,13 @@ ``` -!!! note "技术细节" +/// note | "技术细节" - `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 +`from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +/// ## 覆盖默认异常处理器 @@ -174,10 +176,11 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -!!! warning "警告" +/// warning | "警告" - 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +/// `RequestValidationError` 是 Pydantic 的 <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a> 的子类。 @@ -200,12 +203,13 @@ path -> item_id ``` -!!! note "技术细节" +/// note | "技术细节" - 还可以使用 `from starlette.responses import PlainTextResponse`。 +还可以使用 `from starlette.responses import PlainTextResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +/// ### 使用 `RequestValidationError` 的请求体 diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index 25dfeba87..a9064c519 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ 首先,导入 `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// ## 声明 `Header` 参数 @@ -48,51 +64,71 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated -!!! note "技术细节" +/// tip - `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 +尽可能选择使用 `Annotated` 的版本。 - 注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` -!!! info "说明" +//// - 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 +/// note | "技术细节" + +`Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 + +注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 + +/// + +/// info | "说明" + +必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 + +/// ## 自动转换 @@ -110,46 +146,63 @@ 如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/header_params/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+" +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +//// -!!! warning "警告" +/// warning | "警告" - 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 +注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 +/// ## 重复的请求头 @@ -161,50 +214,71 @@ 例如,声明 `X-Token` 多次出现的请求头,可以写成这样: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial003_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// 与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头: diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md index 6180d3de3..ab19f02c5 100644 --- a/docs/zh/docs/tutorial/index.md +++ b/docs/zh/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。 -!!! note - 你也可以分开来安装。 +/// note - 假如你想将应用程序部署到生产环境,你可能要执行以下操作: +你也可以分开来安装。 - ``` - pip install fastapi - ``` +假如你想将应用程序部署到生产环境,你可能要执行以下操作: - 并且安装`uvicorn`来作为服务器: +``` +pip install fastapi +``` + +并且安装`uvicorn`来作为服务器: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +然后对你想使用的每个可选依赖项也执行相同的操作。 - 然后对你想使用的每个可选依赖项也执行相同的操作。 +/// ## 进阶用户指南 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 59a4af86e..3316e2ce4 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -1,101 +1,110 @@ -# 元数据和文档 URL - -你可以在 FastAPI 应用程序中自定义多个元数据配置。 - -## API 元数据 - -你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: - -| 参数 | 类型 | 描述 | -|------------|------|-------------| -| `title` | `str` | API 的标题。 | -| `summary` | `str` | API 的简短摘要。 <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。.</small> | -| `description` | `str` | API 的简短描述。可以使用Markdown。 | -| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | -| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | -| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。<details><summary><code>contact</code> 字段</summary><table><thead><tr><th>参数</th><th>Type</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>联系人/组织的识别名称。</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>指向联系信息的 URL。必须采用 URL 格式。</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。</td></tr></tbody></table></details> | -| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。<details><summary><code>license_info</code> 字段</summary><table><thead><tr><th>参数</th><th>类型</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>必须的</strong> (如果设置了<code>license_info</code>). 用于 API 的许可证名称。</td></tr><tr><td><code>identifier</code></td><td><code>str</code></td><td>一个API的<a href="https://spdx.org/licenses/" class="external-link" target="_blank">SPDX</a>许可证表达。 The <code>identifier</code> field is mutually exclusive of the <code>url</code> field. <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。</small></td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>用于 API 的许可证的 URL。必须采用 URL 格式。</td></tr></tbody></table></details> | - -你可以按如下方式设置它们: - -```Python hl_lines="4-6" -{!../../../docs_src/metadata/tutorial001.py!} -``` - -!!! tip - 您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 - -通过这样设置,自动 API 文档看起来会像: - -<img src="/img/tutorial/metadata/image01.png"> - -## 标签元数据 - -### 创建标签元数据 - -让我们在带有标签的示例中为 `users` 和 `items` 试一下。 - -创建标签元数据并把它传递给 `openapi_tags` 参数: - -```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 - -!!! tip "提示" - 不必为你使用的所有标签都添加元数据。 - -### 使用你的标签 - -将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: - -```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -!!! info "信息" - 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 - -### 查看文档 - -如果你现在查看文档,它们会显示所有附加的元数据: - -<img src="/img/tutorial/metadata/image02.png"> - -### 标签顺序 - -每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 - -例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 - -## OpenAPI URL - -默认情况下,OpenAPI 模式服务于 `/openapi.json`。 - -但是你可以通过参数 `openapi_url` 对其进行配置。 - -例如,将其设置为服务于 `/api/v1/openapi.json`: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} -``` - -如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 - -## 文档 URLs - -你可以配置两个文档用户界面,包括: - -* **Swagger UI**:服务于 `/docs`。 - * 可以使用参数 `docs_url` 设置它的 URL。 - * 可以通过设置 `docs_url=None` 禁用它。 -* ReDoc:服务于 `/redoc`。 - * 可以使用参数 `redoc_url` 设置它的 URL。 - * 可以通过设置 `redoc_url=None` 禁用它。 - -例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} -``` +# 元数据和文档 URL + +你可以在 FastAPI 应用程序中自定义多个元数据配置。 + +## API 元数据 + +你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: + +| 参数 | 类型 | 描述 | +|------------|------|-------------| +| `title` | `str` | API 的标题。 | +| `summary` | `str` | API 的简短摘要。 <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。.</small> | +| `description` | `str` | API 的简短描述。可以使用Markdown。 | +| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | +| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | +| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。<details><summary><code>contact</code> 字段</summary><table><thead><tr><th>参数</th><th>Type</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>联系人/组织的识别名称。</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>指向联系信息的 URL。必须采用 URL 格式。</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。</td></tr></tbody></table></details> | +| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。<details><summary><code>license_info</code> 字段</summary><table><thead><tr><th>参数</th><th>类型</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>必须的</strong> (如果设置了<code>license_info</code>). 用于 API 的许可证名称。</td></tr><tr><td><code>identifier</code></td><td><code>str</code></td><td>一个API的<a href="https://spdx.org/licenses/" class="external-link" target="_blank">SPDX</a>许可证表达。 The <code>identifier</code> field is mutually exclusive of the <code>url</code> field. <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。</small></td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>用于 API 的许可证的 URL。必须采用 URL 格式。</td></tr></tbody></table></details> | + +你可以按如下方式设置它们: + +```Python hl_lines="4-6" +{!../../../docs_src/metadata/tutorial001.py!} +``` + +/// tip + +您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 + +/// + +通过这样设置,自动 API 文档看起来会像: + +<img src="/img/tutorial/metadata/image01.png"> + +## 标签元数据 + +### 创建标签元数据 + +让我们在带有标签的示例中为 `users` 和 `items` 试一下。 + +创建标签元数据并把它传递给 `openapi_tags` 参数: + +```Python hl_lines="3-16 18" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 + +/// tip | "提示" + +不必为你使用的所有标签都添加元数据。 + +/// + +### 使用你的标签 + +将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: + +```Python hl_lines="21 26" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +/// info | "信息" + +阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 + +/// + +### 查看文档 + +如果你现在查看文档,它们会显示所有附加的元数据: + +<img src="/img/tutorial/metadata/image02.png"> + +### 标签顺序 + +每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 + +例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 + +## OpenAPI URL + +默认情况下,OpenAPI 模式服务于 `/openapi.json`。 + +但是你可以通过参数 `openapi_url` 对其进行配置。 + +例如,将其设置为服务于 `/api/v1/openapi.json`: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial002.py!} +``` + +如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 + +## 文档 URLs + +你可以配置两个文档用户界面,包括: + +* **Swagger UI**:服务于 `/docs`。 + * 可以使用参数 `docs_url` 设置它的 URL。 + * 可以通过设置 `docs_url=None` 禁用它。 +* ReDoc:服务于 `/redoc`。 + * 可以使用参数 `redoc_url` 设置它的 URL。 + * 可以通过设置 `redoc_url=None` 禁用它。 + +例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial003.py!} +``` diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md index c9a7e7725..7cc6cac42 100644 --- a/docs/zh/docs/tutorial/middleware.md +++ b/docs/zh/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * 它可以对该**响应**做些什么或者执行任何需要的代码. * 然后它返回这个 **响应**. -!!! note "技术细节" - 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. +/// note | "技术细节" - 如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. +如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. + +如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. + +/// ## 创建中间件 @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - 请记住可以 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">用'X-' 前缀</a>添加专有自定义请求头. +/// tip + +请记住可以 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">用'X-' 前缀</a>添加专有自定义请求头. + +但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>文档中. + +/// + +/// note | "技术细节" - 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>文档中. +你也可以使用 `from starlette.requests import Request`. -!!! note "技术细节" - 你也可以使用 `from starlette.requests import Request`. +**FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. - **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. +/// ### 在 `response` 的前和后 diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md index f79b0e692..ac0177128 100644 --- a/docs/zh/docs/tutorial/path-operation-configuration.md +++ b/docs/zh/docs/tutorial/path-operation-configuration.md @@ -2,9 +2,11 @@ *路径操作装饰器*支持多种配置参数。 -!!! warning "警告" +/// warning | "警告" - 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 +注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 + +/// ## `status_code` 状态码 @@ -20,11 +22,13 @@ 状态码在响应中使用,并会被添加到 OpenAPI 概图。 -!!! note "技术细节" +/// note | "技术细节" + +也可以使用 `from starlette import status` 导入状态码。 - 也可以使用 `from starlette import status` 导入状态码。 +**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 - **FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 +/// ## `tags` 参数 @@ -68,15 +72,19 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: {!../../../docs_src/path_operation_configuration/tutorial005.py!} ``` -!!! info "说明" +/// info | "说明" + +注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 + +/// - 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 +/// check | "检查" -!!! check "检查" +OpenAPI 规定每个*路径操作*都要有响应描述。 - OpenAPI 规定每个*路径操作*都要有响应描述。 +如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 - 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 +/// <img src="/img/tutorial/path-operation-configuration/image03.png"> diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md index 9b41ad7cf..6310ad8d2 100644 --- a/docs/zh/docs/tutorial/path-params-numeric-validations.md +++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md @@ -6,41 +6,57 @@ 首先,从 `fastapi` 导入 `Path`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// + +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// ## 声明元数据 @@ -48,48 +64,67 @@ 例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// -!!! note - 路径参数总是必需的,因为它必须是路径的一部分。 +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - 所以,你应该在声明时使用 `...` 将其标记为必需参数。 +//// - 然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note + +路径参数总是必需的,因为它必须是路径的一部分。 + +所以,你应该在声明时使用 `...` 将其标记为必需参数。 + +然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 + +/// ## 按需对参数排序 @@ -107,14 +142,19 @@ 因此,你可以将函数声明为: -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// ## 按需对参数排序的技巧 @@ -174,18 +214,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 * `lt`:小于(`l`ess `t`han) * `le`:小于等于(`l`ess than or `e`qual) -!!! info - `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 +/// info + +`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 + +而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 + +/// + +/// note | "技术细节" - 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 +当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 -!!! note "技术细节" - 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 +当被调用时,它们返回同名类的实例。 - 当被调用时,它们返回同名类的实例。 +如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 - 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 +因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 - 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 +这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 - 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 +/// diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 12a08b4a3..091dcbeb0 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -24,9 +24,11 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** 本例把 `item_id` 的类型声明为 `int`。 -!!! check "检查" +/// check | "检查" - 类型声明将为函数提供错误检查、代码补全等编辑器支持。 +类型声明将为函数提供错误检查、代码补全等编辑器支持。 + +/// ## 数据<abbr title="也称为:序列化、解析">转换</abbr> @@ -36,11 +38,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** {"item_id":3} ``` -!!! check "检查" +/// check | "检查" + +注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 - 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 +**FastAPI** 通过类型声明自动<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">**解析**请求中的数据</abbr>。 - **FastAPI** 通过类型声明自动<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">**解析**请求中的数据</abbr>。 +/// ## 数据校验 @@ -65,13 +69,15 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** 值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2。</a> -!!! check "检查" +/// check | "检查" - **FastAPI** 使用 Python 类型声明实现了数据校验。 +**FastAPI** 使用 Python 类型声明实现了数据校验。 - 注意,上面的错误清晰地指出了未通过校验的具体原因。 +注意,上面的错误清晰地指出了未通过校验的具体原因。 - 这在开发调试与 API 交互的代码时非常有用。 +这在开发调试与 API 交互的代码时非常有用。 + +/// ## 查看文档 @@ -79,11 +85,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** <img src="/img/tutorial/path-params/image01.png"> -!!! check "检查" +/// check | "检查" + +还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 - 还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 +注意,路径参数的类型是整数。 - 注意,路径参数的类型是整数。 +/// ## 基于标准的好处,备选文档 @@ -135,13 +143,17 @@ FastAPI 充分地利用了 <a href="https://docs.pydantic.dev/" class="external- {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "说明" +/// info | "说明" - Python 3.4 及之后版本支持<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">枚举(即 enums)</a>。 +Python 3.4 及之后版本支持<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">枚举(即 enums)</a>。 -!!! tip "提示" +/// - **AlexNet**、**ResNet**、**LeNet** 是机器学习<abbr title="技术上来说是深度学习模型架构">模型</abbr>。 +/// tip | "提示" + +**AlexNet**、**ResNet**、**LeNet** 是机器学习<abbr title="技术上来说是深度学习模型架构">模型</abbr>。 + +/// ### 声明*路径参数* @@ -177,9 +189,11 @@ FastAPI 充分地利用了 <a href="https://docs.pydantic.dev/" class="external- {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "提示" +/// tip | "提示" - 使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。 +使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。 + +/// #### 返回*枚举元素* @@ -232,11 +246,13 @@ OpenAPI 不支持声明包含路径的*路径参数*,因为这会导致测试 {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "提示" +/// tip | "提示" + +注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。 - 注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。 +本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。 - 本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index af0428837..cb4beb0ca 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -4,17 +4,21 @@ 让我们以下面的应用程序为例: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// 查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。 @@ -98,8 +102,11 @@ q: Union[str, None] = Query(default=None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note - 具有默认值还会使该参数成为可选参数。 +/// note + +具有默认值还会使该参数成为可选参数。 + +/// ## 声明为必需参数 @@ -135,9 +142,12 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006b.py!} ``` -!!! info - 如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Python 的一部分并且被称为「省略号」</a>。 - Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 +/// info + +如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Python 的一部分并且被称为「省略号」</a>。 +Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 + +/// 这将使 **FastAPI** 知道此查询参数是必需的。 @@ -151,8 +161,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006c.py!} ``` -!!! tip - Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关<a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">必需可选字段</a>的更多信息。 +/// tip + +Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关<a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">必需可选字段</a>的更多信息。 + +/// ### 使用Pydantic中的`Required`代替省略号(`...`) @@ -162,9 +175,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006d.py!} ``` -!!! tip - 请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` +/// tip + +请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` +/// ## 查询参数列表 / 多个值 @@ -195,8 +210,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 +/// tip + +要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 + +/// 交互式 API 文档将会相应地进行更新,以允许使用多个值: @@ -235,10 +253,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - 请记住,在这种情况下 FastAPI 将不会检查列表的内容。 +/// note - 例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 +请记住,在这种情况下 FastAPI 将不会检查列表的内容。 + +例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 + +/// ## 声明更多元数据 @@ -246,10 +267,13 @@ http://localhost:8000/items/ 这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。 -!!! note - 请记住,不同的工具对 OpenAPI 的支持程度可能不同。 +/// note + +请记住,不同的工具对 OpenAPI 的支持程度可能不同。 + +其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 - 其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 +/// 你可以添加 `title`: diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index 8b2528c9a..6853e3899 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -63,48 +63,58 @@ http://127.0.0.1:8000/items/?skip=20 同理,把默认值设为 `None` 即可声明**可选的**查询参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` + +//// 本例中,查询参数 `q` 是可选的,默认值为 `None`。 -!!! check "检查" +/// check | "检查" + +注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。 - 注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。 +/// -!!! note "笔记" +/// note | "笔记" - 因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。 +因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。 - FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。 +FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。 + +/// ## 查询参数类型转换 参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` +//// 本例中,访问: @@ -147,18 +157,21 @@ http://127.0.0.1:8000/items/foo?short=yes FastAPI 通过参数名进行检测: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` +//// ## 必选查询参数 @@ -214,17 +227,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// 本例中有 3 个查询参数: @@ -232,5 +249,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`,默认值为 `0` 的 `int` 类型参数 * `limit`,可选的 `int` 类型参数 -!!! tip "提示" - 还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。 +/// tip | "提示" + +还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。 + +/// diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 1cd3518cf..d5d0fb671 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -2,13 +2,15 @@ `File` 用于定义客户端的上传文件。 -!!! info "说明" +/// info | "说明" - 因为上传文件以「表单数据」形式发送。 +因为上传文件以「表单数据」形式发送。 - 所以接收上传文件,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 +所以接收上传文件,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 - 例如: `pip install python-multipart`。 +例如: `pip install python-multipart`。 + +/// ## 导入 `File` @@ -26,15 +28,19 @@ {!../../../docs_src/request_files/tutorial001.py!} ``` -!!! info "说明" +/// info | "说明" + +`File` 是直接继承自 `Form` 的类。 + +注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 - `File` 是直接继承自 `Form` 的类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 +/// tip | "提示" -!!! tip "提示" +声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 - 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// 文件作为「表单数据」上传。 @@ -92,13 +98,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 技术细节" +/// note | "`async` 技术细节" + +使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 + +/// - 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 +/// note | "Starlette 技术细节" -!!! note "Starlette 技术细节" +**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 - **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 +/// ## 什么是 「表单数据」 @@ -106,35 +116,43 @@ contents = myfile.file.read() **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | "技术细节" - 不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 +不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 - 但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 +但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 - 编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST </code></a> 小节。 +编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST </code></a> 小节。 -!!! warning "警告" +/// - 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 +/// warning | "警告" - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 + +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 + +/// ## 可选文件上传 您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7 14" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` + +//// - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +//// ## 带有额外元数据的 `UploadFile` @@ -152,42 +170,52 @@ FastAPI 支持同时上传多个文件。 上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// 接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。 -!!! note "技术细节" +/// note | "技术细节" - 也可以使用 `from starlette.responses import HTMLResponse`。 +也可以使用 `from starlette.responses import HTMLResponse`。 - `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 +`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 + +/// ### 带有额外元数据的多文件上传 和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## 小结 diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md index f58593669..723cf5b18 100644 --- a/docs/zh/docs/tutorial/request-forms-and-files.md +++ b/docs/zh/docs/tutorial/request-forms-and-files.md @@ -2,11 +2,13 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 -!!! info "说明" +/// info | "说明" - 接收上传文件或表单数据,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 +接收上传文件或表单数据,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `File` 与 `Form` @@ -26,11 +28,13 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 声明文件可以使用 `bytes` 或 `UploadFile` 。 -!!! warning "警告" +/// warning | "警告" + +可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md index e4fcd88ff..6cc472ac1 100644 --- a/docs/zh/docs/tutorial/request-forms.md +++ b/docs/zh/docs/tutorial/request-forms.md @@ -2,11 +2,13 @@ 接收的不是 JSON,而是表单字段时,要使用 `Form`。 -!!! info "说明" +/// info | "说明" - 要使用表单,需预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 +要使用表单,需预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `Form` @@ -30,13 +32,17 @@ 使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。 -!!! info "说明" +/// info | "说明" + +`Form` 是直接继承自 `Body` 的类。 + +/// - `Form` 是直接继承自 `Body` 的类。 +/// tip | "提示" -!!! tip "提示" +声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 - 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// ## 关于 "表单字段" @@ -44,19 +50,23 @@ **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | "技术细节" + +表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 + +但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 - 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 +编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST</code></a>小节。 - 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 +/// - 编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST</code></a>小节。 +/// warning | "警告" -!!! warning "警告" +可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index 0f1b3b4b9..3c196c964 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -8,26 +8,35 @@ * `@app.delete()` * 等等。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note - 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 +//// + +/// note + +注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 + +/// 它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。 @@ -42,8 +51,11 @@ FastAPI 将使用此 `response_model` 来: * 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。 -!!! note "技术细节" - 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 +/// note | "技术细节" + +响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 + +/// ## 返回与输入相同的数据 @@ -65,52 +77,67 @@ FastAPI 将使用此 `response_model` 来: 但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。 -!!! danger - 永远不要存储用户的明文密码,也不要在响应中发送密码。 +/// danger + +永远不要存储用户的明文密码,也不要在响应中发送密码。 + +/// ## 添加输出模型 相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// 这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// ...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// 因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。 @@ -159,16 +186,22 @@ FastAPI 将使用此 `response_model` 来: } ``` -!!! info - FastAPI 通过 Pydantic 模型的 `.dict()` 配合 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">该方法的 `exclude_unset` 参数</a> 来实现此功能。 +/// info + +FastAPI 通过 Pydantic 模型的 `.dict()` 配合 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">该方法的 `exclude_unset` 参数</a> 来实现此功能。 -!!! info - 你还可以使用: +/// - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +/// info - 参考 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 文档</a> 中对 `exclude_defaults` 和 `exclude_none` 的描述。 +你还可以使用: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +参考 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 文档</a> 中对 `exclude_defaults` 和 `exclude_none` 的描述。 + +/// #### 默认值字段有实际值的数据 @@ -203,10 +236,13 @@ FastAPI 将使用此 `response_model` 来: 因此,它们将包含在 JSON 响应中。 -!!! tip - 请注意默认值可以是任何值,而不仅是`None`。 +/// tip + +请注意默认值可以是任何值,而不仅是`None`。 + +它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 - 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 +/// ### `response_model_include` 和 `response_model_exclude` @@ -216,21 +252,27 @@ FastAPI 将使用此 `response_model` 来: 如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。 -!!! tip - 但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 +/// tip - 这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 +但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 - 这也适用于作用类似的 `response_model_by_alias`。 +这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 + +这也适用于作用类似的 `response_model_by_alias`。 + +/// ```Python hl_lines="31 37" {!../../../docs_src/response_model/tutorial005.py!} ``` -!!! tip - `{"name", "description"}` 语法创建一个具有这两个值的 `set`。 +/// tip + +`{"name", "description"}` 语法创建一个具有这两个值的 `set`。 + +等同于 `set(["name", "description"])`。 - 等同于 `set(["name", "description"])`。 +/// #### 使用 `list` 而不是 `set` diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index cc23231b4..506cd4a43 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -12,15 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "笔记" +/// note | "笔记" - 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 +注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 + +/// `status_code` 参数接收表示 HTTP 状态码的数字。 -!!! info "说明" +/// info | "说明" + +`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>。 - `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>。 +/// 它可以: @@ -29,17 +33,21 @@ <img src="/img/tutorial/response-status-code/image01.png"> -!!! note "笔记" +/// note | "笔记" + +某些响应状态码表示响应没有响应体(参阅下一章)。 - 某些响应状态码表示响应没有响应体(参阅下一章)。 +FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 - FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 +/// ## 关于 HTTP 状态码 -!!! note "笔记" +/// note | "笔记" - 如果已经了解 HTTP 状态码,请跳到下一章。 +如果已经了解 HTTP 状态码,请跳到下一章。 + +/// 在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。 @@ -58,9 +66,11 @@ * 对于来自客户端的一般错误,可以只使用 `400` * `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码 -!!! tip "提示" +/// tip | "提示" + +状态码及适用场景的详情,请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN 的 HTTP 状态码</abbr>文档</a>。 - 状态码及适用场景的详情,请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN 的 HTTP 状态码</abbr>文档</a>。 +/// ## 状态码名称快捷方式 @@ -84,11 +94,13 @@ <img src="../../../../../../img/tutorial/response-status-code/image02.png"> -!!! note "技术细节" +/// note | "技术细节" + +也可以使用 `from starlette import status`。 - 也可以使用 `from starlette import status`。 +为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 - 为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 +/// ## 更改默认状态码 diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md index ae204dc61..6063bd731 100644 --- a/docs/zh/docs/tutorial/schema-extra-example.md +++ b/docs/zh/docs/tutorial/schema-extra-example.md @@ -10,17 +10,21 @@ 您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如<a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Pydantic 文档:定制 Schema </a>中所述: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-21" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-23" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// 这些额外的信息将按原样添加到输出的JSON模式中。 @@ -28,20 +32,27 @@ 在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// -!!! warning - 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 +/// warning + +请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 + +/// ## `Body` 额外参数 @@ -49,41 +60,57 @@ 比如,你可以将请求体的一个 `example` 传递给 `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="23-28" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="18-23" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="20-25" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +//// ## 文档 UI 中的例子 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index f28cc24f8..266a5fcdf 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -20,36 +20,47 @@ 把下面的示例代码复制到 `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// ## 运行 -!!! info "说明" +/// info | "说明" + +先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 - 先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。 +安装命令: `pip install python-multipart`。 - 安装命令: `pip install python-multipart`。 +这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 - 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 +/// 用下面的命令运行该示例: @@ -71,19 +82,23 @@ $ uvicorn main:app --reload <img src="/img/tutorial/security/image01.png"> -!!! check "Authorize 按钮!" +/// check | "Authorize 按钮!" - 页面右上角出现了一个「**Authorize**」按钮。 +页面右上角出现了一个「**Authorize**」按钮。 - *路径操作*的右上角也出现了一个可以点击的小锁图标。 +*路径操作*的右上角也出现了一个可以点击的小锁图标。 + +/// 点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段: <img src="/img/tutorial/security/image02.png"> -!!! note "笔记" +/// note | "笔记" + +目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 - 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 +/// 虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。 @@ -125,15 +140,17 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。 -!!! info "说明" +/// info | "说明" - `Bearer` 令牌不是唯一的选择。 +`Bearer` 令牌不是唯一的选择。 - 但它是最适合这个用例的方案。 +但它是最适合这个用例的方案。 - 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 +甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 - 本例中,**FastAPI** 还提供了构建工具。 +本例中,**FastAPI** 还提供了构建工具。 + +/// 创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。 @@ -141,23 +158,27 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" + +在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 - 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 +因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。 - 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。 +使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 - 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 +/// 该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。 接下来,学习如何创建实际的路径操作。 -!!! info "说明" +/// info | "说明" - 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 +严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 - 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 +这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 + +/// `oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。 @@ -181,11 +202,13 @@ oauth2_scheme(some, parameters) **FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。 -!!! info "技术细节" +/// info | "技术细节" + +**FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 - **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 +所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 - 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 +/// ## 实现的操作 diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md index 1f17f5bd9..f8094e86a 100644 --- a/docs/zh/docs/tutorial/security/get-current-user.md +++ b/docs/zh/docs/tutorial/security/get-current-user.md @@ -55,18 +55,21 @@ 这有助于在函数内部使用代码补全和类型检查。 -!!! tip "提示" +/// tip | "提示" - 还记得请求体也是使用 Pydantic 模型声明的吧。 +还记得请求体也是使用 Pydantic 模型声明的吧。 - 放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 +放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 -!!! check "检查" +/// - 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 +/// check | "检查" - 而不是局限于只能有一个返回该类型数据的依赖项。 +依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 +而不是局限于只能有一个返回该类型数据的依赖项。 + +/// ## 其它模型 diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md index 0595f5f63..e888a4fe9 100644 --- a/docs/zh/docs/tutorial/security/index.md +++ b/docs/zh/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法 OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。 -!!! tip - 在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 +/// tip +在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI 定义了以下安全方案: * 此自动发现机制是 OpenID Connect 规范中定义的内容。 -!!! tip - 集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 +/// tip + +集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 + +最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 - 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 +/// ## **FastAPI** 实用工具 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 117f74d3e..690bd1789 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -40,11 +40,13 @@ $ pip install pyjwt </div> -!!! info "说明" +/// info | "说明" - 如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 +如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 - 您可以在 <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a> 获得更多信息。 +您可以在 <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a> 获得更多信息。 + +/// ## 密码哈希 @@ -80,13 +82,15 @@ $ pip install passlib[bcrypt] </div> -!!! tip "提示" +/// tip | "提示" + +`passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 - `passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 +例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 - 例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 +并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 - 并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 +/// ## 密码哈希与校验 @@ -94,13 +98,15 @@ $ pip install passlib[bcrypt] 创建用于密码哈希和身份校验的 PassLib **上下文**。 -!!! tip "提示" +/// tip | "提示" + +PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 - PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 +例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 - 例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 +同时,这些功能都是兼容的。 - 同时,这些功能都是兼容的。 +/// 接下来,创建三个工具函数,其中一个函数用于哈希用户的密码。 @@ -108,45 +114,63 @@ $ pip install passlib[bcrypt] 第三个函数用于身份验证,并返回用户。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 50 57-58 61-62 71-77" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="8 50 57-58 61-62 71-77" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +/// note | "笔记" -!!! note "笔记" +查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 - 查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 +/// ## 处理 JWT 令牌 @@ -188,41 +212,57 @@ $ openssl rand -hex 32 如果令牌无效,则直接返回 HTTP 错误。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 7 14-16 30-32 80-88" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="4 7 14-16 30-32 80-88" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3 6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ## 更新 `/token` *路径操作* @@ -230,41 +270,57 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="119-134" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="119-134" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="116-131" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="116-131" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ### JWT `sub` 的技术细节 @@ -302,9 +358,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 用户名: `johndoe` 密码: `secret` -!!! check "检查" +/// check | "检查" + +注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 - 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 +/// <img src="https://fastapi.tiangolo.com/img/tutorial/security/image08.png"> @@ -325,9 +383,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 <img src="https://fastapi.tiangolo.com/img/tutorial/security/image10.png"> -!!! note "笔记" +/// note | "笔记" + +注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 - 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 +/// ## `scopes` 高级用法 diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index 751767ea2..261421dad 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -32,15 +32,17 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info "说明" +/// info | "说明" - OAuth2 中,**作用域**只是声明指定权限的字符串。 +OAuth2 中,**作用域**只是声明指定权限的字符串。 - 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 这些细节只是特定的实现方式。 +这些细节只是特定的实现方式。 - 对 OAuth2 来说,都只是字符串而已。 +对 OAuth2 来说,都只是字符串而已。 + +/// ## 获取 `username` 和 `password` 的代码 @@ -61,32 +63,38 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串 * 可选的 `grant_type` -!!! tip "提示" +/// tip | "提示" + +实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 - 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 +如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 - 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 +/// * 可选的 `client_id`(本例未使用) * 可选的 `client_secret`(本例未使用) -!!! info "说明" +/// info | "说明" - `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 +`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 - **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 +**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 - 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 +但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 - 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 +但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 + +/// ### 使用表单数据 -!!! tip "提示" +/// tip | "提示" + +`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 - `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 +本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 - 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 +/// 现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。 @@ -142,9 +150,11 @@ UserInDB( ) ``` -!!! info "说明" +/// info | "说明" - `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 +`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 + +/// ## 返回 Token @@ -156,25 +166,29 @@ UserInDB( 本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。 -!!! tip "提示" +/// tip | "提示" + +下一章介绍使用哈希密码和 <abbr title="JSON Web Tokens">JWT</abbr> Token 的真正安全机制。 - 下一章介绍使用哈希密码和 <abbr title="JSON Web Tokens">JWT</abbr> Token 的真正安全机制。 +但现在,仅关注所需的特定细节。 - 但现在,仅关注所需的特定细节。 +/// ```Python hl_lines="85" {!../../../docs_src/security/tutorial003.py!} ``` -!!! tip "提示" +/// tip | "提示" - 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 +按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 - 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 +这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 - 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 +这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 - **FastAPI** 则负责处理其它的工作。 +**FastAPI** 则负责处理其它的工作。 + +/// ## 更新依赖项 @@ -192,21 +206,23 @@ UserInDB( {!../../../docs_src/security/tutorial003.py!} ``` -!!! info "说明" +/// info | "说明" + +此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 - 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 +任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 - 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 +本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 - 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 +实际上,忽略这个附加响应头,也不会有什么问题。 - 实际上,忽略这个附加响应头,也不会有什么问题。 +之所以在此提供这个附加响应头,是为了符合规范的要求。 - 之所以在此提供这个附加响应头,是为了符合规范的要求。 +说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 - 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 +这就是遵循标准的好处…… - 这就是遵循标准的好处…… +/// ## 实际效果 diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index 8629b23fa..45ec71f7c 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -1,11 +1,14 @@ # SQL (关系型) 数据库 -!!! info - 这些文档即将被更新。🎉 +/// info - 当前版本假设Pydantic v1和SQLAlchemy版本小于2。 +这些文档即将被更新。🎉 - 新的文档将包括Pydantic v2以及 <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a>(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 +当前版本假设Pydantic v1和SQLAlchemy版本小于2。 + +新的文档将包括Pydantic v2以及 <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a>(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 + +/// **FastAPI**不需要你使用SQL(关系型)数据库。 @@ -25,11 +28,17 @@ 稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。 -!!! tip - 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:<a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> +/// tip + +这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:<a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a> + +/// -!!! note - 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 +/// note + +请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 + +/// ## ORMs(对象关系映射) @@ -63,8 +72,11 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 以类似的方式,您也可以使用任何其他 ORM。 -!!! tip - 在文档中也有一篇使用 Peewee 的等效的文章。 +/// tip + +在文档中也有一篇使用 Peewee 的等效的文章。 + +/// ## 文件结构 @@ -129,9 +141,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。 -!!! tip +/// tip + +如果您想使用不同的数据库,这是就是您必须修改的地方。 - 如果您想使用不同的数据库,这是就是您必须修改的地方。 +/// ### 创建 SQLAlchemy 引擎 @@ -153,15 +167,17 @@ connect_args={"check_same_thread": False} ...仅用于`SQLite`,在其他数据库不需要它。 -!!! info "技术细节" +/// info | "技术细节" + +默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 - 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 +这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 +但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 - 但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 +此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 - 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 +/// ### 创建一个`SessionLocal`类 @@ -197,10 +213,13 @@ connect_args={"check_same_thread": False} 我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。 -!!! tip - SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 +/// tip - 而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 +SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 + +而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 + +/// 从`database`(来自上面的`database.py`文件)导入`Base`。 @@ -250,12 +269,15 @@ connect_args={"check_same_thread": False} 现在让我们查看一下文件`sql_app/schemas.py`。 -!!! tip - 为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 +/// tip + +为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 - 这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 +这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 - 因此,这将帮助我们在使用两者时避免混淆。 +因此,这将帮助我们在使用两者时避免混淆。 + +/// ### 创建初始 Pydantic*模型*/模式 @@ -267,23 +289,29 @@ connect_args={"check_same_thread": False} 但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// #### SQLAlchemy 风格和 Pydantic 风格 @@ -311,26 +339,35 @@ name: str 不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13-15 29-32" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` -!!! tip - 请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 +//// + +/// tip + +请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 + +/// ### 使用 Pydantic 的`orm_mode` @@ -340,32 +377,41 @@ name: str 在`Config`类中,设置属性`orm_mode = True`。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 17-18 29 34-35" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +请注意,它使用`=`分配一个值,例如: -!!! tip - 请注意,它使用`=`分配一个值,例如: +`orm_mode = True` - `orm_mode = True` +它不使用之前的`:`来类型声明。 - 它不使用之前的`:`来类型声明。 +这是设置配置值,而不是声明类型。 - 这是设置配置值,而不是声明类型。 +/// Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。 @@ -431,8 +477,11 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 +/// tip + +通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 + +/// ### 创建数据 @@ -449,34 +498,43 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 +/// tip + +SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 + +但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 + +然后将hashed_password参数与要保存的值一起传递。 + +/// + +/// warning - 但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 +此示例不安全,密码未经过哈希处理。 - 然后将hashed_password参数与要保存的值一起传递。 +在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 -!!! warning - 此示例不安全,密码未经过哈希处理。 +有关更多详细信息,请返回教程中的安全部分。 - 在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 +在这里,我们只关注数据库的工具和机制。 - 有关更多详细信息,请返回教程中的安全部分。 +/// - 在这里,我们只关注数据库的工具和机制。 +/// tip -!!! tip - 这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: +这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: - `item.dict()` +`item.dict()` - 然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: +然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: - `Item(**item.dict())` +`Item(**item.dict())` - 然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: +然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: - `Item(**item.dict(), owner_id=user_id)` +`Item(**item.dict(), owner_id=user_id)` + +/// ## 主**FastAPI**应用程序 @@ -486,17 +544,21 @@ current_user.items 以非常简单的方式创建数据库表: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// #### Alembic 注意 @@ -520,63 +582,81 @@ current_user.items 我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13-18" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-20" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +/// info -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 +我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - 然后我们在finally块中关闭它。 +然后我们在finally块中关闭它。 - 通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 +通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 - 但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) +但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) + +/// *然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。 *这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="22 30 36 45 51" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ -!!! info "技术细节" - 参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 +```Python hl_lines="24 32 38 47 53" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - 但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 +//// + +/// info | "技术细节" + +参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 + +但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 + +/// ### 创建您的**FastAPI** *路径操作* 现在,到了最后,编写标准的**FastAPI** *路径操作*代码。 -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// 我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。 @@ -584,15 +664,21 @@ current_user.items 这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。 -!!! tip - 请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 +/// tip + +请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 + +但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 + +/// + +/// tip - 但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 +另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. -!!! tip - 另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. +但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 - 但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 +/// ### 关于 `def` 对比 `async def` @@ -621,11 +707,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - 如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) +/// info -!!! note "Very Technical Details" - 如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 +如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) + +/// + +/// note | "Very Technical Details" + +如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 + +/// ## 迁移 @@ -659,23 +751,29 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/schemas.py`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// * `sql_app/crud.py`: @@ -685,25 +783,31 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// ## 执行项目 您可以复制这些代码并按原样使用它。 -!!! info +/// info + +事实上,这里的代码只是大多数测试代码的一部分。 - 事实上,这里的代码只是大多数测试代码的一部分。 +/// 你可以用 Uvicorn 运行它: @@ -744,24 +848,31 @@ $ uvicorn sql_app.main:app --reload 我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="12-20" +{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +```Python hl_lines="14-22" +{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 +然后我们在finally块中关闭它。 - 然后我们在finally块中关闭它。 +通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 - 通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 +/// ### 关于`request.state` @@ -782,10 +893,16 @@ $ uvicorn sql_app.main:app --reload * 将为每个请求创建一个连接。 * 即使处理该请求的*路径操作*不需要数据库。 -!!! tip - 最好使用带有yield的依赖项,如果这足够满足用例需求 +/// tip + +最好使用带有yield的依赖项,如果这足够满足用例需求 + +/// + +/// info + +带有`yield`的依赖项是最近刚加入**FastAPI**中的。 -!!! info - 带有`yield`的依赖项是最近刚加入**FastAPI**中的。 +所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 - 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 +/// diff --git a/docs/zh/docs/tutorial/static-files.md b/docs/zh/docs/tutorial/static-files.md index e7c5c3f0a..3d14f34d8 100644 --- a/docs/zh/docs/tutorial/static-files.md +++ b/docs/zh/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "技术细节" - 你也可以用 `from starlette.staticfiles import StaticFiles`。 +/// note | "技术细节" - **FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 +你也可以用 `from starlette.staticfiles import StaticFiles`。 + +**FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 + +/// ### 什么是"挂载"(Mounting) diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md index 69841978c..18c35e8c6 100644 --- a/docs/zh/docs/tutorial/testing.md +++ b/docs/zh/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## 使用 `TestClient` -!!! info "信息" - 要使用 `TestClient`,先要安装 <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. +/// info | "信息" - 例:`pip install httpx`. +要使用 `TestClient`,先要安装 <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. + +例:`pip install httpx`. + +/// 导入 `TestClient`. @@ -27,20 +30,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "提示" - 注意测试函数是普通的 `def`,不是 `async def`。 +/// tip | "提示" + +注意测试函数是普通的 `def`,不是 `async def`。 + +还有client的调用也是普通的调用,不是用 `await`。 + +这让你可以直接使用 `pytest` 而不会遇到麻烦。 + +/// + +/// note | "技术细节" + +你也可以用 `from starlette.testclient import TestClient`。 - 还有client的调用也是普通的调用,不是用 `await`。 +**FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 - 这让你可以直接使用 `pytest` 而不会遇到麻烦。 +/// -!!! note "技术细节" - 你也可以用 `from starlette.testclient import TestClient`。 +/// tip | "提示" - **FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 +除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 -!!! tip "提示" - 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 +/// ## 分离测试 @@ -110,41 +122,57 @@ 所有*路径操作* 都需要一个`X-Token` 头。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip "提示" - Prefer to use the `Annotated` version if possible. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "提示" - !!! tip "提示" - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "提示" + +Prefer to use the `Annotated` version if possible. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### 扩展后的测试文件 @@ -168,10 +196,13 @@ 关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX 文档</a>. -!!! info "信息" - 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 +/// info | "信息" + +注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 + +如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 - 如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 +/// ## 运行起来 diff --git a/requirements-docs-insiders.txt b/requirements-docs-insiders.txt new file mode 100644 index 000000000..d8d3c37a9 --- /dev/null +++ b/requirements-docs-insiders.txt @@ -0,0 +1,3 @@ +git+https://${TOKEN}@github.com/squidfunk/mkdocs-material-insiders.git@9.5.30-insiders-4.53.11 +git+https://${TOKEN}@github.com/pawamoy-insiders/griffe-typing-deprecated.git +git+https://${TOKEN}@github.com/pawamoy-insiders/mkdocstrings-python.git diff --git a/requirements-docs.txt b/requirements-docs.txt index c672f0ef7..a7ef7ef2e 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -3,16 +3,16 @@ mkdocs-material==9.5.18 mdx-include >=1.4.1,<2.0.0 mkdocs-redirects>=1.2.1,<1.3.0 -typer >=0.12.0 +typer == 0.12.3 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs pillow==10.3.0 # For image processing by Material for MkDocs -cairosvg==2.7.0 -mkdocstrings[python]==0.24.3 -griffe-typingdoc==0.2.2 +cairosvg==2.7.1 +mkdocstrings[python]==0.25.1 +griffe-typingdoc==0.2.5 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 diff --git a/scripts/docs.py b/scripts/docs.py index 59578a820..fd2dd78f1 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -11,9 +11,6 @@ from multiprocessing import Pool from pathlib import Path from typing import Any, Dict, List, Optional, Union -import mkdocs.commands.build -import mkdocs.commands.serve -import mkdocs.config import mkdocs.utils import typer import yaml @@ -165,6 +162,13 @@ def generate_readme_content() -> str: pre_content = content[frontmatter_end:pre_end] post_content = content[post_start:] new_content = pre_content + message + post_content + # Remove content between <!-- only-mkdocs --> and <!-- /only-mkdocs --> + new_content = re.sub( + r"<!-- only-mkdocs -->.*?<!-- /only-mkdocs -->", + "", + new_content, + flags=re.DOTALL, + ) return new_content @@ -258,12 +262,15 @@ def live( en. """ # Enable line numbers during local development to make it easier to highlight - os.environ["LINENUMS"] = "true" if lang is None: lang = "en" lang_path: Path = docs_path / lang - os.chdir(lang_path) - mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008") + subprocess.run( + ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008", "--dirty"], + env={**os.environ, "LINENUMS": "true"}, + cwd=lang_path, + check=True, + ) def get_updated_config_content() -> Dict[str, Any]: From df419b739cf66108adac63d7ab81d62bced1f5a7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 6 Aug 2024 04:48:52 +0000 Subject: [PATCH 672/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 78e27ba7e..1fa24af65 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). * 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). ## 0.112.0 From 7ff5da8bf2b8bfe895e4621f630e9fc3f2c434f4 Mon Sep 17 00:00:00 2001 From: Dom <domdent@protonmail.com> Date: Tue, 6 Aug 2024 14:46:39 +0100 Subject: [PATCH 673/846] edit middleware docs code sample to use perf_counter as a timer --- docs_src/middleware/tutorial001.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py index 6bab3410a..e65a7dade 100644 --- a/docs_src/middleware/tutorial001.py +++ b/docs_src/middleware/tutorial001.py @@ -7,8 +7,8 @@ app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): - start_time = time.time() + start_time = time.perf_counter() response = await call_next(request) - process_time = time.time() - start_time + process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = str(process_time) return response From f0a146e4f8405aba8708e93cf163da70ee922dfe Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Wed, 7 Aug 2024 15:58:00 -0300 Subject: [PATCH 674/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/using-request-directly.md?= =?UTF-8?q?`=20(#11956)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/using-request-directly.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/pt/docs/advanced/using-request-directly.md diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..3dd0a8aef --- /dev/null +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -0,0 +1,58 @@ +# Utilizando o Request diretamente + +Até agora você declarou as partes da requisição que você precisa utilizando os seus tipos. + +Obtendo dados de: + +* Os parâmetros das rotas. +* Cabeçalhos (*Headers*). +* Cookies. +* etc. + +E ao fazer isso, o **FastAPI** está validando as informações, convertendo-as e gerando documentação para a sua API automaticamente. + +Porém há situações em que você possa precisar acessar o objeto `Request` diretamente. + +## Detalhes sobre o objeto `Request` + +Como o **FastAPI** é na verdade o **Starlette** por baixo, com camadas de diversas funcionalidades por cima, você pode utilizar o objeto <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request`</a> do Starlette diretamente quando precisar. + +Isso significaria também que se você obtiver informações do objeto `Request` diretamente (ler o corpo da requisição por exemplo), as informações não serão validadas, convertidas ou documentadas (com o OpenAPI, para a interface de usuário automática da API) pelo FastAPI. + +Embora qualquer outro parâmetro declarado normalmente (o corpo da requisição com um modelo Pydantic, por exemplo) ainda seria validado, convertido, anotado, etc. + +Mas há situações específicas onde é útil utilizar o objeto `Request`. + +## Utilize o objeto `Request` diretamente + +Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro da sua *função de operação de rota*. + +Para isso você precisa acessar a requisição diretamente. + +```Python hl_lines="1 7-8" +{!../../../docs_src/using_request_directly/tutorial001.py!} +``` + +Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. + +/// tip | "Dica" + +Note que neste caso, nós estamos declarando o parâmetro da rota ao lado do parâmetro da requisição. + +Assim, o parâmetro da rota será extraído, validado, convertido para o tipo especificado e anotado com OpenAPI. + +Do mesmo jeito, você pode declarar qualquer outro parâmetro normalmente, e além disso, obter o `Request` também. + +/// + +## Documentação do `Request` + +Você pode ler mais sobre os detalhes do objeto <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request` no site da documentação oficial do Starlette.</a>. + +/// note | "Detalhes Técnicos" + +Você também pode utilizar `from starlette.requests import Request`. + +O **FastAPI** fornece isso diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// From a031d80e5c8a5fd80b8b63337759788976ff1e97 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 7 Aug 2024 18:58:22 +0000 Subject: [PATCH 675/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1fa24af65..abf41b858 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). * 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). From f118154576d5c4d8a2f8a7e88d1f92a6a9d07d7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 7 Aug 2024 14:15:24 -0500 Subject: [PATCH 676/846] =?UTF-8?q?=F0=9F=91=B7=F0=9F=8F=BB=20Add=20deploy?= =?UTF-8?q?=20docs=20status=20and=20preview=20links=20to=20PRs=20(#11961)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 34 +++++---- scripts/comment_docs_deploy_url_in_pr.py | 31 -------- scripts/deploy_docs_status.py | 97 ++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 44 deletions(-) delete mode 100644 scripts/comment_docs_deploy_url_in_pr.py create mode 100644 scripts/deploy_docs_status.py diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 7d8846bb3..85c0cebec 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -20,6 +20,25 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - uses: actions/cache@v4 + id: cache + with: + path: ${{ env.pythonLocation }} + key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01 + - name: Install GitHub Actions dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: pip install -r requirements-github-actions.txt + - name: Deploy Docs Status Pending + run: python ./scripts/deploy_docs_status.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} + - name: Clean site run: | rm -rf ./site @@ -43,22 +62,11 @@ jobs: directory: './site' gitHubToken: ${{ secrets.GITHUB_TOKEN }} branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - - name: Set up Python - uses: actions/setup-python@v5 - with: - python-version: "3.11" - - uses: actions/cache@v4 - id: cache - with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01 - - name: Install GitHub Actions dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-github-actions.txt - name: Comment Deploy if: steps.deploy.outputs.url != '' - run: python ./scripts/comment_docs_deploy_url_in_pr.py + run: python ./scripts/deploy_docs_status.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} DEPLOY_URL: ${{ steps.deploy.outputs.url }} COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} diff --git a/scripts/comment_docs_deploy_url_in_pr.py b/scripts/comment_docs_deploy_url_in_pr.py deleted file mode 100644 index 3148a3bb4..000000000 --- a/scripts/comment_docs_deploy_url_in_pr.py +++ /dev/null @@ -1,31 +0,0 @@ -import logging -import sys - -from github import Github -from pydantic import SecretStr -from pydantic_settings import BaseSettings - - -class Settings(BaseSettings): - github_repository: str - github_token: SecretStr - deploy_url: str - commit_sha: str - - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - settings = Settings() - logging.info(f"Using config: {settings.model_dump_json()}") - g = Github(settings.github_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - use_pr = next( - (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None - ) - if not use_pr: - logging.error(f"No PR found for hash: {settings.commit_sha}") - sys.exit(0) - use_pr.as_issue().create_comment( - f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}" - ) - logging.info("Finished") diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py new file mode 100644 index 000000000..b19989235 --- /dev/null +++ b/scripts/deploy_docs_status.py @@ -0,0 +1,97 @@ +import logging +import re + +from github import Github +from pydantic import SecretStr +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + github_repository: str + github_token: SecretStr + deploy_url: str | None = None + commit_sha: str + run_id: int + + +def main(): + logging.basicConfig(level=logging.INFO) + settings = Settings() + + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + use_pr = next( + (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None + ) + if not use_pr: + logging.error(f"No PR found for hash: {settings.commit_sha}") + return + commits = list(use_pr.get_commits()) + current_commit = [c for c in commits if c.sha == settings.commit_sha][0] + run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}" + if not settings.deploy_url: + current_commit.create_status( + state="pending", + description="Deploy Docs", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No deploy URL available yet") + return + current_commit.create_status( + state="success", + description="Deploy Docs", + context="deploy-docs", + target_url=run_url, + ) + + files = list(use_pr.get_files()) + docs_files = [f for f in files if f.filename.startswith("docs/")] + + lang_links: dict[str, list[str]] = {} + for f in docs_files: + match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) + assert match + lang = match.group(1) + path = match.group(2) + if path.endswith("index.md"): + path = path.replace("index.md", "") + else: + path = path.replace(".md", "/") + if lang == "en": + link = f"{settings.deploy_url}{path}" + else: + link = f"{settings.deploy_url}{lang}/{path}" + lang_links.setdefault(lang, []).append(link) + + links: list[str] = [] + en_links = lang_links.get("en", []) + en_links.sort() + links.extend(en_links) + + langs = list(lang_links.keys()) + langs.sort() + for lang in langs: + if lang == "en": + continue + current_lang_links = lang_links[lang] + current_lang_links.sort() + links.extend(current_lang_links) + + message = ( + f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}" + ) + + if links: + message += "\n\n### Modified Pages\n\n" + message += "\n".join([f"* {link}" for link in links]) + + print(message) + use_pr.as_issue().create_comment(message) + + logging.info("Finished") + + +if __name__ == "__main__": + main() From 9e84537685348368b45d42e85c8306d6df07185d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 7 Aug 2024 19:15:50 +0000 Subject: [PATCH 677/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index abf41b858..62421ce72 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). * 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). From 13b56ab499fc0fda121787491fa25e3083f8272b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 7 Aug 2024 15:56:47 -0500 Subject: [PATCH 678/846] =?UTF-8?q?=F0=9F=94=92=EF=B8=8F=20Update=20permis?= =?UTF-8?q?sions=20for=20deploy-docs=20action=20(#11964)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 85c0cebec..f28262b2a 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -10,6 +10,7 @@ permissions: deployments: write issues: write pull-requests: write + statuses: write jobs: deploy-docs: From 0eddc02aca24698fc61915107eb5c14f574e1d9d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 7 Aug 2024 20:57:09 +0000 Subject: [PATCH 679/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 62421ce72..2ecd5e9a0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). * 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). From 58279670b6757dccb510721ec3461aac87c51c2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 7 Aug 2024 16:17:14 -0500 Subject: [PATCH 680/846] =?UTF-8?q?=F0=9F=94=A8=20Refactor=20script=20`dep?= =?UTF-8?q?loy=5Fdocs=5Fstatus.py`=20to=20account=20for=20deploy=20URLs=20?= =?UTF-8?q?with=20or=20without=20trailing=20slash=20(#11965)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/deploy_docs_status.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py index b19989235..e00fa2be0 100644 --- a/scripts/deploy_docs_status.py +++ b/scripts/deploy_docs_status.py @@ -49,6 +49,7 @@ def main(): files = list(use_pr.get_files()) docs_files = [f for f in files if f.filename.startswith("docs/")] + deploy_url = settings.deploy_url.rstrip("/") lang_links: dict[str, list[str]] = {} for f in docs_files: match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) @@ -60,9 +61,9 @@ def main(): else: path = path.replace(".md", "/") if lang == "en": - link = f"{settings.deploy_url}{path}" + link = f"{deploy_url}/{path}" else: - link = f"{settings.deploy_url}{lang}/{path}" + link = f"{deploy_url}/{lang}/{path}" lang_links.setdefault(lang, []).append(link) links: list[str] = [] @@ -79,9 +80,7 @@ def main(): current_lang_links.sort() links.extend(current_lang_links) - message = ( - f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}" - ) + message = f"📝 Docs preview for commit {settings.commit_sha} at: {deploy_url}" if links: message += "\n\n### Modified Pages\n\n" From b7f035512a06b736257150ca9d51bbc9810bb987 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 7 Aug 2024 21:17:38 +0000 Subject: [PATCH 681/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2ecd5e9a0..01c6f50e7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). * 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). From 8377c5237cb718b4dd212103b8bb2cedfd4091e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 7 Aug 2024 22:51:13 -0500 Subject: [PATCH 682/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 01c6f50e7..5776f4308 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -44,7 +44,7 @@ pip install "fastapi[standard]" * This adds support for calling the CLI as: ```bash -python -m python +python -m fastapi ``` * And it upgrades `fastapi-cli[standard] >=0.0.5`. From 233bab7f419c5bf2f9167a850f83c06a7d2c2af0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 8 Aug 2024 18:28:14 -0500 Subject: [PATCH 683/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20docs-previews?= =?UTF-8?q?=20to=20handle=20no=20docs=20changes=20(#11975)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 2 +- scripts/deploy_docs_status.py | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index f28262b2a..d2953f284 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -64,10 +64,10 @@ jobs: gitHubToken: ${{ secrets.GITHUB_TOKEN }} branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - name: Comment Deploy - if: steps.deploy.outputs.url != '' run: python ./scripts/deploy_docs_status.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} DEPLOY_URL: ${{ steps.deploy.outputs.url }} COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} RUN_ID: ${{ github.run_id }} + IS_DONE: "true" diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py index e00fa2be0..ef33fe43d 100644 --- a/scripts/deploy_docs_status.py +++ b/scripts/deploy_docs_status.py @@ -12,6 +12,7 @@ class Settings(BaseSettings): deploy_url: str | None = None commit_sha: str run_id: int + is_done: bool = False def main(): @@ -30,10 +31,19 @@ def main(): commits = list(use_pr.get_commits()) current_commit = [c for c in commits if c.sha == settings.commit_sha][0] run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}" + if settings.is_done and not settings.deploy_url: + current_commit.create_status( + state="success", + description="No Docs Changes", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No docs changes found") + return if not settings.deploy_url: current_commit.create_status( state="pending", - description="Deploy Docs", + description="Deploying Docs", context="deploy-docs", target_url=run_url, ) @@ -41,7 +51,7 @@ def main(): return current_commit.create_status( state="success", - description="Deploy Docs", + description="Docs Deployed", context="deploy-docs", target_url=run_url, ) From fda1813e1345c69ac93b53966889207b2bf340d1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 8 Aug 2024 23:28:35 +0000 Subject: [PATCH 684/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5776f4308..e0bdb46ed 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). * 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). * 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). From 51563564c6cbe50472d07b324f8304dcd59ad67c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 8 Aug 2024 18:34:25 -0500 Subject: [PATCH 685/846] =?UTF-8?q?=F0=9F=91=B7=20Add=20alls-green=20for?= =?UTF-8?q?=20test-redistribute=20(#11974)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test-redistribute.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml index 0cc5f866e..693f0c603 100644 --- a/.github/workflows/test-redistribute.yml +++ b/.github/workflows/test-redistribute.yml @@ -55,3 +55,15 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + + # https://github.com/marketplace/actions/alls-green#why + test-redistribute-alls-green: # This job does nothing and is only used for the branch protection + if: always() + needs: + - test-redistribute + runs-on: ubuntu-latest + steps: + - name: Decide whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + jobs: ${{ toJSON(needs) }} From 4b5342b568494597d58cd824a6f9fbe00da76046 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 8 Aug 2024 23:34:46 +0000 Subject: [PATCH 686/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e0bdb46ed..8a467a1f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). * 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). * 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). * 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). From 4f9ca032d6bbc6061a703780b5d74ac3264cdeb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 8 Aug 2024 20:42:26 -0500 Subject: [PATCH 687/846] =?UTF-8?q?=F0=9F=92=A1=20Add=20comment=20about=20?= =?UTF-8?q?custom=20Termynal=20line-height=20(#11976)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/css/termynal.css | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/css/termynal.css b/docs/en/docs/css/termynal.css index af2fbe670..8534f9102 100644 --- a/docs/en/docs/css/termynal.css +++ b/docs/en/docs/css/termynal.css @@ -26,6 +26,7 @@ position: relative; -webkit-box-sizing: border-box; box-sizing: border-box; + /* Custom line-height */ line-height: 1.2; } From 0b30cad9d218a4d267e399eb4796d91fcc97879d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 9 Aug 2024 01:43:55 +0000 Subject: [PATCH 688/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8a467a1f6..a0176364c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). * 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). * 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). * 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). From 8b6d9ba7898a130e7e3b2ce59d3a84c4476f7142 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 9 Aug 2024 10:52:41 -0500 Subject: [PATCH 689/846] =?UTF-8?q?=F0=9F=90=9B=20Fix=20deploy=20docs=20pr?= =?UTF-8?q?eviews=20script=20to=20handle=20mkdocs.yml=20files=20(#11984)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/deploy_docs_status.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py index ef33fe43d..19dffbcb9 100644 --- a/scripts/deploy_docs_status.py +++ b/scripts/deploy_docs_status.py @@ -63,7 +63,8 @@ def main(): lang_links: dict[str, list[str]] = {} for f in docs_files: match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) - assert match + if not match: + continue lang = match.group(1) path = match.group(2) if path.endswith("index.md"): From 4cbb846d9eb5e2544ad93b3b0c0a7c415bc5c16e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 9 Aug 2024 15:54:10 +0000 Subject: [PATCH 690/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a0176364c..c3b74ff73 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). * 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). * 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). * 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). From e06e0b1c4a49bad052519afad67ef4dfe0bf33f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 9 Aug 2024 11:53:58 -0500 Subject: [PATCH 691/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20MkDocs=20instan?= =?UTF-8?q?t=20previews=20(#11982)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.insiders.yml | 2 +- docs/en/mkdocs.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index 18c6d3f53..4cec588fa 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -9,4 +9,4 @@ markdown_extensions: material.extensions.preview: targets: include: - - ./* + - "*" diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 782d4ef87..d37d7f42f 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -35,7 +35,7 @@ theme: - navigation.indexes - navigation.instant - navigation.instant.prefetch - - navigation.instant.preview + # - navigation.instant.preview - navigation.instant.progress - navigation.path - navigation.tabs From 6d9dc39fcb3eb3bcd9c2a693683d68311d1618e0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 9 Aug 2024 16:54:22 +0000 Subject: [PATCH 692/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c3b74ff73..c978ad12c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). * 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). * 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). * 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). From 4ec134426d6c44a2f7d7c532933ae831e2c6be84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 9 Aug 2024 16:29:09 -0500 Subject: [PATCH 693/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20about=20?= =?UTF-8?q?discussions=20questions=20(#11985)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/management-tasks.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index 2c91cab72..815bad539 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -280,8 +280,4 @@ Dependabot will create PRs to update dependencies for several things, and those When a question in GitHub Discussions has been answered, mark the answer by clicking "Mark as answer". -Many of the current Discussion Questions were migrated from old issues. Many have the label `answered`, that means they were answered when they were issues, but now in GitHub Discussions, it's not known what is the actual response from the messages. - -You can filter discussions by [`Questions` that are `Unanswered` and have the label `answered`](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aopen+label%3Aanswered+is%3Aunanswered). - -All of those discussions already have an answer in the conversation, you can find it and mark it with the "Mark as answer" button. +You can filter discussions by <a href="https://github.com/tiangolo/fastapi/discussions/categories/questions?discussions_q=category:Questions+is:open+is:unanswered" class="external-link" target="_blank">`Questions` that are `Unanswered`</a>. From 2b7fc3f340b7474a21e3e0e466eb4a64d90cf438 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 9 Aug 2024 21:29:31 +0000 Subject: [PATCH 694/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c978ad12c..ed66f7a21 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo). + ### Translations * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). From 06fc1c2cc82bc585d0e695d57b1d7c7a0c2e0a67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 9 Aug 2024 16:30:19 -0500 Subject: [PATCH 695/846] =?UTF-8?q?=F0=9F=94=A8=20Update=20docs.py=20scrip?= =?UTF-8?q?t=20to=20enable=20dirty=20reload=20conditionally=20(#11986)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/docs.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/scripts/docs.py b/scripts/docs.py index fd2dd78f1..5ef548889 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -251,6 +251,7 @@ def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang ), + dirty: bool = False, ) -> None: """ Serve with livereload a docs site for a specific language. @@ -265,11 +266,12 @@ def live( if lang is None: lang = "en" lang_path: Path = docs_path / lang + # Enable line numbers during local development to make it easier to highlight + args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"] + if dirty: + args.append("--dirty") subprocess.run( - ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008", "--dirty"], - env={**os.environ, "LINENUMS": "true"}, - cwd=lang_path, - check=True, + args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True ) From 0e8b6d3bb8629168f2dcdc77dadc53b9a47ca84e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 9 Aug 2024 21:32:11 +0000 Subject: [PATCH 696/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ed66f7a21..c861508b4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). * 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). * 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). From b0a8e7356a3b2809045e68638cfcd2d6ff6de2e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 12 Aug 2024 16:47:53 -0500 Subject: [PATCH 697/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20admonitions=20i?= =?UTF-8?q?n=20docs=20missing=20(#11998)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/docker.md | 7 +++++-- docs/em/docs/deployment/docker.md | 7 +++++-- docs/en/docs/contributing.md | 4 ++-- docs/en/docs/deployment/docker.md | 7 +++++-- docs/ja/docs/deployment/docker.md | 7 +++++-- docs/ko/docs/deployment/docker.md | 7 +++++-- docs/ko/docs/help-fastapi.md | 6 +++++- docs/pt/docs/deployment/docker.md | 7 +++++-- docs/ru/docs/deployment/docker.md | 7 +++++-- docs/zh/docs/deployment/docker.md | 7 +++++-- docs/zh/docs/deployment/https.md | 7 +++++-- 11 files changed, 52 insertions(+), 21 deletions(-) diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index 2186d16c5..c11dc4127 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Die Option `--no-cache-dir` weist `pip` an, die heruntergeladenen Pakete nicht lokal zu speichern, da dies nur benötigt wird, sollte `pip` erneut ausgeführt werden, um dieselben Pakete zu installieren, aber das ist beim Arbeiten mit Containern nicht der Fall. - !!! note "Hinweis" - Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + /// note | Hinweis + + Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + + /// Die Option `--upgrade` weist `pip` an, die Packages zu aktualisieren, wenn sie bereits installiert sind. diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md index 6540761ac..2152f1a0e 100644 --- a/docs/em/docs/deployment/docker.md +++ b/docs/em/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 🎛 💬 `pip` 🚫 🖊 ⏬ 📦 🌐, 👈 🕴 🚥 `pip` 🔜 🏃 🔄 ❎ 🎏 📦, ✋️ 👈 🚫 💼 🕐❔ 👷 ⏮️ 📦. - !!! note - `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦. + /// note + + `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦. + + /// `--upgrade` 🎛 💬 `pip` ♻ 📦 🚥 👫 ⏪ ❎. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index e86c34e48..9d6b773f7 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -458,9 +458,9 @@ Serving at: http://127.0.0.1:8008 * Do not change anything enclosed in "``" (inline code). -* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. +* In lines starting with `///` translate only the ` "... Text ..."` part. Leave the rest unchanged. -* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. +* You can translate info boxes like `/// warning` with for example `/// warning | Achtung`. But do not change the word immediately after the `///`, it determines the color of the info box. * Do not change the paths in links to images, code files, Markdown documents. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 6140b1c42..253e25fe5 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -202,8 +202,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] The `--no-cache-dir` option tells `pip` to not save the downloaded packages locally, as that is only if `pip` was going to be run again to install the same packages, but that's not the case when working with containers. - !!! note - The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + /// note + + The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + + /// The `--upgrade` option tells `pip` to upgrade the packages if they are already installed. diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index c294ef88d..53fc851f1 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -213,8 +213,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 4. 要件ファイルにあるパッケージの依存関係をインストールします `--no-cache-dir` オプションはダウンロードしたパッケージをローカルに保存しないように `pip` に指示します。これは、同じパッケージをインストールするために `pip` を再度実行する場合にのみ有効ですが、コンテナで作業する場合はそうではないです。 - !!! note - `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + /// note + + `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + + /// `--upgrade` オプションは、パッケージが既にインストールされている場合、`pip` にアップグレードするように指示します。 diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md index edf10b318..502a36fc0 100644 --- a/docs/ko/docs/deployment/docker.md +++ b/docs/ko/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 옵션은 `pip`에게 다운로드한 패키지들을 로컬 환경에 저장하지 않도록 전달합니다. 이는 마치 같은 패키지를 설치하기 위해 오직 `pip`만 다시 실행하면 될 것 같지만, 컨테이너로 작업하는 경우 그렇지는 않습니다. - !!! note "노트" - `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + /// note | 노트 + + `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + + /// `--upgrade` 옵션은 `pip`에게 설치된 패키지들을 업데이트하도록 합니다. diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md index 7c3b15d33..932952b4a 100644 --- a/docs/ko/docs/help-fastapi.md +++ b/docs/ko/docs/help-fastapi.md @@ -118,7 +118,11 @@ 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. - !!! tip 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . + /// tip + + 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . + + /// ``` 다른 일반적인 대화에서만 채팅을 사용하십시오. diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index fa1a6b9c2..df93bac2c 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] A opção `--no-cache-dir` diz ao `pip` para não salvar os pacotes baixados localmente, pois isso só aconteceria se `pip` fosse executado novamente para instalar os mesmos pacotes, mas esse não é o caso quando trabalhamos com contêineres. - !!! note - `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + /// note + + `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + + /// A opção `--upgrade` diz ao `pip` para atualizar os pacotes se eles já estiverem instalados. diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index e627d01fe..9eef5c4d2 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -207,8 +207,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Опция `--no-cache-dir` указывает `pip` не сохранять загружаемые библиотеки на локальной машине для использования их в случае повторной загрузки. В контейнере, в случае пересборки этого шага, они всё равно будут удалены. - !!! note "Заметка" - Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + /// note | Заметка + + Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + + /// Опция `--upgrade` указывает `pip` обновить библиотеки, емли они уже установлены. diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md index e5f66dba1..f120ebfb8 100644 --- a/docs/zh/docs/deployment/docker.md +++ b/docs/zh/docs/deployment/docker.md @@ -213,8 +213,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 选项告诉 `pip` 不要在本地保存下载的包,因为只有当 `pip` 再次运行以安装相同的包时才会这样,但在与容器一起工作时情况并非如此。 - !!! note "笔记" - `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + /// note | 笔记 + + `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + + /// `--upgrade` 选项告诉 `pip` 升级软件包(如果已经安装)。 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md index e5d66482a..9c963d587 100644 --- a/docs/zh/docs/deployment/https.md +++ b/docs/zh/docs/deployment/https.md @@ -4,8 +4,11 @@ 但实际情况比这复杂得多。 -!!!提示 - 如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 +/// note | 提示 + +如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 + +/// 要从用户的视角**了解 HTTPS 的基础知识**,请查看 <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>。 From d839e3ccbbcaa771a5ce2b925a1916939556aa21 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 12 Aug 2024 21:48:16 +0000 Subject: [PATCH 698/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c861508b4..d7af1ccb6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). * 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). From 922ce32aa2a6cc4e78e8bcaa0a781d13060e4863 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 12 Aug 2024 18:04:54 -0500 Subject: [PATCH 699/846] =?UTF-8?q?=F0=9F=91=B7=20Add=20GitHub=20Action=20?= =?UTF-8?q?add-to-project=20(#11999)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/add-to-project.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .github/workflows/add-to-project.yml diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml new file mode 100644 index 000000000..701f06fae --- /dev/null +++ b/.github/workflows/add-to-project.yml @@ -0,0 +1,22 @@ +name: Add to Project + +on: + pull_request: + types: + - opened + - reopened + - synchronize + issues: + types: + - opened + - reopened + +jobs: + add-to-project: + name: Add to project + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v1.0.2 + with: + project-url: https://github.com/orgs/fastapi/projects/2 + github-token: ${{ secrets.PROJECTS_TOKEN }} From 768df2736ec57c3e54201485d4e962db7dd762c4 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 12 Aug 2024 23:05:15 +0000 Subject: [PATCH 700/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d7af1ccb6..84efe6bc0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). * 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). From 748159289f438d39ce424681c3ccd2d694561ca4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 12 Aug 2024 20:02:29 -0500 Subject: [PATCH 701/846] =?UTF-8?q?=F0=9F=91=B7=20Add=20GitHub=20Action=20?= =?UTF-8?q?labeler=20(#12000)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 23 +++++++++++++++++++++++ .github/workflows/labeler.yml | 12 ++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 .github/labeler.yml create mode 100644 .github/workflows/labeler.yml diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..e07a303b1 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,23 @@ +docs: + - changed-files: + - any-glob-to-any-file: + - docs/en/docs/* + - docs_src/* + +lang-all: + - all: + - changed-files: + - any-glob-to-any-file: + - docs/*/docs/* + - all-globs-to-all-files: + - '!docs/en/docs/*' + +internal: + - changed-files: + - any-glob-to-any-file: + - .github/* + - scripts/* + - .gitignore + - .pre-commit-config.yaml + - pdm_build.py + - requirements*.txt diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 000000000..9cbdfda21 --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,12 @@ +name: Pull Request Labeler +on: + pull_request_target: + +jobs: + labeler: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v5 From 663810cb1a2e770ffc885365a17a6244df3967f1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 13 Aug 2024 01:02:50 +0000 Subject: [PATCH 702/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 84efe6bc0..d3fa9aa40 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). * 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). From b5e167d406f2d08caa02e0672a8a2f291053fee6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 12 Aug 2024 20:47:59 -0500 Subject: [PATCH 703/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20labeler=20GitHu?= =?UTF-8?q?b=20Action=20(#12001)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index e07a303b1..758f37e37 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,22 +1,22 @@ docs: - changed-files: - any-glob-to-any-file: - - docs/en/docs/* - - docs_src/* + - docs/en/docs/**/* + - docs_src/**/* lang-all: - all: - changed-files: - any-glob-to-any-file: - - docs/*/docs/* + - docs/*/docs/**/* - all-globs-to-all-files: - - '!docs/en/docs/*' + - '!docs/en/docs/**/*' internal: - changed-files: - any-glob-to-any-file: - - .github/* - - scripts/* + - .github/**/* + - scripts/**/* - .gitignore - .pre-commit-config.yaml - pdm_build.py From 14779a3ae141f56869d845616b03cc9b77f1365a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 13 Aug 2024 01:48:24 +0000 Subject: [PATCH 704/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d3fa9aa40..7e1c49eaa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). * 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). From 48c269ba6820c5a7c39af91f9462d93b2940353c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 12 Aug 2024 21:00:25 -0500 Subject: [PATCH 705/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20GitHub=20Action?= =?UTF-8?q?=20add-to-project=20(#12002)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/add-to-project.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml index 701f06fae..dccea83f3 100644 --- a/.github/workflows/add-to-project.yml +++ b/.github/workflows/add-to-project.yml @@ -1,11 +1,7 @@ name: Add to Project on: - pull_request: - types: - - opened - - reopened - - synchronize + pull_request_target: issues: types: - opened From 14c621ea3013df983144aa4fdf9fdb4fcdbbe64c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 13 Aug 2024 02:00:51 +0000 Subject: [PATCH 706/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7e1c49eaa..2f2727797 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). From c89533254ec58785dc9f6ea0489372bafb3e8089 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Mon, 12 Aug 2024 23:54:14 -0500 Subject: [PATCH 707/846] =?UTF-8?q?=F0=9F=91=B7=20Add=20label=20checker=20?= =?UTF-8?q?GitHub=20Action=20(#12004)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/label-checker.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .github/workflows/label-checker.yml diff --git a/.github/workflows/label-checker.yml b/.github/workflows/label-checker.yml new file mode 100644 index 000000000..20e9704cb --- /dev/null +++ b/.github/workflows/label-checker.yml @@ -0,0 +1,19 @@ +name: Label Checker +on: + pull_request: + types: + - opened + - synchronize + - reopened + - labeled + - unlabeled + +jobs: + check_labels: + name: Check labels + runs-on: ubuntu-latest + steps: + - uses: docker://agilepathway/pull-request-label-checker:latest + with: + one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal + repo_token: ${{ secrets.GITHUB_TOKEN }} From 26a37a6a2043ea76d3a62df7688e64eda6ee8bd1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 13 Aug 2024 04:54:36 +0000 Subject: [PATCH 708/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f2727797..f3782805e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). From e5f25e3bcaa329834d0b7c8236c6307aca3ef66c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 13 Aug 2024 00:39:57 -0500 Subject: [PATCH 709/846] =?UTF-8?q?=F0=9F=91=B7=F0=9F=8F=BB=20Add=20GitHub?= =?UTF-8?q?=20Action=20label-checker=20(#12005)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/labeler.yml | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 9cbdfda21..7cb88936b 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,6 +1,13 @@ -name: Pull Request Labeler +name: Pull Request Labeler and Checker on: pull_request_target: + types: + - opened + - synchronize + - reopened + # For label-checker + - labeled + - unlabeled jobs: labeler: @@ -10,3 +17,12 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/labeler@v5 + # Run this after labeler applied labels + check-labels: + name: Check labels + runs-on: ubuntu-latest + steps: + - uses: docker://agilepathway/pull-request-label-checker:latest + with: + one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal + repo_token: ${{ secrets.GITHUB_TOKEN }} From 69a6456d9e3729eaefd7ba9a0196916909c0ed2a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 13 Aug 2024 05:40:18 +0000 Subject: [PATCH 710/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f3782805e..90ef1452d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). * 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). From 7c6e70a0c73ab0c32335c03070eb9a2d9b944944 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Tue, 13 Aug 2024 19:30:46 -0500 Subject: [PATCH 711/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20permissions=20a?= =?UTF-8?q?nd=20config=20for=20labeler=20GitHub=20Action=20(#12008)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/label-checker.yml | 19 ------------------- .github/workflows/labeler.yml | 4 ++++ 2 files changed, 4 insertions(+), 19 deletions(-) delete mode 100644 .github/workflows/label-checker.yml diff --git a/.github/workflows/label-checker.yml b/.github/workflows/label-checker.yml deleted file mode 100644 index 20e9704cb..000000000 --- a/.github/workflows/label-checker.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Label Checker -on: - pull_request: - types: - - opened - - synchronize - - reopened - - labeled - - unlabeled - -jobs: - check_labels: - name: Check labels - runs-on: ubuntu-latest - steps: - - uses: docker://agilepathway/pull-request-label-checker:latest - with: - one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal - repo_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 7cb88936b..7c5b4616a 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -19,6 +19,10 @@ jobs: - uses: actions/labeler@v5 # Run this after labeler applied labels check-labels: + needs: + - labeler + permissions: + pull-requests: read name: Check labels runs-on: ubuntu-latest steps: From 96cb538fa3621b7be283f4209e675327a0c1fe92 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 14 Aug 2024 00:31:10 +0000 Subject: [PATCH 712/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 90ef1452d..99c1507f8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). * 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). From 2dad7c98344f05dadd5cb198a5c5e2f9b166162f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 14 Aug 2024 09:33:27 -0500 Subject: [PATCH 713/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20configs=20for?= =?UTF-8?q?=20MkDocs=20for=20languages=20and=20social=20cards=20(#12016)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/layouts/custom.yml | 228 ------------------------------------ docs/en/mkdocs.insiders.yml | 2 - docs/en/mkdocs.yml | 3 +- 3 files changed, 2 insertions(+), 231 deletions(-) delete mode 100644 docs/en/layouts/custom.yml diff --git a/docs/en/layouts/custom.yml b/docs/en/layouts/custom.yml deleted file mode 100644 index aad81af28..000000000 --- a/docs/en/layouts/custom.yml +++ /dev/null @@ -1,228 +0,0 @@ -# Copyright (c) 2016-2023 Martin Donath <martin.donath@squidfunk.com> - -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: - -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. - -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. - -# ----------------------------------------------------------------------------- -# Configuration -# ----------------------------------------------------------------------------- - -# The same default card with a a configurable logo - -# Definitions -definitions: - - # Background image - - &background_image >- - {{ layout.background_image or "" }} - - # Background color (default: indigo) - - &background_color >- - {%- if layout.background_color -%} - {{ layout.background_color }} - {%- else -%} - {%- set palette = config.theme.palette or {} -%} - {%- if not palette is mapping -%} - {%- set palette = palette | first -%} - {%- endif -%} - {%- set primary = palette.get("primary", "indigo") -%} - {%- set primary = primary.replace(" ", "-") -%} - {{ { - "red": "#ef5552", - "pink": "#e92063", - "purple": "#ab47bd", - "deep-purple": "#7e56c2", - "indigo": "#4051b5", - "blue": "#2094f3", - "light-blue": "#02a6f2", - "cyan": "#00bdd6", - "teal": "#009485", - "green": "#4cae4f", - "light-green": "#8bc34b", - "lime": "#cbdc38", - "yellow": "#ffec3d", - "amber": "#ffc105", - "orange": "#ffa724", - "deep-orange": "#ff6e42", - "brown": "#795649", - "grey": "#757575", - "blue-grey": "#546d78", - "black": "#000000", - "white": "#ffffff" - }[primary] or "#4051b5" }} - {%- endif -%} - - # Text color (default: white) - - &color >- - {%- if layout.color -%} - {{ layout.color }} - {%- else -%} - {%- set palette = config.theme.palette or {} -%} - {%- if not palette is mapping -%} - {%- set palette = palette | first -%} - {%- endif -%} - {%- set primary = palette.get("primary", "indigo") -%} - {%- set primary = primary.replace(" ", "-") -%} - {{ { - "red": "#ffffff", - "pink": "#ffffff", - "purple": "#ffffff", - "deep-purple": "#ffffff", - "indigo": "#ffffff", - "blue": "#ffffff", - "light-blue": "#ffffff", - "cyan": "#ffffff", - "teal": "#ffffff", - "green": "#ffffff", - "light-green": "#ffffff", - "lime": "#000000", - "yellow": "#000000", - "amber": "#000000", - "orange": "#000000", - "deep-orange": "#ffffff", - "brown": "#ffffff", - "grey": "#ffffff", - "blue-grey": "#ffffff", - "black": "#ffffff", - "white": "#000000" - }[primary] or "#ffffff" }} - {%- endif -%} - - # Font family (default: Roboto) - - &font_family >- - {%- if layout.font_family -%} - {{ layout.font_family }} - {%- elif config.theme.font != false -%} - {{ config.theme.font.get("text", "Roboto") }} - {%- else -%} - Roboto - {%- endif -%} - - # Site name - - &site_name >- - {{ config.site_name }} - - # Page title - - &page_title >- - {{ page.meta.get("title", page.title) }} - - # Page title with site name - - &page_title_with_site_name >- - {%- if not page.is_homepage -%} - {{ page.meta.get("title", page.title) }} - {{ config.site_name }} - {%- else -%} - {{ page.meta.get("title", page.title) }} - {%- endif -%} - - # Page description - - &page_description >- - {{ page.meta.get("description", config.site_description) or "" }} - - - # Start of custom modified logic - # Logo - - &logo >- - {%- if layout.logo -%} - {{ layout.logo }} - {%- elif config.theme.logo -%} - {{ config.docs_dir }}/{{ config.theme.logo }} - {%- endif -%} - # End of custom modified logic - - # Logo (icon) - - &logo_icon >- - {{ config.theme.icon.logo or "" }} - -# Meta tags -tags: - - # Open Graph - og:type: website - og:title: *page_title_with_site_name - og:description: *page_description - og:image: "{{ image.url }}" - og:image:type: "{{ image.type }}" - og:image:width: "{{ image.width }}" - og:image:height: "{{ image.height }}" - og:url: "{{ page.canonical_url }}" - - # Twitter - twitter:card: summary_large_image - twitter.title: *page_title_with_site_name - twitter:description: *page_description - twitter:image: "{{ image.url }}" - -# ----------------------------------------------------------------------------- -# Specification -# ----------------------------------------------------------------------------- - -# Card size and layers -size: { width: 1200, height: 630 } -layers: - - # Background - - background: - image: *background_image - color: *background_color - - # Logo - - size: { width: 144, height: 144 } - offset: { x: 992, y: 64 } - background: - image: *logo - icon: - value: *logo_icon - color: *color - - # Site name - - size: { width: 832, height: 42 } - offset: { x: 64, y: 64 } - typography: - content: *site_name - color: *color - font: - family: *font_family - style: Bold - - # Page title - - size: { width: 832, height: 310 } - offset: { x: 62, y: 160 } - typography: - content: *page_title - align: start - color: *color - line: - amount: 3 - height: 1.25 - font: - family: *font_family - style: Bold - - # Page description - - size: { width: 832, height: 64 } - offset: { x: 64, y: 512 } - typography: - content: *page_description - align: start - color: *color - line: - amount: 2 - height: 1.5 - font: - family: *font_family - style: Regular diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index 4cec588fa..8d6d26e17 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -1,7 +1,5 @@ plugins: social: - cards_layout_dir: ../en/layouts - cards_layout: custom cards_layout_options: logo: ../en/docs/img/icon-white.svg typeset: diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d37d7f42f..d23ddd42f 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -57,7 +57,8 @@ repo_url: https://github.com/fastapi/fastapi plugins: # Material for MkDocs search: - social: + # Configured in mkdocs.insiders.yml + # social: # Other plugins macros: include_yaml: From 4c490de33d351df15907b124e5aafddaaac75d94 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 14 Aug 2024 14:33:49 +0000 Subject: [PATCH 714/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 99c1507f8..8637e4643 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). * 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). * 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). From 9f57ecd41fde086427f7cbf75d6f1e94d4d58d50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 14 Aug 2024 13:29:24 -0500 Subject: [PATCH 715/846] =?UTF-8?q?=F0=9F=91=B7=F0=9F=8F=BB=20Update=20Lab?= =?UTF-8?q?eler=20GitHub=20Actions=20(#12019)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 39 ++++++++++++++++++++++------------- .github/workflows/labeler.yml | 5 +++-- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index 758f37e37..1d49a2411 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,23 +1,34 @@ docs: - - changed-files: - - any-glob-to-any-file: - - docs/en/docs/**/* - - docs_src/**/* + - all: + - changed-files: + - any-glob-to-any-file: + - docs/en/docs/** + - docs_src/** + - all-globs-to-all-files: + - '!fastapi/**' + - '!pyproject.toml' lang-all: - all: - changed-files: - any-glob-to-any-file: - - docs/*/docs/**/* + - docs/*/docs/** - all-globs-to-all-files: - - '!docs/en/docs/**/*' + - '!docs/en/docs/**' + - '!fastapi/**' + - '!pyproject.toml' internal: - - changed-files: - - any-glob-to-any-file: - - .github/**/* - - scripts/**/* - - .gitignore - - .pre-commit-config.yaml - - pdm_build.py - - requirements*.txt + - all: + - changed-files: + - any-glob-to-any-file: + - .github/** + - scripts/** + - .gitignore + - .pre-commit-config.yaml + - pdm_build.py + - requirements*.txt + - all-globs-to-all-files: + - '!docs/*/docs/**' + - '!fastapi/**' + - '!pyproject.toml' diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 7c5b4616a..d62f1668d 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,4 +1,4 @@ -name: Pull Request Labeler and Checker +name: Labels on: pull_request_target: types: @@ -17,13 +17,14 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/labeler@v5 + with: + sync-labels: true # Run this after labeler applied labels check-labels: needs: - labeler permissions: pull-requests: read - name: Check labels runs-on: ubuntu-latest steps: - uses: docker://agilepathway/pull-request-label-checker:latest From 75705617a66300847436e39ba703af1b8d109963 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 14 Aug 2024 18:29:51 +0000 Subject: [PATCH 716/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8637e4643..2685396a7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). * 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). From 85bd4067c2133a9eac1cec30b2c7d39aa67f4fc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 14 Aug 2024 17:57:10 -0500 Subject: [PATCH 717/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20documentation=20fo?= =?UTF-8?q?r=20non-translated=20pages=20and=20scripts=20to=20verify=20them?= =?UTF-8?q?=20(#12020)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/external-links.md | 42 ------ docs/de/docs/newsletter.md | 5 - docs/de/docs/reference/apirouter.md | 24 ---- docs/de/docs/reference/background.md | 11 -- docs/de/docs/reference/dependencies.md | 29 ---- docs/de/docs/reference/encoders.md | 3 - docs/de/docs/reference/exceptions.md | 20 --- docs/de/docs/reference/fastapi.md | 31 ----- docs/de/docs/reference/httpconnection.md | 11 -- docs/de/docs/reference/index.md | 11 -- docs/de/docs/reference/middleware.md | 45 ------- docs/de/docs/reference/openapi/docs.md | 11 -- docs/de/docs/reference/openapi/index.md | 5 - docs/de/docs/reference/openapi/models.md | 5 - docs/de/docs/reference/parameters.md | 35 ----- docs/de/docs/reference/request.md | 17 --- docs/de/docs/reference/response.md | 13 -- docs/de/docs/reference/responses.md | 164 ----------------------- docs/de/docs/reference/security/index.md | 73 ---------- docs/de/docs/reference/staticfiles.md | 13 -- docs/de/docs/reference/status.md | 36 ----- docs/de/docs/reference/templating.md | 13 -- docs/de/docs/reference/testclient.md | 13 -- docs/de/docs/reference/uploadfile.md | 22 --- docs/de/docs/reference/websockets.md | 67 --------- docs/em/docs/external-links.md | 38 ------ docs/en/docs/contributing.md | 16 +++ docs/es/docs/external-links.md | 36 ----- docs/es/docs/newsletter.md | 5 - docs/fr/docs/external-links.md | 36 ----- docs/ja/docs/external-links.md | 36 ----- docs/pt/docs/external-links.md | 36 ----- docs/pt/docs/reference/apirouter.md | 24 ---- docs/pt/docs/reference/background.md | 11 -- docs/pt/docs/reference/exceptions.md | 20 --- docs/pt/docs/reference/index.md | 6 - docs/ru/docs/external-links.md | 36 ----- docs/tr/docs/external-links.md | 36 ----- docs/tr/docs/newsletter.md | 5 - scripts/docs.py | 33 +++++ scripts/mkdocs_hooks.py | 8 +- 41 files changed, 55 insertions(+), 1046 deletions(-) delete mode 100644 docs/de/docs/external-links.md delete mode 100644 docs/de/docs/newsletter.md delete mode 100644 docs/de/docs/reference/apirouter.md delete mode 100644 docs/de/docs/reference/background.md delete mode 100644 docs/de/docs/reference/dependencies.md delete mode 100644 docs/de/docs/reference/encoders.md delete mode 100644 docs/de/docs/reference/exceptions.md delete mode 100644 docs/de/docs/reference/fastapi.md delete mode 100644 docs/de/docs/reference/httpconnection.md delete mode 100644 docs/de/docs/reference/index.md delete mode 100644 docs/de/docs/reference/middleware.md delete mode 100644 docs/de/docs/reference/openapi/docs.md delete mode 100644 docs/de/docs/reference/openapi/index.md delete mode 100644 docs/de/docs/reference/openapi/models.md delete mode 100644 docs/de/docs/reference/parameters.md delete mode 100644 docs/de/docs/reference/request.md delete mode 100644 docs/de/docs/reference/response.md delete mode 100644 docs/de/docs/reference/responses.md delete mode 100644 docs/de/docs/reference/security/index.md delete mode 100644 docs/de/docs/reference/staticfiles.md delete mode 100644 docs/de/docs/reference/status.md delete mode 100644 docs/de/docs/reference/templating.md delete mode 100644 docs/de/docs/reference/testclient.md delete mode 100644 docs/de/docs/reference/uploadfile.md delete mode 100644 docs/de/docs/reference/websockets.md delete mode 100644 docs/em/docs/external-links.md delete mode 100644 docs/es/docs/external-links.md delete mode 100644 docs/es/docs/newsletter.md delete mode 100644 docs/fr/docs/external-links.md delete mode 100644 docs/ja/docs/external-links.md delete mode 100644 docs/pt/docs/external-links.md delete mode 100644 docs/pt/docs/reference/apirouter.md delete mode 100644 docs/pt/docs/reference/background.md delete mode 100644 docs/pt/docs/reference/exceptions.md delete mode 100644 docs/pt/docs/reference/index.md delete mode 100644 docs/ru/docs/external-links.md delete mode 100644 docs/tr/docs/external-links.md delete mode 100644 docs/tr/docs/newsletter.md diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md deleted file mode 100644 index ae5a6c908..000000000 --- a/docs/de/docs/external-links.md +++ /dev/null @@ -1,42 +0,0 @@ -# Externe Links und Artikel - -**FastAPI** hat eine großartige Community, die ständig wächst. - -Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. - -Hier ist eine unvollständige Liste einiger davon. - -/// tip | "Tipp" - -Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>. - -/// - -/// note | "Hinweis Deutsche Übersetzung" - -Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projekte - -Die neuesten GitHub-Projekte zum Thema `fastapi`: - -<div class="github-topic-projects"> -</div> diff --git a/docs/de/docs/newsletter.md b/docs/de/docs/newsletter.md deleted file mode 100644 index 31995b164..000000000 --- a/docs/de/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# FastAPI und Freunde Newsletter - -<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 0;"></iframe> - -<script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script> diff --git a/docs/de/docs/reference/apirouter.md b/docs/de/docs/reference/apirouter.md deleted file mode 100644 index b0728b7df..000000000 --- a/docs/de/docs/reference/apirouter.md +++ /dev/null @@ -1,24 +0,0 @@ -# `APIRouter`-Klasse - -Hier sind die Referenzinformationen für die Klasse `APIRouter` mit all ihren Parametern, Attributen und Methoden. - -Sie können die `APIRouter`-Klasse direkt von `fastapi` importieren: - -```python -from fastapi import APIRouter -``` - -::: fastapi.APIRouter - options: - members: - - websocket - - include_router - - get - - put - - post - - delete - - options - - head - - patch - - trace - - on_event diff --git a/docs/de/docs/reference/background.md b/docs/de/docs/reference/background.md deleted file mode 100644 index 0fd389325..000000000 --- a/docs/de/docs/reference/background.md +++ /dev/null @@ -1,11 +0,0 @@ -# Hintergrundtasks – `BackgroundTasks` - -Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeitsfunktion mit dem Typ `BackgroundTasks` deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren. - -Sie können `BackgroundTasks` direkt von `fastapi` importieren: - -```python -from fastapi import BackgroundTasks -``` - -::: fastapi.BackgroundTasks diff --git a/docs/de/docs/reference/dependencies.md b/docs/de/docs/reference/dependencies.md deleted file mode 100644 index 2ed5b5050..000000000 --- a/docs/de/docs/reference/dependencies.md +++ /dev/null @@ -1,29 +0,0 @@ -# Abhängigkeiten – `Depends()` und `Security()` - -## `Depends()` - -Abhängigkeiten werden hauptsächlich mit der speziellen Funktion `Depends()` behandelt, die ein Callable entgegennimmt. - -Hier finden Sie deren Referenz und Parameter. - -Sie können sie direkt von `fastapi` importieren: - -```python -from fastapi import Depends -``` - -::: fastapi.Depends - -## `Security()` - -In vielen Szenarien können Sie die Sicherheit (Autorisierung, Authentifizierung usw.) mit Abhängigkeiten handhaben, indem Sie `Depends()` verwenden. - -Wenn Sie jedoch auch OAuth2-Scopes deklarieren möchten, können Sie `Security()` anstelle von `Depends()` verwenden. - -Sie können `Security()` direkt von `fastapi` importieren: - -```python -from fastapi import Security -``` - -::: fastapi.Security diff --git a/docs/de/docs/reference/encoders.md b/docs/de/docs/reference/encoders.md deleted file mode 100644 index 2489b8c60..000000000 --- a/docs/de/docs/reference/encoders.md +++ /dev/null @@ -1,3 +0,0 @@ -# Encoder – `jsonable_encoder` - -::: fastapi.encoders.jsonable_encoder diff --git a/docs/de/docs/reference/exceptions.md b/docs/de/docs/reference/exceptions.md deleted file mode 100644 index 230f902a9..000000000 --- a/docs/de/docs/reference/exceptions.md +++ /dev/null @@ -1,20 +0,0 @@ -# Exceptions – `HTTPException` und `WebSocketException` - -Dies sind die <abbr title="Exception – Ausnahme, Fehler: Python-Objekt, das einen Fehler nebst Metadaten repräsentiert">Exceptions</abbr>, die Sie auslösen können, um dem Client Fehler zu berichten. - -Wenn Sie eine Exception auslösen, wird, wie es bei normalem Python der Fall wäre, der Rest der Ausführung abgebrochen. Auf diese Weise können Sie diese Exceptions von überall im Code werfen, um einen Request abzubrechen und den Fehler dem Client anzuzeigen. - -Sie können Folgendes verwenden: - -* `HTTPException` -* `WebSocketException` - -Diese Exceptions können direkt von `fastapi` importiert werden: - -```python -from fastapi import HTTPException, WebSocketException -``` - -::: fastapi.HTTPException - -::: fastapi.WebSocketException diff --git a/docs/de/docs/reference/fastapi.md b/docs/de/docs/reference/fastapi.md deleted file mode 100644 index 4e6a56971..000000000 --- a/docs/de/docs/reference/fastapi.md +++ /dev/null @@ -1,31 +0,0 @@ -# `FastAPI`-Klasse - -Hier sind die Referenzinformationen für die Klasse `FastAPI` mit all ihren Parametern, Attributen und Methoden. - -Sie können die `FastAPI`-Klasse direkt von `fastapi` importieren: - -```python -from fastapi import FastAPI -``` - -::: fastapi.FastAPI - options: - members: - - openapi_version - - webhooks - - state - - dependency_overrides - - openapi - - websocket - - include_router - - get - - put - - post - - delete - - options - - head - - patch - - trace - - on_event - - middleware - - exception_handler diff --git a/docs/de/docs/reference/httpconnection.md b/docs/de/docs/reference/httpconnection.md deleted file mode 100644 index 32a9696fa..000000000 --- a/docs/de/docs/reference/httpconnection.md +++ /dev/null @@ -1,11 +0,0 @@ -# `HTTPConnection`-Klasse - -Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. - -Sie können diese von `fastapi.requests` importieren: - -```python -from fastapi.requests import HTTPConnection -``` - -::: fastapi.requests.HTTPConnection diff --git a/docs/de/docs/reference/index.md b/docs/de/docs/reference/index.md deleted file mode 100644 index 6fd0ef15f..000000000 --- a/docs/de/docs/reference/index.md +++ /dev/null @@ -1,11 +0,0 @@ -# Referenz – Code-API - -Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribute und alle FastAPI-Teile, die Sie in Ihren Anwendungen verwenden können. - -Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen. - -/// note | "Hinweis Deutsche Übersetzung" - -Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch. - -/// diff --git a/docs/de/docs/reference/middleware.md b/docs/de/docs/reference/middleware.md deleted file mode 100644 index d8d2d50fc..000000000 --- a/docs/de/docs/reference/middleware.md +++ /dev/null @@ -1,45 +0,0 @@ -# Middleware - -Es gibt mehrere Middlewares, die direkt von Starlette bereitgestellt werden. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Middleware](../advanced/middleware.md). - -::: fastapi.middleware.cors.CORSMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.cors import CORSMiddleware -``` - -::: fastapi.middleware.gzip.GZipMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.gzip import GZipMiddleware -``` - -::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware -``` - -::: fastapi.middleware.trustedhost.TrustedHostMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.trustedhost import TrustedHostMiddleware -``` - -::: fastapi.middleware.wsgi.WSGIMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.wsgi import WSGIMiddleware -``` diff --git a/docs/de/docs/reference/openapi/docs.md b/docs/de/docs/reference/openapi/docs.md deleted file mode 100644 index 3c19ba917..000000000 --- a/docs/de/docs/reference/openapi/docs.md +++ /dev/null @@ -1,11 +0,0 @@ -# OpenAPI `docs` - -Werkzeuge zur Verwaltung der automatischen OpenAPI-UI-Dokumentation, einschließlich Swagger UI (standardmäßig unter `/docs`) und ReDoc (standardmäßig unter `/redoc`). - -::: fastapi.openapi.docs.get_swagger_ui_html - -::: fastapi.openapi.docs.get_redoc_html - -::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html - -::: fastapi.openapi.docs.swagger_ui_default_parameters diff --git a/docs/de/docs/reference/openapi/index.md b/docs/de/docs/reference/openapi/index.md deleted file mode 100644 index 0ae3d67c6..000000000 --- a/docs/de/docs/reference/openapi/index.md +++ /dev/null @@ -1,5 +0,0 @@ -# OpenAPI - -Es gibt mehrere Werkzeuge zur Handhabung von OpenAPI. - -Normalerweise müssen Sie diese nicht verwenden, es sei denn, Sie haben einen bestimmten fortgeschrittenen Anwendungsfall, welcher das erfordert. diff --git a/docs/de/docs/reference/openapi/models.md b/docs/de/docs/reference/openapi/models.md deleted file mode 100644 index 64306b15f..000000000 --- a/docs/de/docs/reference/openapi/models.md +++ /dev/null @@ -1,5 +0,0 @@ -# OpenAPI-`models` - -OpenAPI Pydantic-Modelle, werden zum Generieren und Validieren der generierten OpenAPI verwendet. - -::: fastapi.openapi.models diff --git a/docs/de/docs/reference/parameters.md b/docs/de/docs/reference/parameters.md deleted file mode 100644 index 2638eaf48..000000000 --- a/docs/de/docs/reference/parameters.md +++ /dev/null @@ -1,35 +0,0 @@ -# Request-Parameter - -Hier die Referenzinformationen für die Request-Parameter. - -Dies sind die Sonderfunktionen, die Sie mittels `Annotated` in *Pfadoperation-Funktion*-Parameter oder Abhängigkeitsfunktionen einfügen können, um Daten aus dem Request abzurufen. - -Dies beinhaltet: - -* `Query()` -* `Path()` -* `Body()` -* `Cookie()` -* `Header()` -* `Form()` -* `File()` - -Sie können diese alle direkt von `fastapi` importieren: - -```python -from fastapi import Body, Cookie, File, Form, Header, Path, Query -``` - -::: fastapi.Query - -::: fastapi.Path - -::: fastapi.Body - -::: fastapi.Cookie - -::: fastapi.Header - -::: fastapi.Form - -::: fastapi.File diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md deleted file mode 100644 index cf7eb61ad..000000000 --- a/docs/de/docs/reference/request.md +++ /dev/null @@ -1,17 +0,0 @@ -# `Request`-Klasse - -Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als vom Typ `Request` deklarieren und dann direkt auf das Requestobjekt zugreifen, ohne jegliche Validierung, usw. - -Sie können es direkt von `fastapi` importieren: - -```python -from fastapi import Request -``` - -/// tip | "Tipp" - -Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. - -/// - -::: fastapi.Request diff --git a/docs/de/docs/reference/response.md b/docs/de/docs/reference/response.md deleted file mode 100644 index 215918931..000000000 --- a/docs/de/docs/reference/response.md +++ /dev/null @@ -1,13 +0,0 @@ -# `Response`-Klasse - -Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als `Response` deklarieren und dann Daten für die Response wie Header oder Cookies festlegen. - -Diese können Sie auch direkt verwenden, um eine Instanz davon zu erstellen und diese von Ihren *Pfadoperationen* zurückzugeben. - -Sie können sie direkt von `fastapi` importieren: - -```python -from fastapi import Response -``` - -::: fastapi.Response diff --git a/docs/de/docs/reference/responses.md b/docs/de/docs/reference/responses.md deleted file mode 100644 index c0e9f07e7..000000000 --- a/docs/de/docs/reference/responses.md +++ /dev/null @@ -1,164 +0,0 @@ -# Benutzerdefinierte Responseklassen – File, HTML, Redirect, Streaming, usw. - -Es gibt mehrere benutzerdefinierte Responseklassen, von denen Sie eine Instanz erstellen und diese direkt von Ihren *Pfadoperationen* zurückgeben können. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu benutzerdefinierten Responses – HTML, Stream, Datei, andere](../advanced/custom-response.md). - -Sie können diese direkt von `fastapi.responses` importieren: - -```python -from fastapi.responses import ( - FileResponse, - HTMLResponse, - JSONResponse, - ORJSONResponse, - PlainTextResponse, - RedirectResponse, - Response, - StreamingResponse, - UJSONResponse, -) -``` - -## FastAPI-Responses - -Es gibt einige benutzerdefinierte FastAPI-Responseklassen, welche Sie verwenden können, um die JSON-Performanz zu optimieren. - -::: fastapi.responses.UJSONResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.ORJSONResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -## Starlette-Responses - -::: fastapi.responses.FileResponse - options: - members: - - chunk_size - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.HTMLResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.JSONResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.PlainTextResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.RedirectResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.Response - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.StreamingResponse - options: - members: - - body_iterator - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie diff --git a/docs/de/docs/reference/security/index.md b/docs/de/docs/reference/security/index.md deleted file mode 100644 index 4c2375f2f..000000000 --- a/docs/de/docs/reference/security/index.md +++ /dev/null @@ -1,73 +0,0 @@ -# Sicherheitstools - -Wenn Sie Abhängigkeiten mit OAuth2-Scopes deklarieren müssen, verwenden Sie `Security()`. - -Aber Sie müssen immer noch definieren, was das <abbr title="Das von dem abhängt, die zu verwendende Abhängigkeit">Dependable</abbr>, das Callable ist, welches Sie als Parameter an `Depends()` oder `Security()` übergeben. - -Es gibt mehrere Tools, mit denen Sie diese Dependables erstellen können, und sie werden in OpenAPI integriert, sodass sie in der Oberfläche der automatischen Dokumentation angezeigt werden und von automatisch generierten Clients und SDKs, usw., verwendet werden können. - -Sie können sie von `fastapi.security` importieren: - -```python -from fastapi.security import ( - APIKeyCookie, - APIKeyHeader, - APIKeyQuery, - HTTPAuthorizationCredentials, - HTTPBasic, - HTTPBasicCredentials, - HTTPBearer, - HTTPDigest, - OAuth2, - OAuth2AuthorizationCodeBearer, - OAuth2PasswordBearer, - OAuth2PasswordRequestForm, - OAuth2PasswordRequestFormStrict, - OpenIdConnect, - SecurityScopes, -) -``` - -## API-Schlüssel-Sicherheitsschemas - -::: fastapi.security.APIKeyCookie - -::: fastapi.security.APIKeyHeader - -::: fastapi.security.APIKeyQuery - -## HTTP-Authentifizierungsschemas - -::: fastapi.security.HTTPBasic - -::: fastapi.security.HTTPBearer - -::: fastapi.security.HTTPDigest - -## HTTP-Anmeldeinformationen - -::: fastapi.security.HTTPAuthorizationCredentials - -::: fastapi.security.HTTPBasicCredentials - -## OAuth2-Authentifizierung - -::: fastapi.security.OAuth2 - -::: fastapi.security.OAuth2AuthorizationCodeBearer - -::: fastapi.security.OAuth2PasswordBearer - -## OAuth2-Passwortformulare - -::: fastapi.security.OAuth2PasswordRequestForm - -::: fastapi.security.OAuth2PasswordRequestFormStrict - -## OAuth2-Sicherheitsscopes in Abhängigkeiten - -::: fastapi.security.SecurityScopes - -## OpenID Connect - -::: fastapi.security.OpenIdConnect diff --git a/docs/de/docs/reference/staticfiles.md b/docs/de/docs/reference/staticfiles.md deleted file mode 100644 index 5629854c6..000000000 --- a/docs/de/docs/reference/staticfiles.md +++ /dev/null @@ -1,13 +0,0 @@ -# Statische Dateien – `StaticFiles` - -Sie können die `StaticFiles`-Klasse verwenden, um statische Dateien wie JavaScript, CSS, Bilder, usw. bereitzustellen. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu statischen Dateien](../tutorial/static-files.md). - -Sie können sie direkt von `fastapi.staticfiles` importieren: - -```python -from fastapi.staticfiles import StaticFiles -``` - -::: fastapi.staticfiles.StaticFiles diff --git a/docs/de/docs/reference/status.md b/docs/de/docs/reference/status.md deleted file mode 100644 index 1d9458ee9..000000000 --- a/docs/de/docs/reference/status.md +++ /dev/null @@ -1,36 +0,0 @@ -# Statuscodes - -Sie können das Modul `status` von `fastapi` importieren: - -```python -from fastapi import status -``` - -`status` wird direkt von Starlette bereitgestellt. - -Es enthält eine Gruppe benannter Konstanten (Variablen) mit ganzzahligen Statuscodes. - -Zum Beispiel: - -* 200: `status.HTTP_200_OK` -* 403: `status.HTTP_403_FORBIDDEN` -* usw. - -Es kann praktisch sein, schnell auf HTTP- (und WebSocket-)Statuscodes in Ihrer Anwendung zuzugreifen, indem Sie die automatische Vervollständigung für den Namen verwenden, ohne sich die Zahlen für die Statuscodes merken zu müssen. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Response-Statuscodes](../tutorial/response-status-code.md). - -## Beispiel - -```python -from fastapi import FastAPI, status - -app = FastAPI() - - -@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT) -def read_items(): - return [{"name": "Plumbus"}, {"name": "Portal Gun"}] -``` - -::: fastapi.status diff --git a/docs/de/docs/reference/templating.md b/docs/de/docs/reference/templating.md deleted file mode 100644 index c367a0179..000000000 --- a/docs/de/docs/reference/templating.md +++ /dev/null @@ -1,13 +0,0 @@ -# Templating – `Jinja2Templates` - -Sie können die `Jinja2Templates`-Klasse verwenden, um Jinja-Templates zu rendern. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Templates](../advanced/templates.md). - -Sie können die Klasse direkt von `fastapi.templating` importieren: - -```python -from fastapi.templating import Jinja2Templates -``` - -::: fastapi.templating.Jinja2Templates diff --git a/docs/de/docs/reference/testclient.md b/docs/de/docs/reference/testclient.md deleted file mode 100644 index 5bc089c05..000000000 --- a/docs/de/docs/reference/testclient.md +++ /dev/null @@ -1,13 +0,0 @@ -# Testclient – `TestClient` - -Sie können die `TestClient`-Klasse verwenden, um FastAPI-Anwendungen zu testen, ohne eine tatsächliche HTTP- und Socket-Verbindung zu erstellen, Sie kommunizieren einfach direkt mit dem FastAPI-Code. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Testen](../tutorial/testing.md). - -Sie können sie direkt von `fastapi.testclient` importieren: - -```python -from fastapi.testclient import TestClient -``` - -::: fastapi.testclient.TestClient diff --git a/docs/de/docs/reference/uploadfile.md b/docs/de/docs/reference/uploadfile.md deleted file mode 100644 index 8556edf82..000000000 --- a/docs/de/docs/reference/uploadfile.md +++ /dev/null @@ -1,22 +0,0 @@ -# `UploadFile`-Klasse - -Sie können *Pfadoperation-Funktionsparameter* als Parameter vom Typ `UploadFile` definieren, um Dateien aus dem Request zu erhalten. - -Sie können es direkt von `fastapi` importieren: - -```python -from fastapi import UploadFile -``` - -::: fastapi.UploadFile - options: - members: - - file - - filename - - size - - headers - - content_type - - read - - write - - seek - - close diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md deleted file mode 100644 index d5597d0ee..000000000 --- a/docs/de/docs/reference/websockets.md +++ /dev/null @@ -1,67 +0,0 @@ -# WebSockets - -Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter vom Typ `WebSocket` und können damit Daten vom Client lesen und an ihn senden. Er wird direkt von Starlette bereitgestellt, Sie können ihn aber von `fastapi` importieren: - -```python -from fastapi import WebSocket -``` - -/// tip | "Tipp" - -Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. - -/// - -::: fastapi.WebSocket - options: - members: - - scope - - app - - url - - base_url - - headers - - query_params - - path_params - - cookies - - client - - state - - url_for - - client_state - - application_state - - receive - - send - - accept - - receive_text - - receive_bytes - - receive_json - - iter_text - - iter_bytes - - iter_json - - send_text - - send_bytes - - send_json - - close - -Wenn ein Client die Verbindung trennt, wird eine `WebSocketDisconnect`-Exception ausgelöst, die Sie abfangen können. - -Sie können diese direkt von `fastapi` importieren: - -```python -from fastapi import WebSocketDisconnect -``` - -::: fastapi.WebSocketDisconnect - -## WebSockets – zusätzliche Klassen - -Zusätzliche Klassen für die Handhabung von WebSockets. - -Werden direkt von Starlette bereitgestellt, Sie können sie jedoch von `fastapi` importieren: - -```python -from fastapi.websockets import WebSocketDisconnect, WebSocketState -``` - -::: fastapi.websockets.WebSocketDisconnect - -::: fastapi.websockets.WebSocketState diff --git a/docs/em/docs/external-links.md b/docs/em/docs/external-links.md deleted file mode 100644 index 486b134d4..000000000 --- a/docs/em/docs/external-links.md +++ /dev/null @@ -1,38 +0,0 @@ -# 🔢 🔗 & 📄 - -**FastAPI** ✔️ 👑 👪 🕧 💗. - -📤 📚 🏤, 📄, 🧰, & 🏗, 🔗 **FastAPI**. - -📥 ❌ 📇 👫. - -/// tip - -🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>. - -/// - -## 📄 - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## 🏗 - -⏪ 📂 🏗 ⏮️ ❔ `fastapi`: - -<div class="github-topic-projects"> -</div> diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 9d6b773f7..73d96e6e1 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -370,6 +370,22 @@ If you go to your browser you will see that now the docs show your new section ( Now you can translate it all and see how it looks as you save the file. +/// warning + +Don't translate: + +* Files under `reference/` +* `release-notes.md` +* `fastapi-people.md` +* `external-links.md` +* `newsletter.md` +* `management-tasks.md` +* `management.md` + +Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc. + +/// + #### New Language Let's say that you want to add translations for a language that is not yet translated, not even some pages. diff --git a/docs/es/docs/external-links.md b/docs/es/docs/external-links.md deleted file mode 100644 index 8163349ab..000000000 --- a/docs/es/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Enlaces Externos y Artículos - -**FastAPI** tiene una gran comunidad en constante crecimiento. - -Hay muchas publicaciones, artículos, herramientas y proyectos relacionados con **FastAPI**. - -Aquí hay una lista incompleta de algunos de ellos. - -/// tip | "Consejo" - -Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request agregándolo</a>. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projects - -Últimos proyectos de GitHub con el tema `fastapi`: - -<div class="github-topic-projects"> -</div> diff --git a/docs/es/docs/newsletter.md b/docs/es/docs/newsletter.md deleted file mode 100644 index f4dcfe155..000000000 --- a/docs/es/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# Boletín de Noticias de FastAPI y amigos - -<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 0;"></iframe> - -<script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script> diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md deleted file mode 100644 index 91a9eae58..000000000 --- a/docs/fr/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Articles et liens externes - -**FastAPI** possède une grande communauté en constante extension. - -Il existe de nombreux articles, outils et projets liés à **FastAPI**. - -Voici une liste incomplète de certains d'entre eux. - -/// tip | "Astuce" - -Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projets - -Les projets Github avec le topic `fastapi` les plus récents : - -<div class="github-topic-projects"> -</div> diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md deleted file mode 100644 index 65cebc8d2..000000000 --- a/docs/ja/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# 外部リンク・記事 - -**FastAPI**には、絶えず成長している素晴らしいコミュニティがあります。 - -**FastAPI**に関連する投稿、記事、ツール、およびプロジェクトは多数あります。 - -それらの不完全なリストを以下に示します。 - -/// tip | "豆知識" - -ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">プルリクエストして下さい</a>。 - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## プロジェクト - -`fastapi`トピックの最新のGitHubプロジェクト: - -<div class="github-topic-projects"> -</div> diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md deleted file mode 100644 index 622ad5ab6..000000000 --- a/docs/pt/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Links externos e Artigos - -**FastAPI** tem uma grande comunidade em crescimento constante. - -Existem muitas postagens, artigos, ferramentas e projetos relacionados ao **FastAPI**. - -Aqui tem uma lista, incompleta, de algumas delas. - -/// tip | "Dica" - -Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um <a href="https://github.com/fastapi/fastapi/edit/master/docs/external-links.md" class="external-link" target="_blank">_Pull Request_ adicionando ele</a>. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projetos - -Últimos projetos no GitHub com o tópico `fastapi`: - -<div class="github-topic-projects"> -</div> diff --git a/docs/pt/docs/reference/apirouter.md b/docs/pt/docs/reference/apirouter.md deleted file mode 100644 index 7568601c9..000000000 --- a/docs/pt/docs/reference/apirouter.md +++ /dev/null @@ -1,24 +0,0 @@ -# Classe `APIRouter` - -Aqui está a informação de referência para a classe `APIRouter`, com todos os seus parâmetros, atributos e métodos. - -Você pode importar a classe `APIRouter` diretamente do `fastapi`: - -```python -from fastapi import APIRouter -``` - -::: fastapi.APIRouter - options: - members: - - websocket - - include_router - - get - - put - - post - - delete - - options - - head - - patch - - trace - - on_event diff --git a/docs/pt/docs/reference/background.md b/docs/pt/docs/reference/background.md deleted file mode 100644 index bfc15aa76..000000000 --- a/docs/pt/docs/reference/background.md +++ /dev/null @@ -1,11 +0,0 @@ -# Tarefas em Segundo Plano - `BackgroundTasks` - -Você pode declarar um parâmetro em uma *função de operação de rota* ou em uma função de dependência com o tipo `BackgroundTasks`, e então utilizá-lo para agendar a execução de tarefas em segundo plano após o envio da resposta. - -Você pode importá-lo diretamente do `fastapi`: - -```python -from fastapi import BackgroundTasks -``` - -::: fastapi.BackgroundTasks diff --git a/docs/pt/docs/reference/exceptions.md b/docs/pt/docs/reference/exceptions.md deleted file mode 100644 index d6b5d2613..000000000 --- a/docs/pt/docs/reference/exceptions.md +++ /dev/null @@ -1,20 +0,0 @@ -# Exceções - `HTTPException` e `WebSocketException` - -Essas são as exceções que você pode lançar para mostrar erros ao cliente. - -Quando você lança uma exceção, como aconteceria com o Python normal, o restante da execução é abortado. Dessa forma, você pode lançar essas exceções de qualquer lugar do código para abortar uma solicitação e mostrar o erro ao cliente. - -Você pode usar: - -* `HTTPException` -* `WebSocketException` - -Essas exceções podem ser importadas diretamente do `fastapi`: - -```python -from fastapi import HTTPException, WebSocketException -``` - -::: fastapi.HTTPException - -::: fastapi.WebSocketException diff --git a/docs/pt/docs/reference/index.md b/docs/pt/docs/reference/index.md deleted file mode 100644 index 533a6a996..000000000 --- a/docs/pt/docs/reference/index.md +++ /dev/null @@ -1,6 +0,0 @@ -# Referência - API de Código - -Aqui está a referência ou API de código, as classes, funções, parâmetros, atributos e todas as partes do FastAPI que você pode usar em suas aplicações. - -Se você quer **aprender FastAPI**, é muito melhor ler o -[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/). diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md deleted file mode 100644 index 2c0e153e2..000000000 --- a/docs/ru/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Внешние ссылки и статьи - -**FastAPI** имеет отличное и постоянно растущее сообщество. - -Существует множество сообщений, статей, инструментов и проектов, связанных с **FastAPI**. - -Вот неполный список некоторых из них. - -/// tip - -Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Проекты - -Последние GitHub-проекты с пометкой `fastapi`: - -<div class="github-topic-projects"> -</div> diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md deleted file mode 100644 index 6e8af4025..000000000 --- a/docs/tr/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Harici Bağlantılar ve Makaleler - -**FastAPI** sürekli büyüyen harika bir topluluğa sahiptir. - -**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır. - -Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. - -/// tip | "İpucu" - -Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a> oluşturabilirsiniz. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* <a href="{{ item.link }}" class="external-link" target="_blank">{{ item.title }}</a> by <a href="{{ item.author_link }}" class="external-link" target="_blank">{{ item.author }}</a>. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projeler - -`fastapi` konulu en son GitHub projeleri: - -<div class="github-topic-projects"> -</div> diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md deleted file mode 100644 index 22ca1b1e2..000000000 --- a/docs/tr/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# FastAPI ve Arkadaşları Bülteni - -<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 0;"></iframe> - -<script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script> diff --git a/scripts/docs.py b/scripts/docs.py index 5ef548889..1dba4aa0a 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -26,6 +26,15 @@ missing_translation_snippet = """ {!../../../docs/missing-translation.md!} """ +non_translated_sections = [ + "reference/", + "release-notes.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", +] + docs_path = Path("docs") en_docs_path = Path("docs/en") en_config_path: Path = en_docs_path / mkdocs_name @@ -333,10 +342,34 @@ def verify_config() -> None: typer.echo("Valid mkdocs.yml ✅") +@app.command() +def verify_non_translated() -> None: + """ + Verify there are no files in the non translatable pages. + """ + print("Verifying non translated pages") + lang_paths = get_lang_paths() + error_paths = [] + for lang in lang_paths: + if lang.name == "en": + continue + for non_translatable in non_translated_sections: + non_translatable_path = lang / "docs" / non_translatable + if non_translatable_path.exists(): + error_paths.append(non_translatable_path) + if error_paths: + print("Non-translated pages found, remove them:") + for error_path in error_paths: + print(error_path) + raise typer.Abort() + print("No non-translated pages found ✅") + + @app.command() def verify_docs(): verify_readme() verify_config() + verify_non_translated() @app.command() diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 24ffecf46..10e8dc153 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -8,9 +8,13 @@ from mkdocs.structure.files import File, Files from mkdocs.structure.nav import Link, Navigation, Section from mkdocs.structure.pages import Page -non_traslated_sections = [ +non_translated_sections = [ "reference/", "release-notes.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", ] @@ -128,7 +132,7 @@ def on_page_markdown( markdown: str, *, page: Page, config: MkDocsConfig, files: Files ) -> str: if isinstance(page.file, EnFile): - for excluded_section in non_traslated_sections: + for excluded_section in non_translated_sections: if page.file.src_path.startswith(excluded_section): return markdown missing_translation_content = get_missing_translation_content(config.docs_dir) From 9c3845be8d42d08cc7ee8c8450adb8b41ca2e756 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 14 Aug 2024 22:57:35 +0000 Subject: [PATCH 718/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2685396a7..26dc7df89 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add documentation for non-translated pages and scripts to verify them. PR [#12020](https://github.com/fastapi/fastapi/pull/12020) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo). ### Translations From c82497f78e38fd37cb214c5e0676e09fd1f70df7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 15 Aug 2024 10:21:25 -0500 Subject: [PATCH 719/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20section?= =?UTF-8?q?=20about=20"Don't=20Translate=20these=20Pages"=20(#12022)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/contributing.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 73d96e6e1..63e1f359a 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -370,9 +370,9 @@ If you go to your browser you will see that now the docs show your new section ( Now you can translate it all and see how it looks as you save the file. -/// warning +#### Don't Translate these Pages -Don't translate: +🚨 Don't translate: * Files under `reference/` * `release-notes.md` @@ -384,8 +384,6 @@ Don't translate: Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc. -/// - #### New Language Let's say that you want to add translations for a language that is not yet translated, not even some pages. From b04d29c983bd6705bda5248f5735705f0e6d06e6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 15:21:51 +0000 Subject: [PATCH 720/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 26dc7df89..0f05df5ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update docs section about "Don't Translate these Pages". PR [#12022](https://github.com/fastapi/fastapi/pull/12022) by [@tiangolo](https://github.com/tiangolo). * 📝 Add documentation for non-translated pages and scripts to verify them. PR [#12020](https://github.com/fastapi/fastapi/pull/12020) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo). From 959e793297ac9f51b5811063e8f5a36059fefb35 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Thu, 15 Aug 2024 17:35:17 +0200 Subject: [PATCH 721/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/testing-dependencies.md`?= =?UTF-8?q?=20(#11995)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/testing-dependencies.md | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 docs/pt/docs/advanced/testing-dependencies.md diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..747dd7d06 --- /dev/null +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -0,0 +1,103 @@ +# Testando Dependências com Sobreposição (Overrides) + +## Sobrepondo dependências durante os testes + +Existem alguns cenários onde você deseje sobrepor uma dependência durante os testes. + +Você não quer que a dependência original execute (e nenhuma das subdependências que você possa ter). + +Em vez disso, você deseja fornecer uma dependência diferente que será usada somente durante os testes (possivelmente apenas para alguns testes específicos) e fornecerá um valor que pode ser usado onde o valor da dependência original foi usado. + +### Casos de uso: serviço externo + +Um exemplo pode ser que você possua um provedor de autenticação externo que você precisa chamar. + +Você envia ao serviço um *token* e ele retorna um usuário autenticado. + +Este provedor pode cobrar por requisição, e chamá-lo pode levar mais tempo do que se você tivesse um usuário fixo para os testes. + +Você provavelmente quer testar o provedor externo uma vez, mas não necessariamente chamá-lo em todos os testes que executarem. + +Neste caso, você pode sobrepor (*override*) a dependência que chama o provedor, e utilizar uma dependência customizada que retorna um *mock* do usuário, apenas para os seus testes. + +### Utilize o atributo `app.dependency_overrides` + +Para estes casos, a sua aplicação **FastAPI** possui o atributo `app.dependency_overrides`. Ele é um simples `dict`. + +Para sobrepor a dependência para os testes, você coloca como chave a dependência original (a função), e como valor, a sua sobreposição da dependência (outra função). + +E então o **FastAPI** chamará a sobreposição no lugar da dependência original. + +//// tab | Python 3.10+ + +```Python hl_lines="26-27 30" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="24-25 28" +{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001.py!} +``` + +//// + +/// tip | "Dica" + +Você pode definir uma sobreposição de dependência para uma dependência que é utilizada em qualquer lugar da sua aplicação **FastAPI**. + +A dependência original pode estar sendo utilizada em uma *função de operação de rota*, um *docorador de operação de rota* (quando você não utiliza o valor retornado), uma chamada ao `.include_router()`, etc. + +O FastAPI ainda poderá sobrescrevê-lo. + +/// + +E então você pode redefinir as suas sobreposições (removê-las) definindo o `app.dependency_overrides` como um `dict` vazio: + +```Python +app.dependency_overrides = {} +``` + +/// tip | "Dica" + +Se você quer sobrepor uma dependência apenas para alguns testes, você pode definir a sobreposição no início do testes (dentro da função de teste) e reiniciá-la ao final (no final da função de teste). + +/// From 4fe1af494af4a0bde8a0c8efc2dbfba4ec74a89b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 15:35:41 +0000 Subject: [PATCH 722/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0f05df5ad..0f1db29f1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). From 60fe2b19e895f0e54a577a0bca86e0dba0926d7b Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques <rafaelomarques@gmail.com> Date: Thu, 15 Aug 2024 17:36:31 +0200 Subject: [PATCH 723/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/testing-websockets.md`=20?= =?UTF-8?q?(#11994)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/testing-websockets.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/pt/docs/advanced/testing-websockets.md diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..f458a05d4 --- /dev/null +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -0,0 +1,15 @@ +# Testando WebSockets + +Você pode usar o mesmo `TestClient` para testar WebSockets. + +Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: + +```Python hl_lines="27-31" +{!../../../docs_src/app_testing/tutorial002.py!} +``` + +/// note | "Nota" + +Para mais detalhes, confira a documentação do Starlette para <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">testar WebSockets</a>. + +/// From e1b52cf4285c73639c30e1cefb698f783494aa8c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 15:38:02 +0000 Subject: [PATCH 724/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0f1db29f1..51dc34986 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-websockets.md`. PR [#11994](https://github.com/fastapi/fastapi/pull/11994) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). From 646232121bf6138a7056bfec5ea2c54201d7e929 Mon Sep 17 00:00:00 2001 From: marcelomarkus <marcelomarkus@gmail.com> Date: Thu, 15 Aug 2024 12:38:22 -0300 Subject: [PATCH 725/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/bigger-applications.md`?= =?UTF-8?q?=20(#11971)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/bigger-applications.md | 556 +++++++++++++++++++ 1 file changed, 556 insertions(+) create mode 100644 docs/pt/docs/tutorial/bigger-applications.md diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..7137bf865 --- /dev/null +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -0,0 +1,556 @@ +# Aplicações Maiores - Múltiplos Arquivos + +Se você está construindo uma aplicação ou uma API web, é raro que você possa colocar tudo em um único arquivo. + +**FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade. + +/// info | "Informação" + +Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask. + +/// + +## Um exemplo de estrutura de arquivos + +Digamos que você tenha uma estrutura de arquivos como esta: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +│ ├── dependencies.py +│ └── routers +│ │ ├── __init__.py +│ │ ├── items.py +│ │ └── users.py +│ └── internal +│ ├── __init__.py +│ └── admin.py +``` + +/// tip | "Dica" + +Existem vários arquivos `__init__.py` presentes em cada diretório ou subdiretório. + +Isso permite a importação de código de um arquivo para outro. + +Por exemplo, no arquivo `app/main.py`, você poderia ter uma linha como: + +``` +from app.routers import items +``` + +/// + +* O diretório `app` contém todo o código da aplicação. Ele possui um arquivo `app/__init__.py` vazio, o que o torna um "pacote Python" (uma coleção de "módulos Python"): `app`. +* Dentro dele, o arquivo `app/main.py` está localizado em um pacote Python (diretório com `__init__.py`). Portanto, ele é um "módulo" desse pacote: `app.main`. +* Existem também um arquivo `app/dependencies.py`, assim como o `app/main.py`, ele é um "módulo": `app.dependencies`. +* Há um subdiretório `app/routers/` com outro arquivo `__init__.py`, então ele é um "subpacote Python": `app.routers`. +* O arquivo `app/routers/items.py` está dentro de um pacote, `app/routers/`, portanto, é um "submódulo": `app.routers.items`. +* O mesmo com `app/routers/users.py`, ele é outro submódulo: `app.routers.users`. +* Há também um subdiretório `app/internal/` com outro arquivo `__init__.py`, então ele é outro "subpacote Python":`app.internal`. +* E o arquivo `app/internal/admin.py` é outro submódulo: `app.internal.admin`. + +<img src="/img/tutorial/bigger-applications/package.svg"> + +A mesma estrutura de arquivos com comentários: + +``` +. +├── app # "app" é um pacote Python +│ ├── __init__.py # este arquivo torna "app" um "pacote Python" +│ ├── main.py # "main" módulo, e.g. import app.main +│ ├── dependencies.py # "dependencies" módulo, e.g. import app.dependencies +│ └── routers # "routers" é um "subpacote Python" +│ │ ├── __init__.py # torna "routers" um "subpacote Python" +│ │ ├── items.py # "items" submódulo, e.g. import app.routers.items +│ │ └── users.py # "users" submódulo, e.g. import app.routers.users +│ └── internal # "internal" é um "subpacote Python" +│ ├── __init__.py # torna "internal" um "subpacote Python" +│ └── admin.py # "admin" submódulo, e.g. import app.internal.admin +``` + +## `APIRouter` + +Vamos supor que o arquivo dedicado a lidar apenas com usuários seja o submódulo em `/app/routers/users.py`. + +Você quer manter as *operações de rota* relacionadas aos seus usuários separadas do restante do código, para mantê-lo organizado. + +Mas ele ainda faz parte da mesma aplicação/web API **FastAPI** (faz parte do mesmo "pacote Python"). + +Você pode criar as *operações de rotas* para esse módulo usando o `APIRouter`. + +### Importar `APIRouter` + +você o importa e cria uma "instância" da mesma maneira que faria com a classe `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Operações de Rota* com `APIRouter` + +E então você o utiliza para declarar suas *operações de rota*. + +Utilize-o da mesma maneira que utilizaria a classe `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Você pode pensar em `APIRouter` como uma classe "mini `FastAPI`". + +Todas as mesmas opções são suportadas. + +Todos os mesmos `parameters`, `responses`, `dependencies`, `tags`, etc. + +/// tip | "Dica" + +Neste exemplo, a variável é chamada de `router`, mas você pode nomeá-la como quiser. + +/// + +Vamos incluir este `APIRouter` na aplicação principal `FastAPI`, mas primeiro, vamos verificar as dependências e outro `APIRouter`. + +## Dependências + +Vemos que precisaremos de algumas dependências usadas em vários lugares da aplicação. + +Então, as colocamos em seu próprio módulo de `dependencies` (`app/dependencies.py`). + +Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` personalizado: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | "Dica" + +Estamos usando um cabeçalho inventado para simplificar este exemplo. + +Mas em casos reais, você obterá melhores resultados usando os [Utilitários de Segurança](security/index.md){.internal-link target=_blank} integrados. + +/// + +## Outro módulo com `APIRouter` + +Digamos que você também tenha os endpoints dedicados a manipular "itens" do seu aplicativo no módulo em `app/routers/items.py`. + +Você tem *operações de rota* para: + +* `/items/` +* `/items/{item_id}` + +É tudo a mesma estrutura de `app/routers/users.py`. + +Mas queremos ser mais inteligentes e simplificar um pouco o código. + +Sabemos que todas as *operações de rota* neste módulo têm o mesmo: + +* Path `prefix`: `/items`. +* `tags`: (apenas uma tag: `items`). +* Extra `responses`. +* `dependências`: todas elas precisam da dependência `X-Token` que criamos. + +Então, em vez de adicionar tudo isso a cada *operação de rota*, podemos adicioná-lo ao `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Como o caminho de cada *operação de rota* deve começar com `/`, como em: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...o prefixo não deve incluir um `/` final. + +Então, o prefixo neste caso é `/items`. + +Também podemos adicionar uma lista de `tags` e `responses` extras que serão aplicadas a todas as *operações de rota* incluídas neste roteador. + +E podemos adicionar uma lista de `dependencies` que serão adicionadas a todas as *operações de rota* no roteador e serão executadas/resolvidas para cada solicitação feita a elas. + +/// tip | "Dica" + +Observe que, assim como [dependências em *decoradores de operação de rota*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, nenhum valor será passado para sua *função de operação de rota*. + +/// + +O resultado final é que os caminhos dos itens agora são: + +* `/items/` +* `/items/{item_id}` + +...como pretendíamos. + +* Elas serão marcadas com uma lista de tags que contêm uma única string `"items"`. + * Essas "tags" são especialmente úteis para os sistemas de documentação interativa automática (usando OpenAPI). +* Todas elas incluirão as `responses` predefinidas. +* Todas essas *operações de rota* terão a lista de `dependencies` avaliada/executada antes delas. + * Se você também declarar dependências em uma *operação de rota* específica, **elas também serão executadas**. + * As dependências do roteador são executadas primeiro, depois as [`dependencies` no decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} e, em seguida, as dependências de parâmetros normais. + * Você também pode adicionar [dependências de `Segurança` com `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | "Dica" + +Ter `dependências` no `APIRouter` pode ser usado, por exemplo, para exigir autenticação para um grupo inteiro de *operações de rota*. Mesmo que as dependências não sejam adicionadas individualmente a cada uma delas. + +/// + +/// check + +Os parâmetros `prefix`, `tags`, `responses` e `dependencies` são (como em muitos outros casos) apenas um recurso do **FastAPI** para ajudar a evitar duplicação de código. + +/// + +### Importar as dependências + +Este código reside no módulo `app.routers.items`, o arquivo `app/routers/items.py`. + +E precisamos obter a função de dependência do módulo `app.dependencies`, o arquivo `app/dependencies.py`. + +Então usamos uma importação relativa com `..` para as dependências: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Como funcionam as importações relativas + +/// tip | "Dica" + +Se você sabe perfeitamente como funcionam as importações, continue para a próxima seção abaixo. + +/// + +Um único ponto `.`, como em: + +```Python +from .dependencies import get_token_header +``` + +significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* encontre o módulo `dependencies` (um arquivo imaginário em `app/routers/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Mas esse arquivo não existe, nossas dependências estão em um arquivo em `app/dependencies.py`. + +Lembre-se de como nossa estrutura app/file se parece: + +<img src="/img/tutorial/bigger-applications/package.svg"> + +--- + +Os dois pontos `..`, como em: + +```Python +from ..dependencies import get_token_header +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) reside (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso funciona corretamente! 🎉 + +--- + +Da mesma forma, se tivéssemos usado três pontos `...`, como em: + +```Python +from ...dependencies import get_token_header +``` + +isso significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* então vá para o pai daquele pacote (não há pacote pai, `app` é o nível superior 😱)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso se referiria a algum pacote acima de `app/`, com seu próprio arquivo `__init__.py`, etc. Mas não temos isso. Então, isso geraria um erro em nosso exemplo. 🚨 + +Mas agora você sabe como funciona, então você pode usar importações relativas em seus próprios aplicativos, não importa o quão complexos eles sejam. 🤓 + +### Adicione algumas `tags`, `respostas` e `dependências` personalizadas + +Não estamos adicionando o prefixo `/items` nem `tags=["items"]` a cada *operação de rota* porque os adicionamos ao `APIRouter`. + +Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação de rota* específica, e também algumas `respostas` extras específicas para essa *operação de rota*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | "Dica" + +Esta última operação de caminho terá a combinação de tags: `["items", "custom"]`. + +E também terá ambas as respostas na documentação, uma para `404` e uma para `403`. + +/// + +## O principal `FastAPI` + +Agora, vamos ver o módulo em `app/main.py`. + +Aqui é onde você importa e usa a classe `FastAPI`. + +Este será o arquivo principal em seu aplicativo que une tudo. + +E como a maior parte de sua lógica agora viverá em seu próprio módulo específico, o arquivo principal será bem simples. + +### Importar `FastAPI` + +Você importa e cria uma classe `FastAPI` normalmente. + +E podemos até declarar [dependências globais](dependencies/global-dependencies.md){.internal-link target=_blank} que serão combinadas com as dependências para cada `APIRouter`: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +### Importe o `APIRouter` + +Agora importamos os outros submódulos que possuem `APIRouter`s: + +```Python hl_lines="4-5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Como os arquivos `app/routers/users.py` e `app/routers/items.py` são submódulos que fazem parte do mesmo pacote Python `app`, podemos usar um único ponto `.` para importá-los usando "importações relativas". + +### Como funciona a importação + +A seção: + +```Python +from .routers import items, users +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/main.py`) reside (o diretório `app/`)... +* procure o subpacote `routers` (o diretório em `app/routers/`)... +* e dele, importe o submódulo `items` (o arquivo em `app/routers/items.py`) e `users` (o arquivo em `app/routers/users.py`)... + +O módulo `items` terá uma variável `router` (`items.router`). Esta é a mesma que criamos no arquivo `app/routers/items.py`, é um objeto `APIRouter`. + +E então fazemos o mesmo para o módulo `users`. + +Também poderíamos importá-los como: + +```Python +from app.routers import items, users +``` + +/// info | "Informação" + +A primeira versão é uma "importação relativa": + +```Python +from .routers import items, users +``` + +A segunda versão é uma "importação absoluta": + +```Python +from app.routers import items, users +``` + +Para saber mais sobre pacotes e módulos Python, leia <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">a documentação oficial do Python sobre módulos</a>. + +/// + +### Evite colisões de nomes + +Estamos importando o submódulo `items` diretamente, em vez de importar apenas sua variável `router`. + +Isso ocorre porque também temos outra variável chamada `router` no submódulo `users`. + +Se tivéssemos importado um após o outro, como: + +```Python +from .routers.items import router +from .routers.users import router +``` + +o `router` de `users` sobrescreveria o de `items` e não poderíamos usá-los ao mesmo tempo. + +Então, para poder usar ambos no mesmo arquivo, importamos os submódulos diretamente: + +```Python hl_lines="5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +### Incluir o `APIRouter`s para `usuários` e `itens` + +Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | "Informação" + +`users.router` contém o `APIRouter` dentro do arquivo `app/routers/users.py`. + +E `items.router` contém o `APIRouter` dentro do arquivo `app/routers/items.py`. + +/// + +Com `app.include_router()` podemos adicionar cada `APIRouter` ao aplicativo principal `FastAPI`. + +Ele incluirá todas as rotas daquele roteador como parte dele. + +/// note | "Detalhe Técnico" + +Na verdade, ele criará internamente uma *operação de rota* para cada *operação de rota* que foi declarada no `APIRouter`. + +Então, nos bastidores, ele realmente funcionará como se tudo fosse o mesmo aplicativo único. + +/// + +/// check + +Você não precisa se preocupar com desempenho ao incluir roteadores. + +Isso levará microssegundos e só acontecerá na inicialização. + +Então não afetará o desempenho. ⚡ + +/// + +### Incluir um `APIRouter` com um `prefix` personalizado, `tags`, `responses` e `dependencies` + +Agora, vamos imaginar que sua organização lhe deu o arquivo `app/internal/admin.py`. + +Ele contém um `APIRouter` com algumas *operações de rota* de administração que sua organização compartilha entre vários projetos. + +Para este exemplo, será super simples. Mas digamos que, como ele é compartilhado com outros projetos na organização, não podemos modificá-lo e adicionar um `prefix`, `dependencies`, `tags`, etc. diretamente ao `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` para que todas as suas *operações de rota* comecem com `/admin`, queremos protegê-lo com as `dependências` que já temos para este projeto e queremos incluir `tags` e `responses`. + +Podemos declarar tudo isso sem precisar modificar o `APIRouter` original passando esses parâmetros para `app.include_router()`: + +```Python hl_lines="14-17" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Dessa forma, o `APIRouter` original permanecerá inalterado, para que possamos compartilhar o mesmo arquivo `app/internal/admin.py` com outros projetos na organização. + +O resultado é que em nosso aplicativo, cada uma das *operações de rota* do módulo `admin` terá: + +* O prefixo `/admin`. +* A tag `admin`. +* A dependência `get_token_header`. +* A resposta `418`. 🍵 + +Mas isso afetará apenas o `APIRouter` em nosso aplicativo, e não em nenhum outro código que o utilize. + +Assim, por exemplo, outros projetos poderiam usar o mesmo `APIRouter` com um método de autenticação diferente. + +### Incluir uma *operação de rota* + +Também podemos adicionar *operações de rota* diretamente ao aplicativo `FastAPI`. + +Aqui fazemos isso... só para mostrar que podemos 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. + +/// info | "Detalhes Técnicos" + +**Observação**: este é um detalhe muito técnico que você provavelmente pode **simplesmente pular**. + +--- + +Os `APIRouter`s não são "montados", eles não são isolados do resto do aplicativo. + +Isso ocorre porque queremos incluir suas *operações de rota* no esquema OpenAPI e nas interfaces de usuário. + +Como não podemos simplesmente isolá-los e "montá-los" independentemente do resto, as *operações de rota* são "clonadas" (recriadas), não incluídas diretamente. + +/// + +## Verifique a documentação automática da API + +Agora, execute `uvicorn`, usando o módulo `app.main` e a variável `app`: + +<div class="termy"> + +```console +$ uvicorn app.main:app --reload + +<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +</div> + +E abra os documentos em <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Você verá a documentação automática da API, incluindo os caminhos de todos os submódulos, usando os caminhos (e prefixos) corretos e as tags corretas: + +<img src="/img/tutorial/bigger-applications/image01.png"> + +## Incluir o mesmo roteador várias vezes com `prefixos` diferentes + +Você também pode usar `.include_router()` várias vezes com o *mesmo* roteador usando prefixos diferentes. + +Isso pode ser útil, por exemplo, para expor a mesma API sob prefixos diferentes, por exemplo, `/api/v1` e `/api/latest`. + +Esse é um uso avançado que você pode não precisar, mas está lá caso precise. + +## Incluir um `APIRouter` em outro + +Da mesma forma que você pode incluir um `APIRouter` em um aplicativo `FastAPI`, você pode incluir um `APIRouter` em outro `APIRouter` usando: + +```Python +router.include_router(other_router) +``` + +Certifique-se de fazer isso antes de incluir `router` no aplicativo `FastAPI`, para que as *operações de rota* de `other_router` também sejam incluídas. From 84d69bb69aa0ca320f108dcfcfdef63f334d54d2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 15:41:45 +0000 Subject: [PATCH 726/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 51dc34986..698825493 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/bigger-applications.md`. PR [#11971](https://github.com/fastapi/fastapi/pull/11971) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-websockets.md`. PR [#11994](https://github.com/fastapi/fastapi/pull/11994) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). From 5fd9ab97509ac7910caea3b704f4b4ad8086b5d3 Mon Sep 17 00:00:00 2001 From: Ben Beasley <code@musicinmybrain.net> Date: Thu, 15 Aug 2024 11:51:33 -0400 Subject: [PATCH 727/846] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Allow=20Starlette?= =?UTF-8?q?=200.38.x,=20update=20the=20pin=20to=20`>=3D0.37.2,<0.39.0`=20(?= =?UTF-8?q?#11876)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg <svlandeg@github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index c34838b83..7a8e061cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.37.2,<0.38.0", + "starlette>=0.37.2,<0.39.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From fc9107843eb26599a1f64220978f5dac2e09ab25 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 15:51:59 +0000 Subject: [PATCH 728/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 698825493..d8e7c2e20 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Allow Starlette 0.38.x, update the pin to `>=0.37.2,<0.39.0`. PR [#11876](https://github.com/fastapi/fastapi/pull/11876) by [@musicinmybrain](https://github.com/musicinmybrain). + ### Docs * 📝 Update docs section about "Don't Translate these Pages". PR [#12022](https://github.com/fastapi/fastapi/pull/12022) by [@tiangolo](https://github.com/tiangolo). From 2c9801720020b3f21295414b65d25836370100fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 15 Aug 2024 13:38:43 -0500 Subject: [PATCH 729/846] =?UTF-8?q?=F0=9F=91=B7=20Do=20not=20sync=20labels?= =?UTF-8?q?=20as=20it=20overrides=20manually=20added=20labels=20(#12024)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/labeler.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index d62f1668d..c3bb83f9a 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -17,8 +17,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/labeler@v5 - with: - sync-labels: true # Run this after labeler applied labels check-labels: needs: From 2f5ed4f2d1433f09b82868c2002158bf87897cc0 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 18:39:22 +0000 Subject: [PATCH 730/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d8e7c2e20..1311be390 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). * 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). From 0d92b42ff08a90bc180784acb6dd8d1f7681c951 Mon Sep 17 00:00:00 2001 From: Pierre V-F <74793957+Pierre-VF@users.noreply.github.com> Date: Thu, 15 Aug 2024 20:50:31 +0200 Subject: [PATCH 731/846] =?UTF-8?q?=F0=9F=94=A7=20Add=20changelog=20URL=20?= =?UTF-8?q?to=20`pyproject.toml`,=20shows=20in=20PyPI=20(#11152)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 7a8e061cc..dc04fcdfe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,6 +50,8 @@ dependencies = [ Homepage = "https://github.com/fastapi/fastapi" Documentation = "https://fastapi.tiangolo.com/" Repository = "https://github.com/fastapi/fastapi" +Issues = "https://github.com/fastapi/fastapi/issues" +Changelog = "https://fastapi.tiangolo.com/release-notes/" [project.optional-dependencies] From b7c80cbca2f27758ee90281b3417f76bdce60242 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 18:51:01 +0000 Subject: [PATCH 732/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1311be390..dc81963cf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 🔧 Add changelog URL to `pyproject.toml`, shows in PyPI. PR [#11152](https://github.com/fastapi/fastapi/pull/11152) by [@Pierre-VF](https://github.com/Pierre-VF). * 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). From 285a54cfbd4a469e4cac72ed053f850d4cdbbd4a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 15 Aug 2024 15:56:19 -0500 Subject: [PATCH 733/846] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.8.14=20to=201.9.0=20(#11727)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.14 to 1.9.0. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.14...v1.9.0) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e7c69befc..591df634b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.14 + uses: pypa/gh-action-pypi-publish@v1.9.0 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 94be8ff3417f47d11389e9ab1d759f026db6a07e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 20:58:06 +0000 Subject: [PATCH 734/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index dc81963cf..b58e60203 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.14 to 1.9.0. PR [#11727](https://github.com/fastapi/fastapi/pull/11727) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add changelog URL to `pyproject.toml`, shows in PyPI. PR [#11152](https://github.com/fastapi/fastapi/pull/11152) by [@Pierre-VF](https://github.com/Pierre-VF). * 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). From 4f937c0c4afbd0b46cf2db91acac6814504bbdcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Thu, 15 Aug 2024 16:00:47 -0500 Subject: [PATCH 735/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b58e60203..7245d072a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.112.1 + ### Upgrades * ⬆️ Allow Starlette 0.38.x, update the pin to `>=0.37.2,<0.39.0`. PR [#11876](https://github.com/fastapi/fastapi/pull/11876) by [@musicinmybrain](https://github.com/musicinmybrain). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 3413dffc8..0b79d45ef 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.112.0" +__version__ = "0.112.1" from starlette import status as status From 86c8f4fc2b1d9157be7bf78535a336d69049fbc5 Mon Sep 17 00:00:00 2001 From: Cedric L'homme <public@l-homme.com> Date: Thu, 15 Aug 2024 23:29:58 +0200 Subject: [PATCH 736/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20`docs/en/docs/t?= =?UTF-8?q?utorial/body.md`=20with=20Python=203.10=20union=20type=20exampl?= =?UTF-8?q?e=20(#11415)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg <svlandeg@github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/en/docs/tutorial/body.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index f3a8685c6..44d2d7da6 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -237,7 +237,9 @@ The function parameters will be recognized as follows: FastAPI will know that the value of `q` is not required because of the default value `= None`. -The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors. +The `str | None` (Python 3.10+) or `Union` in `Union[str, None]` (Python 3.8+) is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`. + +But adding the type annotations will allow your editor to give you better support and detect errors. /// From 366bdebd9eea7018660957271da40dfd5959537d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 21:30:26 +0000 Subject: [PATCH 737/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7245d072a..be8682f48 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). + ## 0.112.1 ### Upgrades From 2cb1333b971ae17b83499bca952a7803cec21b0c Mon Sep 17 00:00:00 2001 From: Luke Okomilo <github@email.okomilo.com> Date: Thu, 15 Aug 2024 23:31:16 +0100 Subject: [PATCH 738/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20inconsistent=20res?= =?UTF-8?q?ponse=20code=20when=20item=20already=20exists=20in=20docs=20for?= =?UTF-8?q?=20testing=20(#11818)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs_src/app_testing/app_b_an/main.py | 2 +- docs_src/app_testing/app_b_an/test_main.py | 2 +- docs_src/app_testing/app_b_an_py310/main.py | 2 +- docs_src/app_testing/app_b_an_py310/test_main.py | 2 +- docs_src/app_testing/app_b_an_py39/main.py | 2 +- docs_src/app_testing/app_b_an_py39/test_main.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs_src/app_testing/app_b_an/main.py b/docs_src/app_testing/app_b_an/main.py index c63134fc9..c66278fdd 100644 --- a/docs_src/app_testing/app_b_an/main.py +++ b/docs_src/app_testing/app_b_an/main.py @@ -34,6 +34,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an/test_main.py +++ b/docs_src/app_testing/app_b_an/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py310/main.py b/docs_src/app_testing/app_b_an_py310/main.py index 48c27a0b8..c5952be0b 100644 --- a/docs_src/app_testing/app_b_an_py310/main.py +++ b/docs_src/app_testing/app_b_an_py310/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py310/test_main.py b/docs_src/app_testing/app_b_an_py310/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py310/test_main.py +++ b/docs_src/app_testing/app_b_an_py310/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py39/main.py b/docs_src/app_testing/app_b_an_py39/main.py index 935a510b7..142e23a26 100644 --- a/docs_src/app_testing/app_b_an_py39/main.py +++ b/docs_src/app_testing/app_b_an_py39/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py39/test_main.py +++ b/docs_src/app_testing/app_b_an_py39/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} From 4636c621a957ddfb927e3a1dd49fee521ee7f5d5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 22:31:36 +0000 Subject: [PATCH 739/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index be8682f48..decd54c99 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). ## 0.112.1 From 265dbeb6635864e527cfd4c7376f0b32bc2301c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jun-Ah=20=EC=A4=80=EC=95=84?= <junah.dev@gmail.com> Date: Fri, 16 Aug 2024 07:38:02 +0900 Subject: [PATCH 740/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20missing=20`compres?= =?UTF-8?q?slevel`=20parameter=20on=20docs=20for=20`GZipMiddleware`=20(#11?= =?UTF-8?q?350)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/en/docs/advanced/middleware.md | 1 + docs_src/advanced_middleware/tutorial003.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 4b273fd89..57e476167 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -88,6 +88,7 @@ The middleware will handle both standard and streaming responses. The following arguments are supported: * `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`. +* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes. ## Other middlewares diff --git a/docs_src/advanced_middleware/tutorial003.py b/docs_src/advanced_middleware/tutorial003.py index b99e3edd1..e2c87e67d 100644 --- a/docs_src/advanced_middleware/tutorial003.py +++ b/docs_src/advanced_middleware/tutorial003.py @@ -3,7 +3,7 @@ from fastapi.middleware.gzip import GZipMiddleware app = FastAPI() -app.add_middleware(GZipMiddleware, minimum_size=1000) +app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5) @app.get("/") From 3c8d0abc87579fdcd7bf1a9045b62d363fed0077 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 22:38:22 +0000 Subject: [PATCH 741/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index decd54c99..3bee16617 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201). * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). From 8809b3685f2778b9b4b1f3edb44523cee36fdccf Mon Sep 17 00:00:00 2001 From: Nils Lindemann <nilslindemann@tutanota.com> Date: Fri, 16 Aug 2024 01:30:12 +0200 Subject: [PATCH 742/846] =?UTF-8?q?=F0=9F=93=9D=20Several=20docs=20improve?= =?UTF-8?q?ments,=20tweaks,=20and=20clarifications=20(#11390)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg <svlandeg@github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/de/docs/features.md | 2 +- docs/en/docs/advanced/additional-responses.md | 2 +- docs/en/docs/advanced/behind-a-proxy.md | 2 +- docs/en/docs/advanced/custom-response.md | 4 ++-- docs/en/docs/advanced/openapi-callbacks.md | 2 +- docs/en/docs/advanced/response-directly.md | 2 +- docs/en/docs/advanced/security/oauth2-scopes.md | 2 +- docs/en/docs/advanced/settings.md | 4 ++-- docs/en/docs/features.md | 2 +- docs/en/docs/help-fastapi.md | 2 +- docs/en/docs/python-types.md | 2 +- docs/en/docs/tutorial/background-tasks.md | 2 +- docs/en/docs/tutorial/body-nested-models.md | 2 +- docs/en/docs/tutorial/body.md | 2 +- docs/en/docs/tutorial/cookie-params.md | 2 +- docs/en/docs/tutorial/cors.md | 6 +++--- .../dependencies/dependencies-with-yield.md | 2 +- docs/en/docs/tutorial/extra-data-types.md | 2 +- docs/en/docs/tutorial/extra-models.md | 6 +++--- docs/en/docs/tutorial/header-params.md | 2 +- .../docs/tutorial/query-params-str-validations.md | 14 +++++++------- docs/en/docs/tutorial/request-files.md | 2 +- docs/en/docs/tutorial/response-model.md | 10 +++++----- docs/en/docs/tutorial/schema-extra-example.md | 2 +- 24 files changed, 40 insertions(+), 40 deletions(-) diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index b268604fa..8fdf42622 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -6,7 +6,7 @@ ### Basiert auf offenen Standards -* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> für die Erstellung von APIs, inklusive Deklarationen von <abbr title="auch genannt Endpunkte, Routen">Pfad</abbr>-<abbr title="gemeint sind HTTP-Methoden wie POST, GET, PUT, DELETE">Operationen</abbr>, Parametern, Body-Anfragen, Sicherheit, usw. +* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> für die Erstellung von APIs, inklusive Deklarationen von <abbr title="auch genannt Endpunkte, Routen">Pfad</abbr>-<abbr title="gemeint sind HTTP-Methoden wie POST, GET, PUT, DELETE">Operationen</abbr>, Parametern, Requestbodys, Sicherheit, usw. * Automatische Dokumentation der Datenmodelle mit <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (da OpenAPI selbst auf JSON Schema basiert). * Um diese Standards herum entworfen, nach sorgfältigem Studium. Statt einer nachträglichen Schicht darüber. * Dies ermöglicht auch automatische **Client-Code-Generierung** in vielen Sprachen. diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 95ca90f6b..07d99df5f 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -40,7 +40,7 @@ Keep in mind that you have to return the `JSONResponse` directly. The `model` key is not part of OpenAPI. -**FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. +**FastAPI** will take the Pydantic model from there, generate the JSON Schema, and put it in the correct place. The correct place is: diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 0447a7220..5ff64016c 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -211,7 +211,7 @@ Now create that other file `routes.toml`: This file configures Traefik to use the path prefix `/api/v1`. -And then it will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. +And then Traefik will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. Now start Traefik: diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index f31127efe..8a6555dba 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -255,11 +255,11 @@ This includes many libraries to interact with cloud storage, video processing, a 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. 2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response. -3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function. +3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function (`iterfile`). So, it is a generator function that transfers the "generating" work to something else internally. - By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing. + By doing it this way, we can put it in a `with` block, and that way, ensure that the file-like object is closed after finishing. /// tip diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index e74af3d3e..7fead2ed9 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -37,7 +37,7 @@ This part is pretty normal, most of the code is probably already familiar to you /// tip -The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">URL</a> type. +The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/api/networks/" class="external-link" target="_blank">Url</a> type. /// diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 33e10d091..73071ed1b 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -54,7 +54,7 @@ Now, let's see how you could use that to return a custom response. Let's say that you want to return an <a href="https://en.wikipedia.org/wiki/XML" class="external-link" target="_blank">XML</a> response. -You could put your XML content in a string, put it in a `Response`, and return it: +You could put your XML content in a string, put that in a `Response`, and return it: ```Python hl_lines="1 18" {!../../../docs_src/response_directly/tutorial002.py!} diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 69b8fa7d2..48798ebac 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -725,7 +725,7 @@ Here's how the hierarchy of dependencies and scopes looks like: * This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so: * `security_scopes.scopes` will contain `["me", "items"]` for the *path operation* `read_own_items`. * `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`. - * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either. + * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scopes` either. /// tip diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index b77557361..b78f83953 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -138,7 +138,7 @@ That means that any value read in Python from an environment variable will be a ## Pydantic `Settings` -Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>. +Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>. ### Install `pydantic-settings` @@ -411,7 +411,7 @@ And then update your `config.py` with: /// tip -The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>. +The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/concepts/config/" class="external-link" target="_blank">Pydantic: Concepts: Configuration</a>. /// diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 1a871a22b..9c38a4bd2 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -6,7 +6,7 @@ ### Based on open standards -* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> for API creation, including declarations of <abbr title="also known as: endpoints, routes">path</abbr> <abbr title="also known as HTTP methods, as POST, GET, PUT, DELETE">operations</abbr>, parameters, body requests, security, etc. +* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> for API creation, including declarations of <abbr title="also known as: endpoints, routes">path</abbr> <abbr title="also known as HTTP methods, as POST, GET, PUT, DELETE">operations</abbr>, parameters, request bodies, security, etc. * Automatic data model documentation with <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (as OpenAPI itself is based on JSON Schema). * Designed around these standards, after a meticulous study. Instead of an afterthought layer on top. * This also allows using automatic **client code generation** in many languages. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index cd367dd6b..81151032f 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -66,7 +66,7 @@ I love to hear about how **FastAPI** is being used, what you have liked in it, i ## Vote for FastAPI * <a href="https://www.slant.co/options/34241/~fastapi-review" class="external-link" target="_blank">Vote for **FastAPI** in Slant</a>. -* <a href="https://alternativeto.net/software/fastapi/" class="external-link" target="_blank">Vote for **FastAPI** in AlternativeTo</a>. +* <a href="https://alternativeto.net/software/fastapi/about/" class="external-link" target="_blank">Vote for **FastAPI** in AlternativeTo</a>. * <a href="https://stackshare.io/pypi-fastapi" class="external-link" target="_blank">Say you use **FastAPI** on StackShare</a>. ## Help others with questions in GitHub diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 900ede22c..4ed1fc680 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -519,7 +519,7 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t /// tip -Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. +Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required Optional fields</a>. /// diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 5370b9ba8..8b4476e41 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -9,7 +9,7 @@ This includes, for example: * Email notifications sent after performing an action: * As connecting to an email server and sending an email tends to be "slow" (several seconds), you can return the response right away and send the email notification in the background. * Processing data: - * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process it in the background. + * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process the file in the background. ## Using `BackgroundTasks` diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index f823a9033..d2bda5979 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -220,7 +220,7 @@ Again, doing just that declaration, with **FastAPI** you get: Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`. -To see all the options you have, checkout the docs for <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic's exotic types</a>. You will see some examples in the next chapter. +To see all the options you have, checkout <a href="https://docs.pydantic.dev/latest/concepts/types/" class="external-link" target="_blank">Pydantic's Type Overview</a>. You will see some examples in the next chapter. For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`: diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 44d2d7da6..608b50dbb 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -4,7 +4,7 @@ When you need to send data from a client (let's say, a browser) to your API, you A **request** body is data sent by the client to your API. A **response** body is the data your API sends to the client. -Your API almost always has to send a **response** body. But clients don't necessarily need to send **request** bodies all the time. +Your API almost always has to send a **response** body. But clients don't necessarily need to send **request bodies** all the time, sometimes they only request a path, maybe with some query parameters, but don't send a body. To declare a **request** body, you use <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> models with all their power and benefits. diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 6196b34d0..0214a9c38 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -62,7 +62,7 @@ Prefer to use the `Annotated` version if possible. Then declare the cookie parameters using the same structure as with `Path` and `Query`. -The first value is the default value, you can pass all the extra validation or annotation parameters: +You can define the default value as well as all the extra validation or annotation parameters: //// tab | Python 3.10+ diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 665249ffa..fd329e138 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -18,11 +18,11 @@ Even if they are all in `localhost`, they use different protocols or ports, so, So, let's say you have a frontend running in your browser at `http://localhost:8080`, and its JavaScript is trying to communicate with a backend running at `http://localhost` (because we don't specify a port, the browser will assume the default port `80`). -Then, the browser will send an HTTP `OPTIONS` request to the backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the browser will let the JavaScript in the frontend send its request to the backend. +Then, the browser will send an HTTP `OPTIONS` request to the `:80`-backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the `:8080`-browser will let the JavaScript in the frontend send its request to the `:80`-backend. -To achieve this, the backend must have a list of "allowed origins". +To achieve this, the `:80`-backend must have a list of "allowed origins". -In this case, it would have to include `http://localhost:8080` for the frontend to work correctly. +In this case, the list would have to include `http://localhost:8080` for the `:8080`-frontend to work correctly. ## Wildcards diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 279fc4d1e..2a3ac2237 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -6,7 +6,7 @@ To do this, use `yield` instead of `return`, and write the extra steps (code) af /// tip -Make sure to use `yield` one single time. +Make sure to use `yield` one single time per dependency. /// diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index aed9f7880..849dee41f 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ Here are some of the additional data types you can use: * `datetime.timedelta`: * A Python `datetime.timedelta`. * In requests and responses will be represented as a `float` of total seconds. - * Pydantic also allows representing it as a "ISO 8601 time diff encoding", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">see the docs for more info</a>. + * Pydantic also allows representing it as a "ISO 8601 time diff encoding", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers" class="external-link" target="_blank">see the docs for more info</a>. * `frozenset`: * In requests and responses, treated the same as a `set`: * In requests, a list will be read, eliminating duplicates and converting it to a `set`. diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 982f59782..1c87e76ce 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -156,7 +156,7 @@ UserInDB( /// warning -The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security. +The supporting additional functions `fake_password_hasher` and `fake_save_user` are just to demo a possible flow of the data, but they of course are not providing any real security. /// @@ -194,7 +194,7 @@ That way, we can declare just the differences between the models (with plaintext ## `Union` or `anyOf` -You can declare a response to be the `Union` of two types, that means, that the response would be any of the two. +You can declare a response to be the `Union` of two or more types, that means, that the response would be any of them. It will be defined in OpenAPI with `anyOf`. @@ -234,7 +234,7 @@ If it was in a type annotation we could have used the vertical bar, as: some_variable: PlaneItem | CarItem ``` -But if we put that in `response_model=PlaneItem | CarItem` we would get an error, because Python would try to perform an **invalid operation** between `PlaneItem` and `CarItem` instead of interpreting that as a type annotation. +But if we put that in the assignment `response_model=PlaneItem | CarItem` we would get an error, because Python would try to perform an **invalid operation** between `PlaneItem` and `CarItem` instead of interpreting that as a type annotation. ## List of models diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index cc5975b85..2e07fe0e6 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -62,7 +62,7 @@ Prefer to use the `Annotated` version if possible. Then declare the header parameters using the same structure as with `Path`, `Query` and `Cookie`. -The first value is the default value, you can pass all the extra validation or annotation parameters: +You can define the default value as well as all the extra validation or annotation parameters: //// tab | Python 3.10+ diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index ce7d0580d..859242d93 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -155,7 +155,7 @@ FastAPI will now: * Show a **clear error** for the client when the data is not valid * **Document** the parameter in the OpenAPI schema *path operation* (so it will show up in the **automatic docs UI**) -## Alternative (old) `Query` as the default value +## Alternative (old): `Query` as the default value Previous versions of FastAPI (before <abbr title="before 2023-03">0.95.0</abbr>) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you. @@ -209,7 +209,7 @@ q: str | None = Query(default=None) q: str | None = None ``` -But it declares it explicitly as being a query parameter. +But the `Query` versions declare it explicitly as being a query parameter. /// info @@ -457,7 +457,7 @@ Having a default value of any type, including `None`, makes the parameter option /// -## Make it required +## Required parameters When we don't need to declare more validations or metadata, we can make the `q` query parameter required just by not declaring a default value, like: @@ -573,7 +573,7 @@ It is used by Pydantic and FastAPI to explicitly declare that a value is require This will let **FastAPI** know that this parameter is required. -### Required with `None` +### Required, can be `None` You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`. @@ -633,7 +633,7 @@ Prefer to use the `Annotated` version if possible. /// tip -Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>. +Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/2.3/usage/models/#required-optional-fields" class="external-link" target="_blank">Required fields</a>. /// @@ -809,7 +809,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: } ``` -#### Using `list` +#### Using just `list` You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): @@ -1107,7 +1107,7 @@ The docs will show it like this: <img src="/img/tutorial/query-params-str-validations/image01.png"> -## Exclude from OpenAPI +## Exclude parameters from OpenAPI To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`: diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index ceaea3626..53d9eefde 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -152,7 +152,7 @@ Using `UploadFile` has several advantages over `bytes`: * `filename`: A `str` with the original file name that was uploaded (e.g. `myimage.jpg`). * `content_type`: A `str` with the content type (MIME type / media type) (e.g. `image/jpeg`). -* `file`: A <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> (a <a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a> object). This is the actual Python file that you can pass directly to other functions or libraries that expect a "file-like" object. +* `file`: A <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> (a <a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a> object). This is the actual Python file object that you can pass directly to other functions or libraries that expect a "file-like" object. `UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`). diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 8a2dccc81..991deca12 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -236,9 +236,9 @@ That's why in this example we have to declare it in the `response_model` paramet ## Return Type and Data Filtering -Let's continue from the previous example. We wanted to **annotate the function with one type** but return something that includes **more data**. +Let's continue from the previous example. We wanted to **annotate the function with one type**, but we wanted to be able to return from the function something that actually includes **more data**. -We want FastAPI to keep **filtering** the data using the response model. +We want FastAPI to keep **filtering** the data using the response model. So that even though the function returns more data, the response will only include the fields declared in the response model. In the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type. @@ -306,7 +306,7 @@ The most common case would be [returning a Response directly as explained later {!> ../../../docs_src/response_model/tutorial003_02.py!} ``` -This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass) of `Response`. +This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`. And tools will also be happy because both `RedirectResponse` and `JSONResponse` are subclasses of `Response`, so the type annotation is correct. @@ -455,7 +455,7 @@ The examples here use `.dict()` for compatibility with Pydantic v1, but you shou /// info -FastAPI uses Pydantic model's `.dict()` with <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this. +FastAPI uses Pydantic model's `.dict()` with <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this. /// @@ -466,7 +466,7 @@ You can also use: * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` -as described in <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`. +as described in <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`. /// diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 141a0bc55..70745b048 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -44,7 +44,7 @@ That extra info will be added as-is to the output **JSON Schema** for that model //// tab | Pydantic v2 -In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic's docs: Model Config</a>. +In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic's docs: Configuration</a>. You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. From 470f1ae57dfef889ce8ec8ad29887f3022df6cf1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 15 Aug 2024 23:30:36 +0000 Subject: [PATCH 743/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3bee16617..1d610e078 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201). * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). From a0c529ef0a87517eb6accec1000ccfd52761905d Mon Sep 17 00:00:00 2001 From: Micael Jarniac <micael@jarniac.com> Date: Thu, 15 Aug 2024 21:04:55 -0300 Subject: [PATCH 744/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20minor=20typo=20(#1?= =?UTF-8?q?2026)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/security/oauth2-scopes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 48798ebac..ff52d7bb8 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -398,7 +398,7 @@ Now update the dependency `get_current_user`. This is the one used by the dependencies above. -Here's were we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. +Here's where we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. Because this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes. From e8f7bf0ad5e6a3fefa13face9ee9864b255b8ee5 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 00:05:21 +0000 Subject: [PATCH 745/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1d610e078..2442259fd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201). * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). From 0aaaed581e59a95ab4ce6d18c26d6881c0782990 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C5=82awomir=20Ehlert?= <slafs.e@gmail.com> Date: Fri, 16 Aug 2024 03:57:38 +0200 Subject: [PATCH 746/846] =?UTF-8?q?=E2=9A=99=EF=B8=8F=20Record=20and=20sho?= =?UTF-8?q?w=20test=20coverage=20contexts=20(what=20test=20covers=20which?= =?UTF-8?q?=20line)=20(#11518)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- pyproject.toml | 1 + scripts/test-cov-html.sh | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index dc04fcdfe..982ae3ed1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -184,6 +184,7 @@ source = [ "fastapi" ] context = '${CONTEXT}' +dynamic_context = "test_function" omit = [ "docs_src/response_model/tutorial003_04.py", "docs_src/response_model/tutorial003_04_py310.py", diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh index d1bdfced2..85aef9601 100755 --- a/scripts/test-cov-html.sh +++ b/scripts/test-cov-html.sh @@ -6,4 +6,4 @@ set -x bash scripts/test.sh ${@} coverage combine coverage report --show-missing -coverage html +coverage html --show-contexts From a51a98b07e69e801dda445d76ac48093661044d7 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 01:58:02 +0000 Subject: [PATCH 747/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2442259fd..e6ef19ed3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,10 @@ hide: * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). +### Internal + +* ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). + ## 0.112.1 ### Upgrades From 10eee5c3b37440d8c1b3684df4676722f8c8d0fe Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 15 Aug 2024 21:04:50 -0500 Subject: [PATCH 748/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20`docs/es/docs/project-generation.md`=20(#11947)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/en/docs/project-generation.md | 1 + docs/es/docs/project-generation.md | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 docs/es/docs/project-generation.md diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md index d142862ee..61459ba53 100644 --- a/docs/en/docs/project-generation.md +++ b/docs/en/docs/project-generation.md @@ -16,6 +16,7 @@ GitHub Repository: <a href="https://github.com/tiangolo/full-stack-fastapi-templ - 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack. - 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components. - 🤖 An automatically generated frontend client. + - 🧪 Playwright for End-to-End testing. - 🦇 Dark mode support. - 🐋 [Docker Compose](https://www.docker.com) for development and production. - 🔒 Secure password hashing by default. diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md new file mode 100644 index 000000000..63febf1ae --- /dev/null +++ b/docs/es/docs/project-generation.md @@ -0,0 +1,28 @@ +# Plantilla de FastAPI Full Stack + +Las plantillas, aunque típicamente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, lo que las convierte en un excelente punto de partida. 🏁 + +Puedes utilizar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya realizados. + +Repositorio en GitHub: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template) + +## Plantilla de FastAPI Full Stack - Tecnología y Características + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para el backend API en Python. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con la base de datos SQL en Python (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y la gestión de configuraciones. + - 💾 [PostgreSQL](https://www.postgresql.org) como la base de datos SQL. +- 🚀 [React](https://react.dev) para el frontend. + - 💃 Usando TypeScript, hooks, Vite y otras partes de un stack de frontend moderno. + - 🎨 [Chakra UI](https://chakra-ui.com) para los componentes del frontend. + - 🤖 Un cliente frontend generado automáticamente. + - 🧪 Playwright para pruebas End-to-End. + - 🦇 Soporte para modo oscuro. +- 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción. +- 🔒 Hashing seguro de contraseñas por defecto. +- 🔑 Autenticación con token JWT. +- 📫 Recuperación de contraseñas basada en email. +- ✅ Tests con [Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) como proxy inverso / balanceador de carga. +- 🚢 Instrucciones de despliegue utilizando Docker Compose, incluyendo cómo configurar un proxy frontend Traefik para manejar certificados HTTPS automáticos. +- 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions. From a3f42718de8a6da2e89d476df92e6e81d7eb24e1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 02:05:14 +0000 Subject: [PATCH 749/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e6ef19ed3..584ca4354 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev). * 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201). From c81f575d0d379273e5b1d515ea4c61246cf976d6 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar <jiri.kuncar@gmail.com> Date: Fri, 16 Aug 2024 18:50:01 +0200 Subject: [PATCH 750/846] =?UTF-8?q?=F0=9F=94=A8=20Specify=20`email-validat?= =?UTF-8?q?or`=20dependency=20with=20dash=20(#11515)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg <svlandeg@github.com> --- README.md | 2 +- docs/az/docs/index.md | 2 +- docs/bn/docs/index.md | 2 +- docs/de/docs/index.md | 2 +- docs/de/docs/tutorial/response-model.md | 2 +- docs/em/docs/index.md | 2 +- docs/em/docs/tutorial/response-model.md | 2 +- docs/en/docs/index.md | 2 +- docs/en/docs/tutorial/response-model.md | 2 +- docs/es/docs/index.md | 2 +- docs/fa/docs/index.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/ko/docs/index.md | 2 +- docs/pl/docs/index.md | 2 +- docs/pt/docs/index.md | 2 +- docs/ru/docs/index.md | 2 +- docs/ru/docs/tutorial/response-model.md | 2 +- docs/tr/docs/index.md | 2 +- docs/uk/docs/index.md | 2 +- docs/vi/docs/index.md | 2 +- docs/yo/docs/index.md | 2 +- docs/zh-hant/docs/index.md | 2 +- docs/zh/docs/index.md | 2 +- pyproject.toml | 4 ++-- 28 files changed, 29 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index aa70ff2da..b00ef6ba9 100644 --- a/README.md +++ b/README.md @@ -462,7 +462,7 @@ When you install FastAPI with `pip install "fastapi[standard]"` it comes the `st Used by Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - for email validation. Used by Starlette: diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index 90864a98e..b5d7f8f92 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -442,7 +442,7 @@ Müstəqil TechEmpower meyarları göstərir ki, Uvicorn üzərində işləyən Pydantic tərəfindən istifadə olunanlar: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - e-poçtun yoxlanılması üçün. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - e-poçtun yoxlanılması üçün. * <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - parametrlərin idarə edilməsi üçün. * <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - Pydantic ilə istifadə edilə bilən əlavə tiplər üçün. diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 042cf9399..c882506ff 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -439,7 +439,7 @@ item: Item Pydantic দ্বারা ব্যবহৃত: -- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - ইমেল যাচাইকরণের জন্য। +- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - ইমেল যাচাইকরণের জন্য। স্টারলেট দ্বারা ব্যবহৃত: diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index 3789c5998..af024d18d 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -449,7 +449,7 @@ Um mehr darüber zu erfahren, siehe den Abschnitt <a href="https://fastapi.tiang Wird von Pydantic verwendet: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - für E-Mail-Validierung. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - für E-Mail-Validierung. * <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - für die Verwaltung von Einstellungen. * <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - für zusätzliche Typen, mit Pydantic zu verwenden. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index 3f632b1cb..b480780bc 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passw /// info -Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>. Z. B. `pip install email-validator` oder `pip install pydantic[email]`. diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index dc8c4f023..aa7542366 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -451,7 +451,7 @@ item: Item ⚙️ Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - 📧 🔬. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 📧 🔬. ⚙️ 💃: diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index caae47d14..9483508aa 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** /// info -⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>. 🤶 Ⓜ. `pip install email-validator` ⚖️ `pip install pydantic[email]`. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 4fe0cd6cc..d76ef498b 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -458,7 +458,7 @@ When you install FastAPI with `pip install "fastapi[standard]"` it comes the `st Used by Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - for email validation. Used by Starlette: diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 991deca12..c17e32f90 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: /// info -To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>. E.g. `pip install email-validator` or `pip install pydantic[email]`. diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 2b6a2f0be..fe4912253 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -437,7 +437,7 @@ Para entender más al respecto revisa la sección <a href="https://fastapi.tiang Usadas por Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - para validación de emails. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - para validación de emails. Usados por Starlette: diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index bc8b77941..1ae566a9f 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -442,7 +442,7 @@ item: Item استفاده شده توسط Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - برای اعتبارسنجی آدرسهای ایمیل. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - برای اعتبارسنجی آدرسهای ایمیل. استفاده شده توسط Starlette: diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 927c0c643..dccefdd5a 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -449,7 +449,7 @@ Pour en savoir plus, consultez la section <a href="https://fastapi.tiangolo.com/ Utilisées par Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - pour la validation des adresses email. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - pour la validation des adresses email. Utilisées par Starlette : diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 3af166ab0..23a2eb824 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -446,7 +446,7 @@ item: Item בשימוש Pydantic: -- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - לאימות כתובות אימייל. +- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - לאימות כתובות אימייל. בשימוש Starlette: diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index e605bbb55..8e326a78b 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -443,7 +443,7 @@ Ezeknek a további megértéséhez: <a href="https://fastapi.tiangolo.com/benchm Pydantic által használt: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - e-mail validációkra. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - e-mail validációkra. * <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - Beállítások követésére. * <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - Extra típusok Pydantic-hoz. diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 272f9a37e..57940f0ed 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -437,7 +437,7 @@ Per approfondire, consulta la sezione <a href="https://fastapi.tiangolo.com/benc Usate da Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - per la validazione di email. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - per la validazione di email. Usate da Starlette: diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index c066c5070..72a0e98bc 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -435,7 +435,7 @@ item: Item Pydantic によって使用されるもの: -- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - E メールの検証 +- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - E メールの検証 Starlette によって使用されるもの: diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 620fcc881..8b00d90bc 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -441,7 +441,7 @@ item: Item Pydantic이 사용하는: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - 이메일 유효성 검사. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 이메일 유효성 검사. Starlette이 사용하는: diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index efa9abfc3..e591e1c9d 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -439,7 +439,7 @@ Aby dowiedzieć się o tym więcej, zobacz sekcję <a href="https://fastapi.tian Używane przez Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - dla walidacji adresów email. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - dla walidacji adresów email. Używane przez Starlette: diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index bdaafdefc..f99144617 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -434,7 +434,7 @@ Para entender mais sobre performance, veja a seção <a href="https://fastapi.ti Usados por Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - para validação de email. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - para validação de email. Usados por Starlette: diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 313e980d8..3aa4d82d0 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -443,7 +443,7 @@ item: Item Используется Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - для проверки электронной почты. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - для проверки электронной почты. Используется Starlette: diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 38d185b98..f8c910fe9 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ FastAPI будет использовать значение `response_model` д /// info | "Информация" -Чтобы использовать `EmailStr`, прежде необходимо установить <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>. +Чтобы использовать `EmailStr`, прежде необходимо установить <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>. Используйте `pip install email-validator` или `pip install pydantic[email]`. diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 7d96b4edc..7ecaf1ba3 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -449,7 +449,7 @@ Daha fazla bilgi için, bu bölüme bir göz at <a href="https://fastapi.tiangol Pydantic tarafında kullanılan: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - email doğrulaması için. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - email doğrulaması için. * <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - ayar yönetimi için. * <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - Pydantic ile birlikte kullanılabilecek ek tipler için. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index ffcb8fd13..4c8c54af2 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -437,7 +437,7 @@ item: Item Pydantic використовує: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - для валідації електронної пошти. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - для валідації електронної пошти. * <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - для управління налаштуваннями. * <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - для додаткових типів, що можуть бути використані з Pydantic. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 5fc1400fd..09deac6f2 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -452,7 +452,7 @@ Independent TechEmpower benchmarks cho thấy các ứng dụng **FastAPI** ch Sử dụng bởi Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - cho email validation. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - cho email validation. Sử dụng Starlette: diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index eb20adbb5..ee7f56220 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -449,7 +449,7 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn <a href="https://fastapi.tian Èyí tí Pydantic ń lò: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - fún ifọwọsi ímeèlì. +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - fún ifọwọsi ímeèlì. * <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - fún ètò ìsàkóso. * <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic. diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index c98a3098f..d260b5b79 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -443,7 +443,7 @@ item: Item 用於 Pydantic: -- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - 用於電子郵件驗證。 +- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 用於電子郵件驗證。 - <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - 用於設定管理。 - <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - 用於與 Pydantic 一起使用的額外型別。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index d1238fdd2..777240ec2 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -446,7 +446,7 @@ item: Item 用于 Pydantic: -* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - 用于 email 校验。 +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 用于 email 校验。 用于 Starlette: diff --git a/pyproject.toml b/pyproject.toml index 982ae3ed1..9e0611387 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,7 +64,7 @@ standard = [ # For forms and file uploads "python-multipart >=0.0.7", # To validate email fields - "email_validator >=2.0.0", + "email-validator >=2.0.0", # Uvicorn with uvloop "uvicorn[standard] >=0.12.0", # TODO: this should be part of some pydantic optional extra dependencies @@ -91,7 +91,7 @@ all = [ # For ORJSONResponse "orjson >=3.2.1", # To validate email fields - "email_validator >=2.0.0", + "email-validator >=2.0.0", # Uvicorn with uvloop "uvicorn[standard] >=0.12.0", # Settings management From 9f78e08c146b27c1c92f812e99c14b057ff9ea08 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 16:50:25 +0000 Subject: [PATCH 751/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 584ca4354..ab0024220 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). * 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev). * 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann). From fd5c00ab7609290638a80925c055a77eafad6879 Mon Sep 17 00:00:00 2001 From: VaitoSoi <duyduy15456@gmail.com> Date: Fri, 16 Aug 2024 23:51:25 +0700 Subject: [PATCH 752/846] =?UTF-8?q?=F0=9F=93=9D=20Edit=20the=20link=20to?= =?UTF-8?q?=20the=20OpenAPI=20"Responses=20Object"=20and=20"Response=20Obj?= =?UTF-8?q?ect"=20sections=20in=20the=20"Additional=20Responses=20in=20Ope?= =?UTF-8?q?nAPI"=20section=20(#11996)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg <svlandeg@github.com> --- docs/en/docs/advanced/additional-responses.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 07d99df5f..674f0672c 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -251,5 +251,5 @@ For example: To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification: -* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject" class="external-link" target="_blank">OpenAPI Responses Object</a>, it includes the `Response Object`. -* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject" class="external-link" target="_blank">OpenAPI Response Object</a>, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object" class="external-link" target="_blank">OpenAPI Responses Object</a>, it includes the `Response Object`. +* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object" class="external-link" target="_blank">OpenAPI Response Object</a>, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. From 46d0ffc0d712f7e09509d5742f0454ddfa03e8ad Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 16:52:46 +0000 Subject: [PATCH 753/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ab0024220..40103a3b0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). * 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). * 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev). * 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac). From f79247b4e581819c55afb761b5f6a702db03cc11 Mon Sep 17 00:00:00 2001 From: gitworkflows <118260833+gitworkflows@users.noreply.github.com> Date: Fri, 16 Aug 2024 22:56:19 +0600 Subject: [PATCH 754/846] =?UTF-8?q?=F0=9F=99=88=20Add=20.coverage*=20to=20?= =?UTF-8?q?`.gitignore`=20(#11940)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 9be494cec..ef6364a9a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ __pycache__ htmlcov dist site -.coverage +.coverage* coverage.xml .netlify test.db From 9a939dec47311fdd8d05c6ea57ed8d53578af1be Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 16:56:43 +0000 Subject: [PATCH 755/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 40103a3b0..951033e4a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). * ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). ## 0.112.1 From ff8fcd3b44626ab830f09a2c559530f1440cc844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 16 Aug 2024 12:29:21 -0500 Subject: [PATCH 756/846] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20griffe-t?= =?UTF-8?q?ypingdoc=20for=20the=20docs=20(#12029)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index a7ef7ef2e..ab2b0165b 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -12,7 +12,7 @@ pillow==10.3.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.25.1 -griffe-typingdoc==0.2.5 +griffe-typingdoc==0.2.6 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 From 2e0f74f58b9cb67f84b2bcf47dc082c74ba7483f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 17:29:43 +0000 Subject: [PATCH 757/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 951033e4a..cc3fee1c1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). * 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). * ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). From 46412ff67d5a0d04b95e6206f9ed050c13db47f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 16 Aug 2024 12:44:28 -0500 Subject: [PATCH 758/846] =?UTF-8?q?=F0=9F=94=8A=20Remove=20old=20ignore=20?= =?UTF-8?q?warnings=20(#11950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9e0611387..8db2d2b2d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -149,27 +149,14 @@ xfail_strict = true junit_family = "xunit2" filterwarnings = [ "error", - # TODO: needed by asyncio in Python 3.9.7 https://bugs.python.org/issue45097, try to remove on 3.9.8 - 'ignore:The loop argument is deprecated since Python 3\.8, and scheduled for removal in Python 3\.10:DeprecationWarning:asyncio', 'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette', - # TODO: remove after upgrading HTTPX to a version newer than 0.23.0 - # Including PR: https://github.com/encode/httpx/pull/2309 - "ignore:'cgi' is deprecated:DeprecationWarning", # For passlib "ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning", # see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28 "ignore:You seem to already have a custom.*:RuntimeWarning:trio", - # TODO remove pytest-cov - 'ignore::pytest.PytestDeprecationWarning:pytest_cov', # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes # https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2 'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy', - # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12 - # also, if it won't receive an update, consider replacing python-jose with some alternative - # related issues: - # - https://github.com/mpdavis/python-jose/issues/332 - # - https://github.com/mpdavis/python-jose/issues/334 - 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', # Trio 24.1.0 raises a warning from attrs # Ref: https://github.com/python-trio/trio/pull/3054 # Remove once there's a new version of Trio From 29babdc0a1974bb331330c20c24d588a26264a5f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 17:44:48 +0000 Subject: [PATCH 759/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cc3fee1c1..a5c713e03 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). * 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). * ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). From be7e7d44334adf4358125224488488910c39f5a5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 16 Aug 2024 17:45:47 +0000 Subject: [PATCH 760/846] =?UTF-8?q?=E2=AC=86=20Update=20sqlalchemy=20requi?= =?UTF-8?q?rement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- updated-dependencies: - dependency-name: sqlalchemy dependency-type: direct:production ... Signed-off-by: dependabot[bot] <support@github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index bfe70f2f5..801cf9dd4 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -7,7 +7,7 @@ ruff ==0.2.0 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel -sqlalchemy >=1.3.18,<1.4.43 +sqlalchemy >=1.3.18,<2.0.33 databases[sqlite] >=0.3.2,<0.7.0 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 From daf4970ed7c8da680c2dd550d6346861c8eb0ace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 16 Aug 2024 16:56:33 -0500 Subject: [PATCH 761/846] =?UTF-8?q?=F0=9F=93=9D=20Clarify=20management=20t?= =?UTF-8?q?asks=20for=20translations,=20multiples=20files=20in=20one=20PR?= =?UTF-8?q?=20(#12030)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/management-tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index 815bad539..7e7aa3baf 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -113,7 +113,7 @@ For the other languages, confirm that: * The title is correct following the instructions above. * It has the labels `lang-all` and `lang-{lang code}`. * The PR changes only one Markdown file adding a translation. - * Or in some cases, at most two files, if they are small and people reviewed them. + * Or in some cases, at most two files, if they are small, for the same language, and people reviewed them. * If it's the first translation for that language, it will have additional `mkdocs.yml` files, for those cases follow the instructions below. * The PR doesn't add any additional or extraneous files. * The translation seems to have a similar structure as the original English file. From 7ed9a4971e0b4b2e5ec3ac3dd22f3146b911fc7a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 21:56:54 +0000 Subject: [PATCH 762/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a5c713e03..7197e803c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). * 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). * 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). * 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev). From beedc72281a12379e6c2e621d3db13726b787851 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 22:32:33 +0000 Subject: [PATCH 763/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7197e803c..da1094ea6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Internal +* ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). * 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). From 8a146b7a28a46f141f3f3be0b74cd6d11fb823ff Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Fri, 16 Aug 2024 18:18:02 -0500 Subject: [PATCH 764/846] =?UTF-8?q?=F0=9F=94=A5=20Remove=20Sentry=20link?= =?UTF-8?q?=20from=20Advanced=20Middleware=20docs=20(#12031)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/middleware.md | 1 - docs/em/docs/advanced/middleware.md | 1 - docs/en/docs/advanced/middleware.md | 1 - docs/zh/docs/advanced/middleware.md | 1 - 4 files changed, 4 deletions(-) diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index 4116b30ec..8912225fb 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -95,7 +95,6 @@ Es gibt viele andere ASGI-Middlewares. Zum Beispiel: -* <a href="https://docs.sentry.io/platforms/python/guides/fastapi/" class="external-link" target="_blank">Sentry</a> * <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorns `ProxyHeadersMiddleware`</a> * <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">MessagePack</a> diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index 89f494aa3..e3cc389c6 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -95,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🖼: -* <a href="https://docs.sentry.io/platforms/python/asgi/" class="external-link" target="_blank">🔫</a> * <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorn `ProxyHeadersMiddleware`</a> * <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">🇸🇲</a> diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 57e476167..70415adca 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -96,7 +96,6 @@ There are many other ASGI middlewares. For example: -* <a href="https://docs.sentry.io/platforms/python/guides/fastapi/" class="external-link" target="_blank">Sentry</a> * <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorn's `ProxyHeadersMiddleware`</a> * <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">MessagePack</a> diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 764784ce3..926082b94 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -95,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 例如: -* <a href="https://docs.sentry.io/platforms/python/asgi/" class="external-link" target="_blank">Sentry</a> * <a href="https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py" class="external-link" target="_blank">Uvicorn 的 `ProxyHeadersMiddleware`</a> * <a href="https://github.com/florimondmanca/msgpack-asgi" class="external-link" target="_blank">MessagePack</a> From 8b05d4518b64ec18938e76954d4ecf6bd9f289b2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 16 Aug 2024 23:18:21 +0000 Subject: [PATCH 765/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index da1094ea6..9d8513faf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). * 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). * 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). * 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). From 957d747d21d07db306a45015178d902367c89342 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem <svlandeg@users.noreply.github.com> Date: Sat, 17 Aug 2024 05:57:21 +0200 Subject: [PATCH 766/846] =?UTF-8?q?=F0=9F=93=9D=20Highlight=20correct=20li?= =?UTF-8?q?ne=20in=20tutorial=20`docs/en/docs/tutorial/body-multiple-param?= =?UTF-8?q?s.md`=20(#11978)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Esteban Maya <emayacadavid9@gmail.com> --- docs/en/docs/tutorial/body-multiple-params.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 3adfcd4d1..511fb358e 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -228,7 +228,7 @@ For example: //// tab | Python 3.10+ -```Python hl_lines="27" +```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` @@ -236,7 +236,7 @@ For example: //// tab | Python 3.9+ -```Python hl_lines="27" +```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` @@ -244,7 +244,7 @@ For example: //// tab | Python 3.8+ -```Python hl_lines="28" +```Python hl_lines="29" {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} ``` @@ -258,7 +258,7 @@ Prefer to use the `Annotated` version if possible. /// -```Python hl_lines="25" +```Python hl_lines="26" {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` @@ -272,7 +272,7 @@ Prefer to use the `Annotated` version if possible. /// -```Python hl_lines="27" +```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004.py!} ``` From 263e46e5403a78d9bdf249338ed382affe01eb1a Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 17 Aug 2024 03:57:45 +0000 Subject: [PATCH 767/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9d8513faf..314ea19c5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). * 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). * 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). * 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). From 4a7f6e0ae66fb1d2b08aee5035df895074dccdfa Mon Sep 17 00:00:00 2001 From: gitworkflows <118260833+gitworkflows@users.noreply.github.com> Date: Sat, 17 Aug 2024 09:59:06 +0600 Subject: [PATCH 768/846] =?UTF-8?q?=F0=9F=94=A8=20Standardize=20shebang=20?= =?UTF-8?q?across=20shell=20scripts=20(#11942)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/format.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/format.sh b/scripts/format.sh index 45742f79a..bf70f42e5 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -1,4 +1,4 @@ -#!/bin/sh -e +#!/usr/bin/env bash set -x ruff check fastapi tests docs_src scripts --fix From 6433c3b70e696398b6cedd33025007960744c281 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 17 Aug 2024 04:00:12 +0000 Subject: [PATCH 769/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 314ea19c5..bd70a80ff 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). From 3a3ad5d66d0cae4be95675b93d8ee8b10c3ce212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 16 Aug 2024 23:13:50 -0500 Subject: [PATCH 770/846] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20version?= =?UTF-8?q?=20of=20Ruff=20and=20reformat=20(#12032)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .github/actions/people/app/main.py | 6 +++--- .pre-commit-config.yaml | 2 +- fastapi/dependencies/utils.py | 6 +++--- fastapi/routing.py | 12 ++++++------ fastapi/utils.py | 6 +++--- requirements-tests.txt | 2 +- tests/test_dependency_contextmanager.py | 6 +++--- tests/test_inherited_custom_class.py | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index 33156f1ca..b752d9d2b 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -515,9 +515,9 @@ def get_individual_sponsors(settings: Settings): tiers: DefaultDict[float, Dict[str, SponsorEntity]] = defaultdict(dict) for node in nodes: - tiers[node.tier.monthlyPriceInDollars][ - node.sponsorEntity.login - ] = node.sponsorEntity + tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = ( + node.sponsorEntity + ) return tiers diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4d49845d6..1ed005657 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.2.0 + rev: v0.6.1 hooks: - id: ruff args: diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 4f984177a..3e8e7b410 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -342,9 +342,9 @@ def analyze_param( if isinstance(arg, (params.Param, params.Body, params.Depends)) ] if fastapi_specific_annotations: - fastapi_annotation: Union[ - FieldInfo, params.Depends, None - ] = fastapi_specific_annotations[-1] + fastapi_annotation: Union[FieldInfo, params.Depends, None] = ( + fastapi_specific_annotations[-1] + ) else: fastapi_annotation = None if isinstance(fastapi_annotation, FieldInfo): diff --git a/fastapi/routing.py b/fastapi/routing.py index fa1351859..2e7959f3d 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -454,9 +454,9 @@ class APIRoute(routing.Route): methods = ["GET"] self.methods: Set[str] = {method.upper() for method in methods} if isinstance(generate_unique_id_function, DefaultPlaceholder): - current_generate_unique_id: Callable[ - ["APIRoute"], str - ] = generate_unique_id_function.value + current_generate_unique_id: Callable[[APIRoute], str] = ( + generate_unique_id_function.value + ) else: current_generate_unique_id = generate_unique_id_function self.unique_id = self.operation_id or current_generate_unique_id(self) @@ -482,9 +482,9 @@ class APIRoute(routing.Route): # By being a new field, no inheritance will be passed as is. A new model # will always be created. # TODO: remove when deprecating Pydantic v1 - self.secure_cloned_response_field: Optional[ - ModelField - ] = create_cloned_field(self.response_field) + self.secure_cloned_response_field: Optional[ModelField] = ( + create_cloned_field(self.response_field) + ) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None diff --git a/fastapi/utils.py b/fastapi/utils.py index dfda4e678..5c2538fac 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -34,9 +34,9 @@ if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` -_CLONED_TYPES_CACHE: MutableMapping[ - Type[BaseModel], Type[BaseModel] -] = WeakKeyDictionary() +_CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( + WeakKeyDictionary() +) def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: diff --git a/requirements-tests.txt b/requirements-tests.txt index 801cf9dd4..08561d23a 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,7 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -ruff ==0.2.0 +ruff ==0.6.1 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index 008dab7bc..039c423b9 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -196,9 +196,9 @@ async def get_sync_context_b_bg( tasks: BackgroundTasks, state: dict = Depends(context_b) ): async def bg(state: dict): - state[ - "sync_bg" - ] = f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + state["sync_bg"] = ( + f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + ) tasks.add_task(bg, state) return state diff --git a/tests/test_inherited_custom_class.py b/tests/test_inherited_custom_class.py index 42b249211..fe9350f4e 100644 --- a/tests/test_inherited_custom_class.py +++ b/tests/test_inherited_custom_class.py @@ -36,7 +36,7 @@ def test_pydanticv2(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} @@ -79,7 +79,7 @@ def test_pydanticv1(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} From 980c88c347cbb54c72b31491efbdc000788bebbe Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 17 Aug 2024 04:14:10 +0000 Subject: [PATCH 771/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bd70a80ff..3c9f53d4b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ⬆️ Upgrade version of Ruff and reformat. PR [#12032](https://github.com/fastapi/fastapi/pull/12032) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). From 659350e9cd0e1948ce2bdc95cc3ac2ffb5a41238 Mon Sep 17 00:00:00 2001 From: Jamie Phan <jamie@ordinarylab.dev> Date: Sat, 17 Aug 2024 14:52:31 +1000 Subject: [PATCH 772/846] =?UTF-8?q?=F0=9F=8E=A8=20Fix=20typing=20annotatio?= =?UTF-8?q?n=20for=20semi-internal=20`FastAPI.add=5Fapi=5Froute()`=20(#102?= =?UTF-8?q?40)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- fastapi/applications.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index 4f5e6f1d9..6d427cdc2 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -1056,7 +1056,7 @@ class FastAPI(Starlette): def add_api_route( self, path: str, - endpoint: Callable[..., Coroutine[Any, Any, Response]], + endpoint: Callable[..., Any], *, response_model: Any = Default(None), status_code: Optional[int] = None, From 6aa0435a3ee1ace6c4fb121a3865c23d2d07bea8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 17 Aug 2024 04:52:53 +0000 Subject: [PATCH 773/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3c9f53d4b..8e58ecb39 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* 🎨 Fix typing annotation for semi-internal `FastAPI.add_api_route()`. PR [#10240](https://github.com/fastapi/fastapi/pull/10240) by [@ordinary-jamie](https://github.com/ordinary-jamie). * ⬆️ Upgrade version of Ruff and reformat. PR [#12032](https://github.com/fastapi/fastapi/pull/12032) by [@tiangolo](https://github.com/tiangolo). ### Docs From ff1118d6a0232d3c768a8fe9346d99a004269eef Mon Sep 17 00:00:00 2001 From: Ahsan Sheraz <ahsansheraz250@gmail.com> Date: Sat, 17 Aug 2024 08:42:07 +0200 Subject: [PATCH 774/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Urdu=20translat?= =?UTF-8?q?ion=20for=20`docs/ur/docs/benchmarks.md`=20(#10046)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/ur/docs/benchmarks.md | 43 +++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/docs/ur/docs/benchmarks.md b/docs/ur/docs/benchmarks.md index 9fc793e6f..8d583de2f 100644 --- a/docs/ur/docs/benchmarks.md +++ b/docs/ur/docs/benchmarks.md @@ -1,5 +1,4 @@ # بینچ مارکس - انڈیپنڈنٹ ٹیک امپور بینچ مارک **FASTAPI** Uvicorn کے تحت چلنے والی ایپلی کیشنز کو <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank"> ایک تیز رفتار Python فریم ورک میں سے ایک </a> ، صرف Starlette اور Uvicorn کے نیچے ( FASTAPI کے ذریعہ اندرونی طور پر استعمال کیا جاتا ہے ) (*) لیکن جب بینچ مارک اور موازنہ کی جانچ پڑتال کرتے ہو تو آپ کو مندرجہ ذیل بات ذہن میں رکھنی چاہئے. @@ -14,39 +13,39 @@ درجہ بندی کی طرح ہے: -<ul style="direction: rtl;"> - <li><div style="text-align: right;">ASGI :<b>Uvicorn</b> سرور</div></li> +<ul> + <li>سرور ASGI :<b>Uvicorn</b></li> <ul> - <li><div style="text-align: right;"><b>Starlette</b>: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک </div></li> + <li><b>Starlette</b>: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک</li> <ul> - <li><div style="text-align: right;"><b>FastAPI</b>: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔</div></li> + <li><b>FastAPI</b>: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔</li> </ul> </ul> </ul> -<ul style="direction: rtl;"> - <li><div style="text-align: right;"><b>Uvicorn</b>:</div></li> +<ul> + <li><b>Uvicorn</b>:</li> <ul> - <li><div style="text-align: right;">بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔</div></li> - <li><div style="text-align: right;">آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا <b>FastAPI</b>) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔</div></li> - <li><div style="text-align: right;">اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔</div></li> + <li>بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔</li> + <li>آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا <b>FastAPI</b>) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔</li> + <li>اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔</li> </ul> </ul> -<ul style="direction: rtl;"> - <li><div style="text-align: right;"><b>Starlette</b>:</div></li> +<ul> + <li><b>Starlette</b>:</li> <ul> - <li><div style="text-align: right;">Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔</div></li> - <li><div style="text-align: right;">لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔</div></li> - <li><div style="text-align: right;">اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)</div></li> + <li>Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔</li> + <li>لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔></li> + <li>اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)</li> </ul> </ul> -<ul style="direction: rtl;"> - <li><div style="text-align: right;"><b>FastAPI</b>:</div></li> +<ul> + <li><b>FastAPI</b>:</li> <ul> - <li><div style="text-align: right;">جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette <b>FastAPI</b> کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔</div></li> - <li><div style="text-align: right;">Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔</div></li> - <li><div style="text-align: right;">اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔</div></li> - <li><div style="text-align: right;">لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )</div></li> - <li><div style="text-align: right;">اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔</div></li> + <li>جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette <b>FastAPI</b> کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔</li> + <li>Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔</li> + <li>اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔</li> + <li>لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )></li> + <li>اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔</li> </ul> </ul> From 066ea10ac5950ffa941e94ed13f112ceab7ae683 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 17 Aug 2024 06:42:28 +0000 Subject: [PATCH 775/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8e58ecb39..486531569 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,10 @@ hide: * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). +### Translations + +* 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). + ### Internal * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). From 85cded53c8273cb26ee50089383498422d75f658 Mon Sep 17 00:00:00 2001 From: 0shah0 <84684114+0shah0@users.noreply.github.com> Date: Sat, 17 Aug 2024 12:23:52 +0530 Subject: [PATCH 776/846] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20import=20typ?= =?UTF-8?q?o=20in=20reference=20example=20for=20`Security`=20(#11168)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- fastapi/param_functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 3b25d774a..0d5f27af4 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -2343,7 +2343,7 @@ def Security( # noqa: N802 ```python from typing import Annotated - from fastapi import Depends, FastAPI + from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user From 882f77f9258c45c5962e0b263c63bdfa80eb4fc3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 17 Aug 2024 06:54:13 +0000 Subject: [PATCH 777/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 486531569..17a24a984 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). * 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). * 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). From 9bfc48ad9fba044462eb9d0e1b556cf721f56ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 17 Aug 2024 16:20:31 -0500 Subject: [PATCH 778/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e,=20do=20not=20translate=20to=20have=20the=20most=20recent=20i?= =?UTF-8?q?nfo=20(#12034)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/az/docs/fastapi-people.md | 185 --------------------- docs/de/docs/fastapi-people.md | 176 -------------------- docs/em/docs/fastapi-people.md | 183 --------------------- docs/en/data/members.yml | 12 +- docs/fr/docs/fastapi-people.md | 180 --------------------- docs/ja/docs/fastapi-people.md | 184 --------------------- docs/pl/docs/fastapi-people.md | 178 --------------------- docs/pt/docs/fastapi-people.md | 183 --------------------- docs/ru/docs/fastapi-people.md | 184 --------------------- docs/tr/docs/fastapi-people.md | 183 --------------------- docs/uk/docs/fastapi-people.md | 183 --------------------- docs/zh-hant/docs/fastapi-people.md | 239 ---------------------------- docs/zh/docs/fastapi-people.md | 239 ---------------------------- scripts/docs.py | 1 + scripts/mkdocs_hooks.py | 1 + 15 files changed, 8 insertions(+), 2303 deletions(-) delete mode 100644 docs/az/docs/fastapi-people.md delete mode 100644 docs/de/docs/fastapi-people.md delete mode 100644 docs/em/docs/fastapi-people.md delete mode 100644 docs/fr/docs/fastapi-people.md delete mode 100644 docs/ja/docs/fastapi-people.md delete mode 100644 docs/pl/docs/fastapi-people.md delete mode 100644 docs/pt/docs/fastapi-people.md delete mode 100644 docs/ru/docs/fastapi-people.md delete mode 100644 docs/tr/docs/fastapi-people.md delete mode 100644 docs/uk/docs/fastapi-people.md delete mode 100644 docs/zh-hant/docs/fastapi-people.md delete mode 100644 docs/zh/docs/fastapi-people.md diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md deleted file mode 100644 index 9bb7ad6ea..000000000 --- a/docs/az/docs/fastapi-people.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI İnsanlar - -FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var. - - - -## Yaradıcı - İcraçı - -Salam! 👋 - -Bu mənəm: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablar: {{ user.answers }}</div><div class="count">Pull Request-lər: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Mən **FastAPI**-ın yaradıcısı və icraçısıyam. Əlavə məlumat almaq üçün [Yardım FastAPI - Yardım alın - Müəlliflə əlaqə qurun](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} səhifəsinə baxa bilərsiniz. - -...Burada isə sizə icmanı göstərmək istəyirəm. - ---- - -**FastAPI** icmadan çoxlu dəstək alır və mən onların əməyini vurğulamaq istəyirəm. - -Bu insanlar: - -* [GitHub-da başqalarının suallarına kömək edirlər](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request-lər yaradırlar](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request-ləri ([xüsusilə tərcümələr üçün vacib olan](contributing.md#translations){.internal-link target=_blank}.) nəzərdən keçirirlər. - -Bu insanlara təşəkkür edirəm. 👏 🙇 - -## Keçən ayın ən fəal istifadəçiləri - -Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Mütəxəssislər - -Burada **FastAPI Mütəxəssisləri** var. 🤓 - -Bu istifadəçilər indiyə qədər [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. - -Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut ediblər. ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cavablandırılmış suallar: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Ən yaxşı əməkdaşlar - -Burada **Ən yaxşı əməkdaşlar** var. 👷 - -Bu istifadəçilərin ən çox *birləşdirilmiş* [Pull Request-ləri var](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. - -Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstərmişlər. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Request-lər: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Əməkdaşlar səhifəsində</a> görə bilərsiniz. 👷 - -## Ən çox rəy verənlər - -Bu istifadəçilər **ən çox rəy verənlər**dir. - -### Tərcümələr üçün rəylər - -Mən yalnız bir neçə dildə danışıram (və çox da yaxşı deyil 😅). Bu səbəbdən, rəy verənlər sənədlərin [**tərcümələrini təsdiqləmək üçün gücə malik olanlar**](contributing.md#translations){.internal-link target=_blank}dır. Onlar olmadan, bir çox dilə tərcümə olunmuş sənədlər olmazdı. - ---- - -Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun, sənədlərin və xüsusilə də **tərcümələrin** keyfiyyətini təmin edirlər. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Rəylər: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Sponsorlar - -Bunlar **Sponsorlar**dır. 😎 - -Onlar mənim **FastAPI** (və digər) işlərimi əsasən <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsorlar</a> vasitəsilə dəstəkləyirlər. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Qızıl Sponsorlar - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bürünc Sponsorlar - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### Fərdi Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## Məlumatlar haqqında - texniki detallar - -Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün göstərdiyi əməyi vurğulamaqdır. - -Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək. - -Bu səhifənin məlumatları hər ay hesablanır və siz <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">buradan mənbə kodunu</a> oxuya bilərsiniz. - -Burada sponsorların əməyini də vurğulamaq istəyirəm. - -Mən həmçinin alqoritmi, bölmələri, eşikləri və s. yeniləmək hüququnu da qoruyuram (hər ehtimala qarşı 🤷). diff --git a/docs/de/docs/fastapi-people.md b/docs/de/docs/fastapi-people.md deleted file mode 100644 index deaecf214..000000000 --- a/docs/de/docs/fastapi-people.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Leute - -FastAPI hat eine großartige Gemeinschaft, die Menschen mit unterschiedlichstem Hintergrund willkommen heißt. - -## Erfinder - Betreuer - -Hey! 👋 - -Das bin ich: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Ich bin der Erfinder und Betreuer von **FastAPI**. Sie können mehr darüber in [FastAPI helfen – Hilfe erhalten – Mit dem Autor vernetzen](help-fastapi.md#mit-dem-autor-vernetzen){.internal-link target=_blank} erfahren. - -... Aber hier möchte ich Ihnen die Gemeinschaft vorstellen. - ---- - -**FastAPI** erhält eine Menge Unterstützung aus der Gemeinschaft. Und ich möchte ihre Beiträge hervorheben. - -Das sind die Menschen, die: - -* [Anderen bei Fragen auf GitHub helfen](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. -* [<abbr title='Pull Request – „Zieh-Anfrage“: Geänderten Quellcode senden, mit dem Vorschlag, ihn mit dem aktuellen Quellcode zu verschmelzen'>Pull Requests</abbr> erstellen](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank}. -* Pull Requests überprüfen (Review), [besonders wichtig für Übersetzungen](contributing.md#ubersetzungen){.internal-link target=_blank}. - -Eine Runde Applaus für sie. 👏 🙇 - -## Aktivste Benutzer im letzten Monat - -Hier die Benutzer, die im letzten Monat am meisten [anderen mit Fragen auf Github](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} geholfen haben. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_active %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Fragen beantwortet: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Experten - -Hier die **FastAPI-Experten**. 🤓 - -Das sind die Benutzer, die *insgesamt* [anderen am meisten mit Fragen auf GitHub geholfen haben](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. - -Sie haben bewiesen, dass sie Experten sind, weil sie vielen anderen geholfen haben. ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Fragen beantwortet: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Top-Mitwirkende - -Hier sind die **Top-Mitwirkenden**. 👷 - -Diese Benutzer haben [die meisten Pull Requests erstellt](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank} welche *<abbr title="Mergen – Zusammenführen: Unterschiedliche Versionen eines Quellcodes zusammenführen">gemerged</abbr>* wurden. - -Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors-Seite</a> sehen. 👷 - -## Top-Rezensenten - -Diese Benutzer sind die **Top-Rezensenten**. 🕵️ - -### Rezensionen für Übersetzungen - -Ich spreche nur ein paar Sprachen (und nicht sehr gut 😅). Daher bestätigen Reviewer [**Übersetzungen der Dokumentation**](contributing.md#ubersetzungen){.internal-link target=_blank}. Ohne sie gäbe es keine Dokumentation in mehreren anderen Sprachen. - ---- - -Die **Top-Reviewer** 🕵️ haben die meisten Pull Requests von anderen überprüft und stellen die Qualität des Codes, der Dokumentation und insbesondere der **Übersetzungen** sicher. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_reviewers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Sponsoren - -Dies sind die **Sponsoren**. 😎 - -Sie unterstützen meine Arbeit an **FastAPI** (und andere), hauptsächlich durch <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub-Sponsoren</a>. - -### Gold Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> -{% endfor %} -{% endif %} - -### Silber Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> -{% endfor %} -{% endif %} - -{% if people %} -{% if people.sponsors_50 %} - -### Bronze Sponsoren - -<div class="user-list user-list-center"> -{% for user in people.sponsors_50 %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> -{% endfor %} - -</div> - -{% endif %} -{% endif %} - -### Individuelle Sponsoren - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.sponsors %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> -{% endfor %} - -</div> -{% endif %} - -## Über diese Daten - technische Details - -Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft. - -Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen. - -Diese Daten werden jeden Monat berechnet, Sie können den <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">Quellcode hier lesen</a>. - -Hier weise ich auch auf Beiträge von Sponsoren hin. - -Ich behalte mir auch das Recht vor, den Algorithmus, die Abschnitte, die Schwellenwerte usw. zu aktualisieren (nur für den Fall 🤷). diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md deleted file mode 100644 index 75880e216..000000000 --- a/docs/em/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 👫👫 - -FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. - -## 👼 - 🐛 - -🙋 ❗ 👶 - -👉 👤: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔: {{ user.answers }}</div><div class="count">🚲 📨: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -👤 👼 & 🐛 **FastAPI**. 👆 💪 ✍ 🌅 🔃 👈 [ℹ FastAPI - 🤚 ℹ - 🔗 ⏮️ 📕](help-fastapi.md#_3){.internal-link target=_blank}. - -...✋️ 📥 👤 💚 🎦 👆 👪. - ---- - -**FastAPI** 📨 📚 🐕🦺 ⚪️➡️ 👪. & 👤 💚 🎦 👫 💰. - -👫 👫👫 👈: - -* [ℹ 🎏 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank}. -* [✍ 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank}. -* 📄 🚲 📨, [✴️ ⚠ ✍](contributing.md#_9){.internal-link target=_blank}. - -👏 👫. 👶 👶 - -## 🌅 🦁 👩💻 🏁 🗓️ - -👫 👩💻 👈 ✔️ [🤝 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} ⏮️ 🏁 🗓️. 👶 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔ 📨: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## 🕴 - -📥 **FastAPI 🕴**. 👶 - -👫 👩💻 👈 ✔️ [ℹ 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} 🔘 *🌐 🕰*. - -👫 ✔️ 🎦 🕴 🤝 📚 🎏. 👶 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">❔ 📨: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## 🔝 👨🔬 - -📥 **🔝 👨🔬**. 👶 - -👉 👩💻 ✔️ [✍ 🏆 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank} 👈 ✔️ *🔗*. - -👫 ✔️ 📉 ℹ 📟, 🧾, ✍, ♒️. 👶 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">🚲 📨: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -📤 📚 🎏 👨🔬 (🌅 🌘 💯), 👆 💪 👀 👫 🌐 <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI 📂 👨🔬 📃</a>. 👶 - -## 🔝 👨🔬 - -👫 👩💻 **🔝 👨🔬**. 👶 👶 - -### 📄 ✍ - -👤 🕴 💬 👩❤👨 🇪🇸 (& 🚫 📶 👍 👶). , 👨🔬 🕐 👈 ✔️ [**🏋️ ✔ ✍**](contributing.md#_9){.internal-link target=_blank} 🧾. 🍵 👫, 📤 🚫🔜 🧾 📚 🎏 🇪🇸. - ---- - -**🔝 👨🔬** 👶 👶 ✔️ 📄 🏆 🚲 📨 ⚪️➡️ 🎏, 🚚 🔆 📟, 🧾, & ✴️, **✍**. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">📄: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## 💰 - -👫 **💰**. 👶 - -👫 🔗 👇 👷 ⏮️ **FastAPI** (& 🎏), ✴️ 🔘 <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">📂 💰</a>. - -{% if sponsors %} - -{% if sponsors.gold %} - -### 🌟 💰 - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 🥇1st 💰 - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 🥈2nd 💰 - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### 🎯 💰 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## 🔃 📊 - 📡 ℹ - -👑 🎯 👉 📃 🎦 🎯 👪 ℹ 🎏. - -✴️ ✅ 🎯 👈 🛎 🌘 ⭐, & 📚 💼 🌅 😩, 💖 🤝 🎏 ⏮️ ❔ & ⚖ 🚲 📨 ⏮️ ✍. - -💽 ⚖ 🔠 🗓️, 👆 💪 ✍ <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">ℹ 📟 📥</a>. - -📥 👤 🎦 💰 ⚪️➡️ 💰. - -👤 🏦 ▶️️ ℹ 📊, 📄, ⚡, ♒️ (💼 🤷). diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml index 0b9e7b94c..0069f8c75 100644 --- a/docs/en/data/members.yml +++ b/docs/en/data/members.yml @@ -1,19 +1,19 @@ members: - login: tiangolo - avatar_url: https://github.com/tiangolo.png + avatar_url: https://avatars.githubusercontent.com/u/1326112 url: https://github.com/tiangolo - login: Kludex - avatar_url: https://github.com/Kludex.png + avatar_url: https://avatars.githubusercontent.com/u/7353520 url: https://github.com/Kludex - login: alejsdev - avatar_url: https://github.com/alejsdev.png + avatar_url: https://avatars.githubusercontent.com/u/90076947 url: https://github.com/alejsdev - login: svlandeg - avatar_url: https://github.com/svlandeg.png + avatar_url: https://avatars.githubusercontent.com/u/8796347 url: https://github.com/svlandeg - login: estebanx64 - avatar_url: https://github.com/estebanx64.png + avatar_url: https://avatars.githubusercontent.com/u/10840422 url: https://github.com/estebanx64 - login: patrick91 - avatar_url: https://github.com/patrick91.png + avatar_url: https://avatars.githubusercontent.com/u/667029 url: https://github.com/patrick91 diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md deleted file mode 100644 index 52a79032a..000000000 --- a/docs/fr/docs/fastapi-people.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -hide: - - navigation ---- - -# La communauté FastAPI - -FastAPI a une communauté extraordinaire qui accueille des personnes de tous horizons. - -## Créateur - Mainteneur - -Salut! 👋 - -C'est moi : - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Réponses: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus à ce sujet dans [Aide FastAPI - Obtenir de l'aide - Se rapprocher de l'auteur](help-fastapi.md#se-rapprocher-de-lauteur){.internal-link target=_blank}. - -...Mais ici, je veux vous montrer la communauté. - ---- - -**FastAPI** reçoit beaucoup de soutien de la part de la communauté. Et je tiens à souligner leurs contributions. - -Ce sont ces personnes qui : - -* [Aident les autres à résoudre des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank}. -* [Créent des Pull Requests](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank}. -* Review les Pull Requests, [particulièrement important pour les traductions](contributing.md#traductions){.internal-link target=_blank}. - -Une salve d'applaudissements pour eux. 👏 🙇 - -## Utilisateurs les plus actifs le mois dernier - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} au cours du dernier mois. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions répondues: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Experts - -Voici les **Experts FastAPI**. 🤓 - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} depuis *toujours*. - -Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personnes. ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions répondues: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Principaux contributeurs - -Ces utilisateurs sont les **Principaux contributeurs**. 👷 - -Ces utilisateurs ont [créé le plus grand nombre de demandes Pull Request](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank} qui ont été *merged*. - -Ils ont contribué au code source, à la documentation, aux traductions, etc. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Il existe de nombreux autres contributeurs (plus d'une centaine), vous pouvez les voir tous dans la <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">Page des contributeurs de FastAPI GitHub</a>. 👷 - -## Principaux Reviewers - -Ces utilisateurs sont les **Principaux Reviewers**. 🕵️ - -### Reviewers des traductions - -Je ne parle que quelques langues (et pas très bien 😅). Ainsi, les reviewers sont ceux qui ont le [**pouvoir d'approuver les traductions**](contributing.md#traductions){.internal-link target=_blank} de la documentation. Sans eux, il n'y aurait pas de documentation dans plusieurs autres langues. - ---- - -Les **Principaux Reviewers** 🕵️ ont examiné le plus grand nombre de demandes Pull Request des autres, assurant la qualité du code, de la documentation, et surtout, des **traductions**. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Sponsors - -Ce sont les **Sponsors**. 😎 - -Ils soutiennent mon travail avec **FastAPI** (et d'autres) avec <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## À propos des données - détails techniques - -L'intention de cette page est de souligner l'effort de la communauté pour aider les autres. - -Notamment en incluant des efforts qui sont normalement moins visibles, et, dans de nombreux cas, plus difficile, comme aider d'autres personnes à résoudre des problèmes et examiner les Pull Requests de traduction. - -Les données sont calculées chaque mois, vous pouvez lire le <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">code source ici</a>. - -Je me réserve également le droit de mettre à jour l'algorithme, les sections, les seuils, etc. (juste au cas où 🤷). diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md deleted file mode 100644 index aaf76ba21..000000000 --- a/docs/ja/docs/fastapi-people.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI People - -FastAPIには、様々なバックグラウンドの人々を歓迎する素晴らしいコミュニティがあります。 - -## Creator - Maintainer - -こんにちは! 👋 - -これが私です: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> - -{% endif %} - -私は **FastAPI** の作成者および Maintainer です。詳しくは [FastAPIを応援 - ヘルプの入手 - 開発者とつながる](help-fastapi.md#_1){.internal-link target=_blank} に記載しています。 - -...ところで、ここではコミュニティを紹介したいと思います。 - ---- - -**FastAPI** は、コミュニティから多くのサポートを受けています。そこで、彼らの貢献にスポットライトを当てたいと思います。 - -紹介するのは次のような人々です: - -* [GitHub issuesで他の人を助ける](help-fastapi.md#github-issues){.internal-link target=_blank}。 -* [プルリクエストをする](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* プルリクエストのレビューをする ([特に翻訳に重要](contributing.md#_8){.internal-link target=_blank})。 - -彼らに大きな拍手を。👏 🙇 - -## 先月最もアクティブだったユーザー - -彼らは、先月の[GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Experts - -**FastAPI experts** を紹介します。🤓 - -彼らは、*これまでに* [GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。 - -多くの人を助けることでexpertsであると示されています。✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Top Contributors - -**Top Contributors** を紹介します。👷 - -彼らは、*マージされた* [最も多くのプルリクエストを作成した](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}ユーザーです。 - -ソースコード、ドキュメント、翻訳などに貢献してくれました。📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -他にもたくさん (100人以上) の contributors がいます。<a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors ページ</a>ですべての contributors を確認できます。👷 - -## Top Reviewers - -以下のユーザーは **Top Reviewers** です。🕵️ - -### 翻訳のレビュー - -私は少しの言語しか話せません (もしくはあまり上手ではありません😅)。したがって、reviewers は、ドキュメントの[**翻訳を承認する権限**](contributing.md#_8){.internal-link target=_blank}を持っています。それらがなければ、いくつかの言語のドキュメントはなかったでしょう。 - ---- - -**Top Reviewers** 🕵️は、他の人からのプルリクエストのほとんどをレビューし、コード、ドキュメント、特に**翻訳**の品質を保証しています。 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Sponsors - -**Sponsors** を紹介します。😎 - -彼らは、<a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a> を介して私の **FastAPI** などに関する活動を支援してくれています。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## データについて - 技術詳細 - -このページの目的は、他の人を助けるためのコミュニティの努力にスポットライトを当てるためです。 - -特に、他の人の issues を支援したり、翻訳のプルリクエストを確認したりするなど、通常は目立たず、多くの場合、より困難な作業を含みます。 - -データは毎月集計されます。<a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">ソースコードはこちら</a>で確認できます。 - -ここでは、スポンサーの貢献も強調しています。 - -アルゴリズム、セクション、閾値などは更新されるかもしれません (念のために 🤷)。 diff --git a/docs/pl/docs/fastapi-people.md b/docs/pl/docs/fastapi-people.md deleted file mode 100644 index 6c431b401..000000000 --- a/docs/pl/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# Ludzie FastAPI - -FastAPI posiada wspaniałą społeczność, która jest otwarta dla ludzi z każdego środowiska. - -## Twórca - Opienik - -Cześć! 👋 - -To ja: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Liczba odpowiedzi: {{ user.answers }}</div><div class="count">Pull Requesty: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Jestem twórcą i opiekunem **FastAPI**. Możesz przeczytać więcej na ten temat w [Pomoc FastAPI - Uzyskaj pomoc - Skontaktuj się z autorem](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Ale tutaj chcę pokazać Ci społeczność. - ---- - -**FastAPI** otrzymuje wiele wsparcia od społeczności. Chciałbym podkreślić ich wkład. - -To są ludzie, którzy: - -* [Pomagają innym z pytaniami na GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Tworzą Pull Requesty](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Oceniają Pull Requesty, [to szczególnie ważne dla tłumaczeń](contributing.md#translations){.internal-link target=_blank}. - -Proszę o brawa dla nich. 👏 🙇 - -## Najaktywniejsi użytkownicy w zeszłym miesiącu - -Oto niektórzy użytkownicy, którzy [pomagali innym w największej liczbie pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} podczas ostatniego miesiąca. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_active %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Udzielonych odpowiedzi: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Eksperci - -Oto **eksperci FastAPI**. 🤓 - -To użytkownicy, którzy [pomogli innym z największa liczbą pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} od *samego początku*. - -Poprzez pomoc wielu innym, udowodnili, że są ekspertami. ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Udzielonych odpowiedzi: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Najlepsi Kontrybutorzy - -Oto **Najlepsi Kontrybutorzy**. 👷 - -Ci użytkownicy [stworzyli najwięcej Pull Requestów](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, które zostały *wcalone*. - -Współtworzyli kod źródłowy, dokumentację, tłumaczenia itp. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requesty: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">Kontrybutorzy FastAPI na GitHub</a>. 👷 - -## Najlepsi Oceniajacy - -Ci uzytkownicy są **Najlepszymi oceniającymi**. 🕵️ - -### Oceny Tłumaczeń - -Ja mówię tylko kilkoma językami (i to niezbyt dobrze 😅). Zatem oceniający są tymi, którzy mają [**moc zatwierdzania tłumaczeń**](contributing.md#translations){.internal-link target=_blank} dokumentacji. Bez nich nie byłoby dokumentacji w kilku innych językach. - ---- - -**Najlepsi Oceniający** 🕵️ przejrzeli więcej Pull Requestów, niż inni, zapewniając jakość kodu, dokumentacji, a zwłaszcza **tłumaczeń**. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_reviewers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Liczba ocen: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Sponsorzy - -Oto **Sponsorzy**. 😎 - -Wspierają moją pracę nad **FastAPI** (i innymi), głównie poprzez <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Złoci Sponsorzy - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Srebrni Sponsorzy - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Brązowi Sponsorzy - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### Indywidualni Sponsorzy - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## Techniczne szczegóły danych - -Głównym celem tej strony jest podkreślenie wysiłku społeczności w pomaganiu innym. - -Szczególnie włączając wysiłki, które są zwykle mniej widoczne, a w wielu przypadkach bardziej żmudne, tak jak pomaganie innym z pytaniami i ocenianie Pull Requestów z tłumaczeniami. - -Dane są obliczane każdego miesiąca, możesz przeczytać <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kod źródłowy tutaj</a>. - -Tutaj również podkreślam wkład od sponsorów. - -Zastrzegam sobie prawo do aktualizacji algorytmu, sekcji, progów itp. (na wszelki wypadek 🤷). diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md deleted file mode 100644 index d67ae0d33..000000000 --- a/docs/pt/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# Pessoas do FastAPI - -FastAPI possue uma comunidade incrível que recebe pessoas de todos os níveis. - -## Criador - Mantenedor - -Ei! 👋 - -Este sou eu: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Respostas: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#conect-se-com-o-autor){.internal-link target=_blank}. - -...Mas aqui eu quero mostrar a você a comunidade. - ---- - -**FastAPI** recebe muito suporte da comunidade. E quero destacar suas contribuições. - -Estas são as pessoas que: - -* [Help others with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank}. -* [Create Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank}. -* Revisar Pull Requests, [especially important for translations](contributing.md#traducoes){.internal-link target=_blank}. - -Uma salva de palmas para eles. 👏 🙇 - -## Usuários mais ativos do ultimo mês - -Estes são os usuários que estão [helping others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} durante o ultimo mês. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues respondidas: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Especialistas - -Aqui está os **Especialistas do FastAPI**. 🤓 - - -Estes são os usuários que [helped others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} em *todo o tempo*. - -Eles provaram ser especialistas ajudando muitos outros. ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues respondidas: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Top Contribuidores - -Aqui está os **Top Contribuidores**. 👷 - -Esses usuários têm [created the most Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank} que tem sido *mergeado*. - -Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Existem muitos outros contribuidores (mais de uma centena), você pode ver todos eles em <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">Página de Contribuidores do FastAPI no GitHub</a>. 👷 - -## Top Revisores - -Esses usuários são os **Top Revisores**. 🕵️ - -### Revisões para Traduções - -Eu só falo algumas línguas (e não muito bem 😅). Então, os revisores são aqueles que têm o [**poder de aprovar traduções**](contributing.md#traducoes){.internal-link target=_blank} da documentação. Sem eles, não haveria documentação em vários outros idiomas. - ---- - -Os **Top Revisores** 🕵️ revisaram a maior parte de Pull Requests de outros, garantindo a qualidade do código, documentação, e especialmente, as **traduções**. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Revisões: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Patrocinadores - -Esses são os **Patrocinadores**. 😎 - -Eles estão apoiando meu trabalho **FastAPI** (e outros), principalmente através de <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>. - -{% if sponsors %} -{% if sponsors.gold %} - -### Patrocinadores Ouro - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Patrocinadores Prata - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Patrocinadores Bronze - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> -{% endfor %} -{% endif %} - -### Patrocinadores Individuais - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -{% endif %} - -## Sobre os dados - detalhes técnicos - -A principal intenção desta página é destacar o esforço da comunidade para ajudar os outros. - -Especialmente incluindo esforços que normalmente são menos visíveis, e em muitos casos mais árduo, como ajudar os outros com issues e revisando Pull Requests com traduções. - -Os dados são calculados todo mês, você pode ler o <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">código fonte aqui</a>. - -Aqui também estou destacando contribuições de patrocinadores. - -Eu também me reservo o direito de atualizar o algoritmo, seções, limites, etc (só para prevenir 🤷). diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md deleted file mode 100644 index 31bb2798e..000000000 --- a/docs/ru/docs/fastapi-people.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -hide: - - navigation ---- - -# Люди, поддерживающие FastAPI - -У FastAPI замечательное сообщество, которое доброжелательно к людям с любым уровнем знаний. - -## Создатель и хранитель - -Хай! 👋 - -Это я: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#_2){.internal-link target=_blank}. - -... но на этой странице я хочу показать вам наше сообщество. - ---- - -**FastAPI** получает огромную поддержку от своего сообщества. И я хочу отметить вклад его участников. - -Это люди, которые: - -* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank}. -* [Создают пул-реквесты](help-fastapi.md#-_1){.internal-link target=_blank}. -* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#_8){.internal-link target=_blank}. - -Поаплодируем им! 👏 🙇 - -## Самые активные участники за прошедший месяц - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} в течение последнего месяца. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Эксперты - -Здесь представлены **Эксперты FastAPI**. 🤓 - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} за *всё время*. - -Оказывая помощь многим другим, они подтвердили свой уровень знаний. ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Рейтинг участников, внёсших вклад в код - -Здесь представлен **Рейтинг участников, внёсших вклад в код**. 👷 - -Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#-_1){.internal-link target=_blank}, *включённых в основной код*. - -Они сделали наибольший вклад в исходный код, документацию, переводы и т.п. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors page</a>. 👷 - -## Рейтинг ревьюеров - -Здесь представлен **Рейтинг ревьюеров**. 🕵️ - -### Проверки переводов на другие языки - -Я знаю не очень много языков (и не очень хорошо 😅). -Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#_8){.internal-link target=_blank}. Без них не было бы документации на многих языках. - ---- - -В **Рейтинге ревьюеров** 🕵️ представлены те, кто проверил наибольшее количество пул-реквестов других участников, обеспечивая качество кода, документации и, особенно, **переводов на другие языки**. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Спонсоры - -Здесь представлены **Спонсоры**. 😎 - -Спонсоры поддерживают мою работу над **FastAPI** (и другими проектами) главным образом через <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золотые спонсоры - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Серебрянные спонсоры - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзовые спонсоры - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### Индивидуальные спонсоры - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## О данных - технические детали - -Основная цель этой страницы - подчеркнуть усилия сообщества по оказанию помощи другим. - -Особенно это касается усилий, которые обычно менее заметны и во многих случаях более трудоемки, таких как помощь другим в решении проблем и проверка пул-реквестов с переводами. - -Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">тут</a>. - -Кроме того, я также подчеркиваю вклад спонсоров. - -И я оставляю за собой право обновлять алгоритмы подсчёта, виды рейтингов, пороговые значения и т.д. (так, на всякий случай 🤷). diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md deleted file mode 100644 index de62c57c4..000000000 --- a/docs/tr/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Topluluğu - -FastAPI, her kökenden insanı ağırlayan harika bir topluluğa sahip. - -## Yazan - Geliştiren - -Merhaba! 👋 - -İşte bu benim: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cevaplar: {{ user.answers }}</div><div class="count">Pull Request'ler: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Ben **FastAPI**'ın geliştiricisiyim. Bununla ilgili daha fazla bilgiyi şurada okuyabilirsiniz: [FastAPI yardım - yardım al - benimle iletişime geç](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...burada size harika FastAPI topluluğunu göstermek istiyorum. - ---- - -**FastAPI**, topluluğundan çok destek alıyor. Ben de onların katkılarını vurgulamak istiyorum. - -Bu insanlar: - -* [GitHubdaki soruları cevaplayarak diğerlerine yardım ediyor](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request'ler oluşturuyor](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request'leri gözden geçiriyorlar, [özellikle çeviriler için bu çok önemli](contributing.md#translations){.internal-link target=_blank}. - -Onları bir alkışlayalım. 👏 🙇 - -## Geçen Ayın En Aktif Kullanıcıları - -Geçtiğimiz ay boyunca [GitHub'da diğerlerine en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} kullanıcılar. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cevaplanan soru sayısı: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Uzmanlar - -İşte **FastAPI Uzmanları**. 🤓 - -Uzmanlarımız ise *tüm zamanlar boyunca* [GitHub'da insanların sorularına en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} insanlar. - -Bir çok kullanıcıya yardım ederek uzman olduklarını kanıtladılar! ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Cevaplanan soru sayısı: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## En Fazla Katkıda Bulunanlar - -Şimdi ise sıra **en fazla katkıda bulunanlar**da. 👷 - -Bu kullanıcılar en fazla [kaynak koduyla birleştirilen Pull Request'lere](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} sahip! - -Kaynak koduna, dökümantasyona, çevirilere ve bir sürü şeye katkıda bulundular. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Request sayısı: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Bunlar dışında katkıda bulunan, yüzden fazla, bir sürü insan var. Hepsini <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Katkıda Bulunanlar</a> sayfasında görebilirsin. 👷 - -## En Fazla Değerlendirme Yapanlar - -İşte **en çok değerlendirme yapanlar**. 🕵️ - -### Çeviri Değerlendirmeleri - -Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzden değerlendirme yapanların da döküman çevirilerini [**onaylama yetkisi**](contributing.md#translations){.internal-link target=_blank} var. Onlar olmasaydı çeşitli dillerde dökümantasyon da olmazdı. - ---- - -**En fazla değerlendirme yapanlar** 🕵️ kodun, dökümantasyonun ve özellikle **çevirilerin** Pull Request'lerini inceleyerek kalitesinden emin oldular. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Değerlendirme sayısı: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Sponsorlar - -işte **Sponsorlarımız**. 😎 - -Çoğunlukla <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsorları</a> aracılığıyla olmak üzere, **FastAPI** ve diğer projelerdeki çalışmalarımı destekliyorlar. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Altın Sponsorlar - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronz Sponsorlar - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### Bireysel Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## Veriler - Teknik detaylar - -Bu sayfanın temel amacı, topluluğun başkalarına yardım etme çabasını vurgulamaktır. - -Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorularında yardımcı olmak, çevirileri ve Pull Request'leri gözden geçirmek gibi çabalar dahil. - -Veriler ayda bir hesaplanır, <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kaynak kodu buradan</a> okuyabilirsin. - -Burada sponsorların katkılarını da vurguluyorum. - -Ayrıca algoritmayı, bölümleri, eşikleri vb. güncelleme hakkımı da saklı tutuyorum (her ihtimale karşı 🤷). diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md deleted file mode 100644 index c6a6451d8..000000000 --- a/docs/uk/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# Люди FastAPI - -FastAPI має дивовижну спільноту, яка вітає людей різного походження. - -## Творець – Супроводжувач - -Привіт! 👋 - -Це я: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Я - творець і супроводжувач **FastAPI**. Детальніше про це можна прочитати в [Довідка FastAPI - Отримати довідку - Зв'язатися з автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Але тут я хочу показати вам спільноту. - ---- - -**FastAPI** отримує велику підтримку від спільноти. І я хочу відзначити їхній внесок. - -Це люди, які: - -* [Допомагають іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Створюють пул реквести](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Переглядають пул реквести, [особливо важливо для перекладів](contributing.md#translations){.internal-link target=_blank}. - -Оплески їм. 👏 🙇 - -## Найбільш активні користувачі минулого місяця - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом минулого місяця. ☕ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Експерти - -Ось **експерти FastAPI**. 🤓 - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом *всього часу*. - -Вони зарекомендували себе як експерти, допомагаючи багатьом іншим. ✨ - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Найкращі контрибютори - -Ось **Найкращі контрибютори**. 👷 - -Ці користувачі [створили найбільшу кількість пул реквестів](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} які були *змержені*. - -Вони надали програмний код, документацію, переклади тощо. 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub Contributors</a>. 👷 - -## Найкращі рецензенти - -Ці користувачі є **Найкращими рецензентами**. 🕵️ - -### Рецензенти на переклади - -Я розмовляю лише кількома мовами (і не дуже добре 😅). Отже, рецензенти – це ті, хто має [**повноваження схвалювати переклади**](contributing.md#translations){.internal-link target=_blank} документації. Без них не було б документації кількома іншими мовами. - ---- - -**Найкращі рецензенти** 🕵️ переглянули більшість пул реквестів від інших, забезпечуючи якість коду, документації і особливо **перекладів**. - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## Спонсори - -Це **Спонсори**. 😎 - -Вони підтримують мою роботу з **FastAPI** (та іншими), переважно через <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золоті спонсори - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Срібні спонсори - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзові спонсори - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### Індивідуальні спонсори - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## Про дані - технічні деталі - -Основна мета цієї сторінки – висвітлити зусилля спільноти, щоб допомогти іншим. - -Особливо враховуючи зусилля, які зазвичай менш помітні, а в багатьох випадках більш важкі, як-от допомога іншим із проблемами та перегляд пул реквестів перекладів. - -Дані розраховуються щомісяця, ви можете ознайомитися з <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">вихідним кодом тут</a>. - -Тут я також підкреслюю внески спонсорів. - -Я також залишаю за собою право оновлювати алгоритми підрахунку, види рейтингів, порогові значення тощо (про всяк випадок 🤷). diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md deleted file mode 100644 index 99277b419..000000000 --- a/docs/zh-hant/docs/fastapi-people.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 社群 - -FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 - -## 作者 - -嘿! 👋 - -關於我: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">解答問題: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -我是 **FastAPI** 的作者。你可以在[幫助 FastAPI - 獲得幫助 - 與作者聯繫](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 中閱讀更多相關資訊。 - -...但在這裡,我想向你介紹這個社群。 - ---- - -**FastAPI** 獲得了許多社群的大力支持。我想特別表揚他們的貢獻。 - -這些人包括: - -* [在 GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 -* [建立 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* 審查 Pull Requests,[尤其是翻譯方面的貢獻](contributing.md#translations){.internal-link target=_blank}。 - -讓我們為他們熱烈鼓掌。 👏 🙇 - -## FastAPI 專家 - -這些是在 [GitHub 中幫助其他人解決問題最多的用戶](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🙇 - -他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨ - -/// 提示 - -你也可以成為官方的 FastAPI 專家! - -只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 - -/// - -你可以查看這些期間的 **FastAPI 專家**: - -* [上個月](#fastapi-experts-last-month) 🤓 -* [過去 3 個月](#fastapi-experts-3-months) 😎 -* [過去 6 個月](#fastapi-experts-6-months) 🧐 -* [過去 1 年](#fastapi-experts-1-year) 🧑🔬 -* [**所有時間**](#fastapi-experts-all-time) 🧙 - -### FastAPI 專家 - 上個月 - -上個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🤓 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -### FastAPI 專家 - 過去 3 個月 - -過去三個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 😎 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.three_months_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -### FastAPI 專家 - 過去 6 個月 - -過去六個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧐 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.six_months_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -### FastAPI 專家 - 過去一年 - -過去一年在 [GitHub 中幫助他人解決最多問題的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧑🔬 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.one_year_experts[:20] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -### FastAPI 專家 - 全部時間 - -以下是全部時間的 **FastAPI 專家**。 🤓🤯 - -過去在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧙 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答問題數: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## 主要貢獻者 - -以下是**主要貢獻者**。 👷 - -這些用戶[建立了最多已被**合併**的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 - -他們貢獻了原始碼、文件和翻譯等。 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -還有許多其他的貢獻者(超過一百位),你可以在 <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 貢獻者頁面</a>查看。 👷 - -## 主要翻譯審核者 - -以下是 **主要翻譯審核者**。 🕵️ - -我只會講幾種語言(而且不是很流利 😅),所以審核者[**擁有批准翻譯**](contributing.md#translations){.internal-link target=_blank}文件的權限。沒有他們,就不會有多語言版本的文件。 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## 贊助者 - -以下是**贊助者**。 😎 - -他們主要透過 <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a> 支持我在 **FastAPI**(以及其他項目)上的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌贊助商 - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 銀牌贊助商 - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 銅牌贊助商 - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### 個人贊助商 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## 關於數據 - 技術細節 - -這個頁面的主要目的是突顯社群幫助他人所做的努力 - -特別是那些通常不太顯眼但往往更加艱辛的工作,例如幫助他人解答問題和審查包含翻譯的 Pull Requests。 - -這些數據每月計算一次,你可以在這查看<a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">原始碼</a>。 - -此外,我也特別表揚贊助者的貢獻。 - -我也保留更新演算法、章節、門檻值等的權利(以防萬一 🤷)。 diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md deleted file mode 100644 index 30a75240c..000000000 --- a/docs/zh/docs/fastapi-people.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 社区 - -FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋友。 - -## 创建者 & 维护者 - -嘿! 👋 - -这就是我: - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.maintainers %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div> -{% endfor %} - -</div> -{% endif %} - -我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#_2){.internal-link target=_blank} 阅读有关此内容的更多信息。 - -...但是在这里我想向您展示社区。 - ---- - -**FastAPI** 得到了社区的大力支持。因此我想突出他们的贡献。 - -这些人: - -* [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 -* [创建 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 -* 审核 Pull Requests, 对于 [翻译](contributing.md#_8){.internal-link target=_blank} 尤为重要。 - -向他们致以掌声。 👏 🙇 - -## FastAPI 专家 - -这些用户一直以来致力于 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🙇 - -他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨ - -/// 小提示 - -你也可以成为认可的 FastAPI 专家! - -只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 - -/// - -你可以查看不同时期的 **FastAPI 专家**: - -* [上个月](#fastapi-experts-last-month) 🤓 -* [三个月](#fastapi-experts-3-months) 😎 -* [六个月](#fastapi-experts-6-months) 🧐 -* [一年](#fastapi-experts-1-year) 🧑🔬 -* [**全部时间**](#fastapi-experts-all-time) 🧙 - -## FastAPI 专家 - 上个月 - -这些是在过去一个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🤓 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.last_month_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -### FastAPI 专家 - 三个月 - -这些是在过去三个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 😎 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.three_months_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -### FastAPI 专家 - 六个月 - -这些是在过去六个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧐 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.six_months_experts[:10] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -### FastAPI 专家 - 一年 - -这些是在过去一年中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧑🔬 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.one_year_experts[:20] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## FastAPI 专家 - 全部时间 - -以下是全部时间的 **FastAPI 专家**。 🤓🤯 - -这些用户一直以来致力于 [帮助他人解决 GitHub 的 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🧙 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.experts[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">回答问题数: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## 杰出贡献者 - -以下是 **杰出的贡献者**。 👷 - -这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 - -他们贡献了源代码,文档,翻译等。 📦 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_contributors[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -还有很多别的贡献者(超过100个),你可以在 <a href="https://github.com/fastapi/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷 - -## 杰出翻译审核者 - -以下用户是 **杰出的评审者**。 🕵️ - -我只会说少数几种语言(而且还不是很流利 😅)。所以这些评审者们具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank}。如果没有他们,就不会有多语言文档。 - -{% if people %} -<div class="user-list user-list-center"> -{% for user in people.top_translations_reviewers[:50] %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">审核数: {{ user.count }}</div></div> -{% endfor %} - -</div> -{% endif %} - -## 赞助商 - -以下是 **赞助商** 。😎 - -他们主要通过<a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>支持我在 **FastAPI** (和其他项目)的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌赞助商 - -{% for sponsor in sponsors.gold -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 银牌赞助商 - -{% for sponsor in sponsors.silver -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 铜牌赞助商 - -{% for sponsor in sponsors.bronze -%} -<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> -{% endfor %} -{% endif %} - -{% endif %} - -### 个人赞助 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -<div class="user-list user-list-center"> - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - -<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div> - -{% endif %} -{% endfor %} - -</div> - -{% endfor %} -{% endif %} - -## 关于数据 - 技术细节 - -该页面的目的是突出社区为帮助他人而付出的努力。 - -尤其是那些不引人注目且涉及更困难的任务,例如帮助他人解决问题或者评审翻译 Pull Requests。 - -该数据每月计算一次,您可以阅读 <a href="https://github.com/fastapi/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">源代码</a>。 - -这里也强调了赞助商的贡献。 - -我也保留更新算法,栏目,统计阈值等的权利(以防万一🤷)。 diff --git a/scripts/docs.py b/scripts/docs.py index 1dba4aa0a..f0c51f7a6 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -29,6 +29,7 @@ missing_translation_snippet = """ non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 10e8dc153..0bc4929a4 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -11,6 +11,7 @@ from mkdocs.structure.pages import Page non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", From 0da0814d8a2029b7d2e19043a606c7faea6b02fa Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 17 Aug 2024 21:20:52 +0000 Subject: [PATCH 779/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 17a24a984..91bbb2adc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Translations +* 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). ### Internal From 4f1eb0cd9e571a68fab19eecbdc59cc27aa7e6f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 18 Aug 2024 16:07:03 -0500 Subject: [PATCH 780/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20coverage=20conf?= =?UTF-8?q?ig=20files=20(#12035)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test.yml | 2 +- pyproject.toml | 8 ++++++++ scripts/test-cov-html.sh | 4 ++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a33b6a68a..0458f83ff 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -117,7 +117,7 @@ jobs: - run: ls -la coverage - run: coverage combine coverage - run: coverage report - - run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}" + - run: coverage html --title "Coverage for ${{ github.sha }}" - name: Store coverage HTML uses: actions/upload-artifact@v4 with: diff --git a/pyproject.toml b/pyproject.toml index 8db2d2b2d..bb87be470 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -165,6 +165,7 @@ filterwarnings = [ [tool.coverage.run] parallel = true +data_file = "coverage/.coverage" source = [ "docs_src", "tests", @@ -177,6 +178,13 @@ omit = [ "docs_src/response_model/tutorial003_04_py310.py", ] +[tool.coverage.report] +show_missing = true +sort = "-Cover" + +[tool.coverage.html] +show_contexts = true + [tool.ruff.lint] select = [ "E", # pycodestyle errors diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh index 85aef9601..517ac6422 100755 --- a/scripts/test-cov-html.sh +++ b/scripts/test-cov-html.sh @@ -5,5 +5,5 @@ set -x bash scripts/test.sh ${@} coverage combine -coverage report --show-missing -coverage html --show-contexts +coverage report +coverage html From 6ebaf0efcb38efc6f06f302fe30142071cfd53e1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 18 Aug 2024 21:08:39 +0000 Subject: [PATCH 781/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 91bbb2adc..cb3e8628e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -34,6 +34,7 @@ hide: ### Internal +* 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo). * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). From 0e77481acfc5f548cd053ee36dbd2879651d73c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 18 Aug 2024 18:16:56 -0500 Subject: [PATCH 782/846] =?UTF-8?q?=F0=9F=93=9D=20Move=20the=20Features=20?= =?UTF-8?q?docs=20to=20the=20top=20level=20to=20improve=20the=20main=20pag?= =?UTF-8?q?e=20menu=20(#12036)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d23ddd42f..d0527ca3c 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -102,9 +102,8 @@ plugins: show_symbol_type_toc: true nav: -- FastAPI: - - index.md - - features.md +- FastAPI: index.md +- features.md - Learn: - learn/index.md - python-types.md From 98712b9e09429e0dd514d39c5064cde4f6ae657b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 18 Aug 2024 23:17:21 +0000 Subject: [PATCH 783/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cb3e8628e..bd8580271 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). * 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). From bcd737de33dfb1c1871f86320b12c86158393b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 18 Aug 2024 18:26:14 -0500 Subject: [PATCH 784/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20Asyncer=20mention?= =?UTF-8?q?=20in=20async=20docs=20(#12037)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/async.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 43fd8e70d..7cf4af627 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -369,6 +369,8 @@ In particular, you can directly use <a href="https://anyio.readthedocs.io/en/sta And even if you were not using FastAPI, you could also write your own async applications with <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> to be highly compatible and get its benefits (e.g. *structured concurrency*). +I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: <a href="https://asyncer.tiangolo.com/" class="external-link" target="_blank">Asyncer</a>. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code. + ### Other forms of asynchronous code This style of using `async` and `await` is relatively new in the language. From ae97785ded0dfb5128cbd6bb9542eaf0fc44f903 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 18 Aug 2024 23:26:36 +0000 Subject: [PATCH 785/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bd8580271..570e7e9db 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). From f0866bc2050552621566ca0c0fd111936ac36918 Mon Sep 17 00:00:00 2001 From: xuvjso <xuvjso@gmail.com> Date: Tue, 20 Aug 2024 01:35:03 +0800 Subject: [PATCH 786/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20docs=20about=20?= =?UTF-8?q?dependencies=20with=20yield=20(#12028)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-with-yield.md | 269 +++++++++++++----- 1 file changed, 197 insertions(+), 72 deletions(-) diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index beca95d45..6058f7878 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -1,12 +1,12 @@ # 使用yield的依赖项 -FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出”("exit"),“清理”("cleanup"),“拆卸”("teardown"),“关闭”("close"),“上下文管理器”("context managers")。 ...'>额外步骤</abbr>的依赖项. +FastAPI支持在完成后执行一些<abbr title='有时也被称为"退出"("exit"),"清理"("cleanup"),"拆卸"("teardown"),"关闭"("close"),"上下文管理器"("context managers")。 ...'>额外步骤</abbr>的依赖项. -为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 +为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。 -/// tip | "提示" +/// tip | 提示 -确保只使用一次 `yield` 。 +确保在每个依赖中只使用一次 `yield`。 /// @@ -25,7 +25,7 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” ## 使用 `yield` 的数据库依赖项 -例如,您可以使用这种方式创建一个数据库会话,并在完成后关闭它。 +例如,你可以使用这种方式创建一个数据库会话,并在完成后关闭它。 在发送响应之前,只会执行 `yield` 语句及之前的代码: @@ -33,44 +33,44 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” {!../../../docs_src/dependencies/tutorial007.py!} ``` -生成的值会注入到*路径操作*和其他依赖项中: +生成的值会注入到 *路由函数* 和其他依赖项中: ```Python hl_lines="4" {!../../../docs_src/dependencies/tutorial007.py!} ``` -"yield"语句后面的代码会在发送响应后执行:: +`yield` 语句后面的代码会在创建响应后,发送响应前执行: ```Python hl_lines="5-6" {!../../../docs_src/dependencies/tutorial007.py!} ``` -/// tip | "提示" +/// tip | 提示 -您可以使用 `async` 或普通函数。 +你可以使用 `async` 或普通函数。 -**FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。 +**FastAPI** 会像处理普通依赖一样,对每个依赖做正确的处理。 /// -## 同时包含了 `yield` 和 `try` 的依赖项 +## 包含 `yield` 和 `try` 的依赖项 -如果在带有 `yield` 的依赖关系中使用 `try` 代码块,就会收到使用依赖关系时抛出的任何异常。 +如果在包含 `yield` 的依赖中使用 `try` 代码块,你会捕获到使用依赖时抛出的任何异常。 -例如,如果中间某个代码在另一个依赖中或在*路径操作*中使数据库事务 "回滚 "或产生任何其他错误,您就会在依赖中收到异常。 +例如,如果某段代码在另一个依赖中或在 *路由函数* 中使数据库事务"回滚"或产生任何其他错误,你将会在依赖中捕获到异常。 -因此,你可以使用 `except SomeException` 在依赖关系中查找特定的异常。 +因此,你可以使用 `except SomeException` 在依赖中捕获特定的异常。 -同样,您也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。 +同样,你也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。 ```Python hl_lines="3 5" {!../../../docs_src/dependencies/tutorial007.py!} ``` -## 使用`yield`的子依赖项 +## 使用 `yield` 的子依赖项 -你可以拥有任意大小和形状的子依赖和子依赖的“树”,而且它们中的任何一个或所有的都可以使用`yield`。 +你可以声明任意数量和层级的树状依赖,而且它们中的任何一个或所有的都可以使用 `yield`。 -**FastAPI** 会确保每个带有`yield`的依赖中的“退出代码”按正确顺序运行。 +**FastAPI** 会确保每个带有 `yield` 的依赖中的"退出代码"按正确顺序运行。 例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。 @@ -92,9 +92,9 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | 提示 -如果可能,请尽量使用“ Annotated”版本。 +如果可以,请尽量使用 `Annotated` 版本。 /// @@ -104,11 +104,11 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” //// -所有这些依赖都可以使用`yield`。 +所有这些依赖都可以使用 `yield`。 -在这种情况下,`dependency_c` 在执行其退出代码时需要`dependency_b`(此处称为 `dep_b`)的值仍然可用。 +在这种情况下,`dependency_c` 在执行其退出代码时需要 `dependency_b`(此处称为 `dep_b`)的值仍然可用。 -而`dependency_b` 反过来则需要`dependency_a`(此处称为 `dep_a`)的值在其退出代码中可用。 +而 `dependency_b` 反过来则需要 `dependency_a`(此处称为 `dep_a` )的值在其退出代码中可用。 //// tab | Python 3.9+ @@ -128,9 +128,9 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | 提示 -如果可能,请尽量使用“ Annotated”版本。 +如果可以,请尽量使用 `Annotated` 版本。 /// @@ -140,9 +140,9 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” //// -同样,你可以有混合了`yield`和`return`的依赖。 +同样,你可以混合使用带有 `yield` 或 `return` 的依赖。 -你也可以有一个单一的依赖需要多个其他带有`yield`的依赖,等等。 +你也可以声明一个依赖于多个带有 `yield` 的依赖,等等。 你可以拥有任何你想要的依赖组合。 @@ -156,33 +156,129 @@ FastAPI支持在完成后执行一些<abbr title='有时也被称为“退出” /// -## 使用 `yield` 和 `HTTPException` 的依赖项 +## 包含 `yield` 和 `HTTPException` 的依赖项 -您看到可以使用带有 `yield` 的依赖项,并且具有捕获异常的 `try` 块。 +你可以使用带有 `yield` 的依赖项,并且可以包含 `try` 代码块用于捕获异常。 -在 `yield` 后抛出 `HTTPException` 或类似的异常是很诱人的,但是**这不起作用**。 +同样,你可以在 `yield` 之后的退出代码中抛出一个 `HTTPException` 或类似的异常。 -带有`yield`的依赖中的退出代码在响应发送之后执行,因此[异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}已经运行过。没有任何东西可以捕获退出代码(在`yield`之后)中的依赖抛出的异常。 +/// tip | 提示 -所以,如果在`yield`之后抛出`HTTPException`,默认(或任何自定义)异常处理程序捕获`HTTPException`并返回HTTP 400响应的机制将不再能够捕获该异常。 +这是一种相对高级的技巧,在大多数情况下你并不需要使用它,因为你可以在其他代码中抛出异常(包括 `HTTPException` ),例如在 *路由函数* 中。 -这就是允许在依赖中设置的任何东西(例如数据库会话(DB session))可以被后台任务使用的原因。 +但是如果你需要,你也可以在依赖项中做到这一点。🤓 -后台任务在响应发送之后运行。因此,无法触发`HTTPException`,因为甚至没有办法更改*已发送*的响应。 +/// + +//// 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 | 提示 + +如果可以,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="16-20 29" +{!> ../../../docs_src/dependencies/tutorial008b.py!} +``` + +//// -但如果后台任务产生了数据库错误,至少你可以在带有`yield`的依赖中回滚或清理关闭会话,并且可能记录错误或将其报告给远程跟踪系统。 +你还可以创建一个 [自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 用于捕获异常(同时也可以抛出另一个 `HTTPException`)。 -如果你知道某些代码可能会引发异常,那就做最“Pythonic”的事情,就是在代码的那部分添加一个`try`块。 +## 包含 `yield` 和 `except` 的依赖项 -如果你有自定义异常,希望在返回响应之前处理,并且可能修改响应甚至触发`HTTPException`,可以创建[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。 +如果你在包含 `yield` 的依赖项中使用 `except` 捕获了一个异常,然后你没有重新抛出该异常(或抛出一个新异常),与在普通的Python代码中相同,FastAPI不会注意到发生了异常。 -/// tip +//// 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!} +``` -在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。 +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 提示 + +如果可以,请尽量使用 `Annotated` 版本。 /// -执行的顺序大致如下图所示。时间从上到下流动。每列都是相互交互或执行代码的其中一部分。 +```Python hl_lines="13-14" +{!> ../../../docs_src/dependencies/tutorial008c.py!} +``` + +//// + +在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱 + +### 在包含 `yield` 和 `except` 的依赖项中一定要 `raise` + +如果你在使用 `yield` 的依赖项中捕获到了一个异常,你应该再次抛出捕获到的异常,除非你抛出 `HTTPException` 或类似的其他异常, + +你可以使用 `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 | 提示 + +如果可以,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial008d.py!} +``` + +//// + +现在客户端同样会得到 *HTTP 500 Internal Server Error* 响应,但是服务器日志会记录下我们自定义的 `InternalError`。 + +## 使用 `yield` 的依赖项的执行 + +执行顺序大致如下时序图所示。时间轴从上到下,每一列都代表交互或者代码执行的一部分。 ```mermaid sequenceDiagram @@ -193,60 +289,89 @@ participant dep as Dep with yield participant operation as Path Operation participant tasks as Background tasks - Note over client,tasks: Can raise exception for dependency, handled after response is sent - Note over client,operation: Can raise HTTPException and can change the response + Note over client,operation: Can raise exceptions, including HTTPException client ->> dep: Start request Note over dep: Run code up to yield - opt raise - dep -->> handler: Raise HTTPException + opt raise Exception + dep -->> handler: Raise Exception handler -->> client: HTTP error response - dep -->> dep: Raise other exception end dep ->> operation: Run dependency, e.g. DB session opt raise - operation -->> dep: Raise HTTPException - dep -->> handler: Auto forward exception + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + end handler -->> client: HTTP error response - operation -->> dep: Raise other exception - dep -->> handler: Auto forward exception end + operation ->> client: Return response to client Note over client,operation: Response is already sent, can't change it anymore opt Tasks operation -->> tasks: Send background tasks end opt Raise other exception - tasks -->> dep: Raise other exception - end - Note over dep: After yield - opt Handle other exception - dep -->> dep: Handle exception, can't change response. E.g. close DB session. + tasks -->> tasks: Handle exceptions in the background task code end ``` -/// info +/// info | 说明 -只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 +只会向客户端发送 **一次响应** ,可能是一个错误响应,也可能是来自 *路由函数* 的响应。 在发送了其中一个响应之后,就无法再发送其他响应了。 /// -/// tip +/// tip | 提示 + +这个时序图展示了 `HTTPException`,除此之外你也可以抛出任何你在使用 `yield` 的依赖项中或者[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}中捕获的异常。 + +如果你引发任何异常,它将传递给使用 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下你应当从使用 `yield` 的依赖项中重新抛出捕获的异常或者一个新的异常来确保它会被正确的处理。 + +/// + +## 包含 `yield`, `HTTPException`, `except` 的依赖项和后台任务 + +/// warning | 注意 + +你大概率不需要了解这些技术细节,可以跳过这一章节继续阅读后续的内容。 + +如果你使用的FastAPI的版本早于0.106.0,并且在使用后台任务中使用了包含 `yield` 的依赖项中的资源,那么这些细节会对你有一些用处。 + +/// + +### 包含 `yield` 和 `except` 的依赖项的技术细节 + +在FastAPI 0.110.0版本之前,如果使用了一个包含 `yield` 的依赖项,你在依赖项中使用 `except` 捕获了一个异常,但是你没有再次抛出该异常,这个异常会被自动抛出/转发到异常处理器或者内部服务错误处理器。 + +### 后台任务和使用 `yield` 的依赖项的技术细节 + +在FastAPI 0.106.0版本之前,在 `yield` 后面抛出异常是不可行的,因为 `yield` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。 -这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 +这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。 -如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 +然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。 + +/// tip | 提示 + +除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。 + +这样也会让你的代码更加简洁。 /// +如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。 + +例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。 + ## 上下文管理器 -### 什么是“上下文管理器” +### 什么是"上下文管理器" -“上下文管理器”是您可以在`with`语句中使用的任何Python对象。 +"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。 -例如,<a href="https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#reading-and-writing-files" class="external-link" target="_blank">您可以使用`with`读取文件</a>: +例如,<a href="https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#reading-and-writing-files" class="external-link" target="_blank">你可以使用`with`读取文件</a>: ```Python with open("./somefile.txt") as f: @@ -254,38 +379,38 @@ with open("./somefile.txt") as f: print(contents) ``` -在底层,`open("./somefile.txt")`创建了一个被称为“上下文管理器”的对象。 +在底层,`open("./somefile.txt")`创建了一个被称为"上下文管理器"的对象。 -当`with`块结束时,它会确保关闭文件,即使发生了异常也是如此。 +当 `with` 代码块结束时,它会确保关闭文件,即使发生了异常也是如此。 -当你使用`yield`创建一个依赖项时,**FastAPI**会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 +当你使用 `yield` 创建一个依赖项时,**FastAPI** 会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 -### 在依赖项中使用带有`yield`的上下文管理器 +### 在使用 `yield` 的依赖项中使用上下文管理器 -/// warning +/// warning | 注意 -这是一个更为“高级”的想法。 +这是一个更为"高级"的想法。 -如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 +如果你刚开始使用 **FastAPI** ,你可以暂时可以跳过它。 /// 在Python中,你可以通过<a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">创建一个带有`__enter__()`和`__exit__()`方法的类</a>来创建上下文管理器。 -你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。 +你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们: ```Python hl_lines="1-9 13" {!../../../docs_src/dependencies/tutorial010.py!} ``` -/// tip +/// tip | 提示 另一种创建上下文管理器的方法是: * <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>或者 * <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a> -使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 +使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 From 63ae0f1070ba1df314b55e2454ec5e356725bd16 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 19 Aug 2024 17:35:25 +0000 Subject: [PATCH 787/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 570e7e9db..3b41fa2ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From 6ba8407ff3acc0e2b8792c35a363803f08c78971 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Mon, 19 Aug 2024 13:15:21 -0500 Subject: [PATCH 788/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20Spanish=20trans?= =?UTF-8?q?lation=20docs=20for=20consistency=20(#12044)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/advanced/additional-status-codes.md | 4 ++-- docs/es/docs/advanced/index.md | 2 +- .../path-operation-advanced-configuration.md | 4 ++-- docs/es/docs/advanced/response-directly.md | 4 ++-- docs/es/docs/advanced/response-headers.md | 2 +- docs/es/docs/advanced/security/index.md | 2 +- docs/es/docs/async.md | 8 ++++---- docs/es/docs/deployment/versions.md | 4 ++-- docs/es/docs/features.md | 2 +- docs/es/docs/how-to/graphql.md | 4 ++-- docs/es/docs/python-types.md | 6 +++--- docs/es/docs/tutorial/cookie-params.md | 16 ++++++++-------- docs/es/docs/tutorial/first-steps.md | 12 ++++++------ docs/es/docs/tutorial/path-params.md | 16 ++++++++-------- docs/es/docs/tutorial/query-params.md | 6 +++--- 15 files changed, 46 insertions(+), 46 deletions(-) diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index f40fad03c..664604c59 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -18,7 +18,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -/// warning | "Advertencia" +/// warning | Advertencia Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. @@ -28,7 +28,7 @@ Asegúrate de que la respuesta tenga los datos que quieras, y que los valores se /// -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También podrías utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md index 88ef8e19f..10a1ff0d5 100644 --- a/docs/es/docs/advanced/index.md +++ b/docs/es/docs/advanced/index.md @@ -6,7 +6,7 @@ El [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_bl En las secciones siguientes verás otras opciones, configuraciones, y características adicionales. -/// tip +/// tip | Consejo Las próximas secciones **no son necesariamente "avanzadas"**. diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 9e8714fe4..18f96213f 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -26,13 +26,13 @@ Deberías hacerlo después de adicionar todas tus *operaciones de path*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -/// tip | "Consejo" +/// tip | Consejo Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. /// -/// warning | "Advertencia" +/// warning | Advertencia Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 7ce5bddca..4eeab3fd0 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizado De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma. -/// tip | "Consejo" +/// tip | Consejo `JSONResponse` en sí misma es una subclase de `Response`. @@ -38,7 +38,7 @@ Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos ante {!../../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También puedes usar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md index 414b145fc..c3aa20993 100644 --- a/docs/es/docs/advanced/response-headers.md +++ b/docs/es/docs/advanced/response-headers.md @@ -29,7 +29,7 @@ Crea un response tal como se describe en [Retornar una respuesta directamente](r {!../../../docs_src/response_headers/tutorial001.py!} ``` -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md index 7fa8047e9..92de67d6a 100644 --- a/docs/es/docs/advanced/security/index.md +++ b/docs/es/docs/advanced/security/index.md @@ -4,7 +4,7 @@ Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. -/// tip +/// tip | Consejo Las siguientes secciones **no necesariamente son "avanzadas"**. diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 193d24270..5ab2ff9a4 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "Nota" +/// note | Nota Solo puedes usar `await` dentro de funciones creadas con `async def`. @@ -138,7 +138,7 @@ Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨. <img src="https://fastapi.tiangolo.com/img/async/concurrent-burgers/concurrent-burgers-07.png" alt="illustration"> -/// info +/// info | Información Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 @@ -204,7 +204,7 @@ Sólo las comes y listo 🍔 ⏹. No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞. -/// info +/// info | Información Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨 @@ -396,7 +396,7 @@ Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que te ## Detalles muy técnicos -/// warning | "Advertencia" +/// warning | Advertencia Probablemente puedas saltarte esto. diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md index 7d09a2739..74243da89 100644 --- a/docs/es/docs/deployment/versions.md +++ b/docs/es/docs/deployment/versions.md @@ -42,7 +42,7 @@ Siguiendo las convenciones de *Semantic Versioning*, cualquier versión por deba FastAPI también sigue la convención de que cualquier cambio hecho en una <abbr title="versiones de parche">"PATCH" version</abbr> es para solucionar errores y <abbr title="cambios que no rompan funcionalidades o compatibilidad">*non-breaking changes*</abbr>. -/// tip +/// tip | Consejo El <abbr title="parche">"PATCH"</abbr> es el último número, por ejemplo, en `0.2.3`, la <abbr title="versiones de parche">PATCH version</abbr> es `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 En versiones <abbr title="versiones menores">"MINOR"</abbr> son añadidas nuevas características y posibles <abbr title="Cambios que rompen posibles funcionalidades o compatibilidad">breaking changes</abbr>. -/// tip +/// tip | Consejo La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la <abbr title="versión menor">"MINOR" version</abbr> es `2`. diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index 3c610f8f1..b75918dff 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -63,7 +63,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info +/// info | Información `**second_user_data` significa: diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md index d75af7d81..590c2e828 100644 --- a/docs/es/docs/how-to/graphql.md +++ b/docs/es/docs/how-to/graphql.md @@ -4,7 +4,7 @@ Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar c Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. -/// tip +/// tip | Consejo **GraphQL** resuelve algunos casos de uso específicos. @@ -49,7 +49,7 @@ Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** -/// tip +/// tip | Consejo Si necesitas GraphQL, te recomendaría revisar <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index fce434483..4015dbb05 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -12,7 +12,7 @@ Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. -/// note | "Nota" +/// note | Nota Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. @@ -256,7 +256,7 @@ Tomado de la documentación oficial de Pydantic: {!../../../docs_src/python_types/tutorial010.py!} ``` -/// info | "Información" +/// info | Información Para aprender más sobre <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic mira su documentación</a>. @@ -288,7 +288,7 @@ Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. -/// info | "Información" +/// info | Información Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">la "cheat sheet" de `mypy`</a>. diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 27ba8ed57..3eaea31f9 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -32,9 +32,9 @@ Primero importa `Cookie`: //// tab | Python 3.10+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -46,9 +46,9 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -90,9 +90,9 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.10+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -104,9 +104,9 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index affdfebff..8d8909b97 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload </div> -/// note | "Nota" +/// note | Nota El comando `uvicorn main:app` se refiere a: @@ -139,7 +139,7 @@ También podrías usarlo para generar código automáticamente, para los cliente `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos `FastAPI` es una clase que hereda directamente de `Starlette`. @@ -205,7 +205,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Información" +/// info | Información Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". @@ -259,7 +259,7 @@ El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo * el path `/` * usando una <abbr title="an HTTP GET method">operación <code>get</code></abbr> -/// info | "Información sobre `@decorator`" +/// info | Información sobre `@decorator` Esa sintaxis `@algo` se llama un "decorador" en Python. @@ -286,7 +286,7 @@ y las más exóticas: * `@app.patch()` * `@app.trace()` -/// tip | "Consejo" +/// tip | Consejo Tienes la libertad de usar cada operación (método de HTTP) como quieras. @@ -324,7 +324,7 @@ También podrías definirla como una función estándar en lugar de `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "Nota" +/// note | Nota Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 73bd586f1..e09e0381f 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota En este caso, `item_id` es declarado como un `int`. -/// check | "Revisa" +/// check | Revisa Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. @@ -38,7 +38,7 @@ Si corres este ejemplo y abres tu navegador en <a href="http://127.0.0.1:8000/it {"item_id":3} ``` -/// check | "Revisa" +/// check | Revisa Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`. @@ -69,7 +69,7 @@ debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es El mismo error aparecería si pasaras un `float` en vez de un `int` como en: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> -/// check | "Revisa" +/// check | Revisa Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. @@ -85,7 +85,7 @@ Cuando abras tu navegador en <a href="http://127.0.0.1:8000/docs" class="externa <img src="/img/tutorial/path-params/image01.png"> -/// check | "Revisa" +/// check | Revisa Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) @@ -143,13 +143,13 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib {!../../../docs_src/path_params/tutorial005.py!} ``` -/// info | "Información" +/// info | Información Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4. /// -/// tip | "Consejo" +/// tip | Consejo Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Técnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning. @@ -189,7 +189,7 @@ Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value` {!../../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "Consejo" +/// tip | Consejo También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. @@ -246,7 +246,7 @@ Entonces lo puedes usar con: {!../../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "Consejo" +/// tip | Consejo Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 52a3e66a4..6f88fd617 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -69,13 +69,13 @@ Del mismo modo puedes declarar parámetros de query opcionales definiendo el val En este caso el parámetro de la función `q` será opcional y será `None` por defecto. -/// check | "Revisa" +/// check | Revisa También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. /// -/// note | "Nota" +/// note | Nota FastAPI sabrá que `q` es opcional por el `= None`. @@ -199,7 +199,7 @@ En este caso hay 3 parámetros de query: * `skip`, un `int` con un valor por defecto de `0`. * `limit`, un `int` opcional. -/// tip | "Consejo" +/// tip | Consejo También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. From e8322228b42c11299d1df75bf3586a3a675f72d1 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 19 Aug 2024 18:15:49 +0000 Subject: [PATCH 789/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3b41fa2ad..646060fea 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From f4dfbae90396c1eed349fa96e1770874fe482ae1 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 19 Aug 2024 19:40:31 -0500 Subject: [PATCH 790/846] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12046)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.6.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.4.0...v4.6.0) - https://github.com/charliermarsh/ruff-pre-commit → https://github.com/astral-sh/ruff-pre-commit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1ed005657..7532f21b5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.6.0 hooks: - id: check-added-large-files - id: check-toml @@ -13,7 +13,7 @@ repos: - --unsafe - id: end-of-file-fixer - id: trailing-whitespace -- repo: https://github.com/charliermarsh/ruff-pre-commit +- repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.6.1 hooks: - id: ruff From 2d34086b70a1026aeb4974ffcf92041cd69e1ece Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Tue, 20 Aug 2024 00:40:55 +0000 Subject: [PATCH 791/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 646060fea..f562ba06e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12046](https://github.com/fastapi/fastapi/pull/12046) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo). * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). From 34e6e63fb2ca05a5929bc2d151b4e45194ed87a0 Mon Sep 17 00:00:00 2001 From: Yuki Watanabe <ukwhatn@gmail.com> Date: Thu, 22 Aug 2024 01:55:16 +0900 Subject: [PATCH 792/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/learn/index.md`=20(#11592)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/ja/docs/learn/index.md diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md new file mode 100644 index 000000000..2f24c670a --- /dev/null +++ b/docs/ja/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学習 + +ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。 + +これは、FastAPIを学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎 From 2fe05762b2672959d754ee869a11efbf9cdd6e97 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 21 Aug 2024 16:55:38 +0000 Subject: [PATCH 793/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f562ba06e..a9fcd1383 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). From 38ff43b690df0d5a8ce7e4069750696eca323c23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= <joaopedroph09@gmail.com> Date: Wed, 21 Aug 2024 13:56:50 -0300 Subject: [PATCH 794/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/request=5Ffile.md`=20(#12?= =?UTF-8?q?018)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/request_files.md | 418 +++++++++++++++++++++++++ 1 file changed, 418 insertions(+) create mode 100644 docs/pt/docs/tutorial/request_files.md diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md new file mode 100644 index 000000000..60e4ecb26 --- /dev/null +++ b/docs/pt/docs/tutorial/request_files.md @@ -0,0 +1,418 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados para o cliente utilizando `File`. + +/// info + +Para receber arquivos compartilhados, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. + +E.g. `pip install python-multipart`. + +Isso se deve por que arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` do `fastapi`: + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +## Defina os parâmetros de `File` + +Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`,`Path`, `File`, entre outros, do `fastapi`, essas são na verdade funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar o corpo de arquivos, você precisa utilizar `File`, do contrário os parâmetros seriam interpretados como parâmetros de consulta ou corpo (JSON) da requisição. + +/// + +Os arquivos serão enviados como "form data". + +Se você declarar o tipo do seu parâmetro na sua *função de operação de rota* como `bytes`, o **FastAPI** irá ler o arquivo para você e você receberá o conteúdo como `bytes`. + +Lembre-se que isso significa que o conteúdo inteiro será armazenado em memória. Isso funciona bem para arquivos pequenos. + +Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. + +## Parâmetros de arquivo com `UploadFile` + +Defina um parâmetro de arquivo com o tipo `UploadFile` + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +Utilizando `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar `File()` como o valor padrão do parâmetro. +* A classe utiliza um arquivo em "spool": + * Um arquivo guardado em memória até um tamanho máximo, depois desse limite ele é guardado em disco. +* Isso significa que a classe funciona bem com arquivos grandes como imagens, vídeos, binários extensos, etc. Sem consumir toda a memória. +* Você pode obter metadados do arquivo enviado. +* Ela possui uma interface <a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">semelhante a arquivos</a> `async`. +* Ela expõe um objeto python <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> que você pode repassar para bibliotecas que esperam um objeto com comportamento de arquivo. + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma string (`str`) com o nome original do arquivo enviado (e.g. `myimage.jpg`). +* `content-type`: Uma `str` com o tipo do conteúdo (tipo MIME / media) (e.g. `image/jpeg`). +* `file`: Um objeto do tipo <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> (um objeto <a href="https://docs.python.org/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a>). O arquivo propriamente dito que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto "file-like". + +`UploadFile` tem os seguintes métodos `async`. Todos eles chamam os métodos de arquivos por baixo dos panos (usando o objeto `SpooledTemporaryFile` interno). + +* `write(data)`: escreve dados (`data`) em `str` ou `bytes` no arquivo. +* `read(size)`: Lê um número de bytes/caracteres de acordo com a quantidade `size` (`int`). +* `seek(offset)`: Navega para o byte na posição `offset` (`int`) do arquivo. + * E.g., `await myfile.seek(0)` navegaria para o ínicio do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e depois precisar ler os conteúdos do arquivo de novo. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são assíncronos (`async`) você precisa esperar ("await") por eles. + +Por exemplo, dentro de uma *função de operação de rota* assíncrona você pode obter os conteúdos com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma *função de operação de rota* definida normalmente com `def`, você pode acessar `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes técnicos do `async` + +Quando você utiliza métodos assíncronos, o **FastAPI** executa os métodos do arquivo em uma threadpool e espera por eles. + +/// + +/// note | Detalhes técnicos do Starlette + +O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas funcionalidades necessárias para ser compatível com o **Pydantic** + +/// + +## O que é "Form Data" + +A forma como formulários HTML(`<form></form>`) enviam dados para o servidor normalmente utilizam uma codificação "especial" para esses dados, que é diferente do JSON. + +O **FastAPI** garante que os dados serão lidos da forma correta, em vez do JSON. + +/// note | Detalhes Técnicos + +Dados vindos de formulários geralmente tem a codificação com o "media type" `application/x-www-form-urlencoded` quando estes não incluem arquivos. + +Mas quando os dados incluem arquivos, eles são codificados como `multipart/form-data`. Se você utilizar `File`, **FastAPI** saberá que deve receber os arquivos da parte correta do corpo da requisição. + +Se você quer ler mais sobre essas codificações e campos de formulário, veja a documentação online da <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> sobre <code> POST</code> </a>. + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que seriam recebidos como JSON junto desses parâmetros, por que a codificação do corpo da requisição será `multipart/form-data` em vez de `application/json`. + +Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. + +/// + +## Arquivo de upload opcional + +Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: + +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// + +## `UploadFile` com Metadados Adicionais + +Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` + +//// + +## Envio de Múltiplos Arquivos + +É possível enviar múltiplos arquivos ao mesmo tmepo. + +Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// + +Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, + +/// note | Detalhes Técnicos + +Você também poderia utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como um facilitador para você, desenvolvedor. Mas a maior parte das respostas vem diretamente do Starlette. + +/// + +### Enviando Múltiplos Arquivos com Metadados Adicionais + +E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` + +//// + +## Recapitulando + +Use `File`, `bytes` e `UploadFile` para declarar arquivos que serão enviados na requisição, enviados como dados do formulário. From 4f3381a95eee1c1a76630d0a232cdd4553166d2b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 21 Aug 2024 16:58:20 +0000 Subject: [PATCH 795/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a9fcd1383..12f1f50cd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). From 705659bb2277633e75269de9bac9d84cc3c15ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 21 Aug 2024 19:47:31 -0500 Subject: [PATCH 796/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20docs=20about=20Env?= =?UTF-8?q?ironment=20Variables=20and=20Virtual=20Environments=20(#12054)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + docs/en/docs/advanced/settings.md | 126 +-- docs/en/docs/advanced/templates.md | 2 +- docs/en/docs/advanced/websockets.md | 2 +- docs/en/docs/contributing.md | 138 +-- docs/en/docs/deployment/manually.md | 4 +- docs/en/docs/deployment/server-workers.md | 2 + docs/en/docs/environment-variables.md | 300 +++++++ docs/en/docs/index.md | 2 + docs/en/docs/tutorial/index.md | 8 +- docs/en/docs/tutorial/request-files.md | 6 +- .../docs/tutorial/request-forms-and-files.md | 6 +- docs/en/docs/tutorial/request-forms.md | 6 +- docs/en/docs/tutorial/response-model.md | 13 +- docs/en/docs/tutorial/security/first-steps.md | 8 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 6 +- docs/en/docs/tutorial/sql-databases.md | 4 +- docs/en/docs/tutorial/testing.md | 10 +- docs/en/docs/virtual-environments.md | 844 ++++++++++++++++++ docs/en/mkdocs.yml | 2 + 20 files changed, 1228 insertions(+), 263 deletions(-) create mode 100644 docs/en/docs/environment-variables.md create mode 100644 docs/en/docs/virtual-environments.md diff --git a/README.md b/README.md index b00ef6ba9..889a89ed7 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,8 @@ FastAPI stands on the shoulders of giants: ## Installation +Create and activate a <a href="https://fastapi.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install FastAPI: + <div class="termy"> ```console diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index b78f83953..22bf7de20 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -6,135 +6,17 @@ Most of these settings are variable (can change), like database URLs. And many c For this reason it's common to provide them in environment variables that are read by the application. -## Environment Variables - -/// tip - -If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. - -/// - -An <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">environment variable</a> (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). - -You can create and use environment variables in the shell, without needing Python: - -//// tab | Linux, macOS, Windows Bash - -<div class="termy"> - -```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 -``` - -</div> - -//// - -//// tab | Windows PowerShell - -<div class="termy"> - -```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 -``` - -</div> - -//// - -### Read env vars in Python - -You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python. - -For example you could have a file `main.py` with: - -```Python hl_lines="3" -import os - -name = os.getenv("MY_NAME", "World") -print(f"Hello {name} from Python") -``` - -/// tip - -The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return. - -If not provided, it's `None` by default, here we provide `"World"` as the default value to use. - -/// - -Then you could call that Python program: - -<div class="termy"> - -```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 -``` - -</div> - -As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings. - -You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration. - -To do that, create it right before the program itself, on the same line: - -<div class="termy"> - -```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 -``` - -</div> - /// tip -You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>. +To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}. /// -### Types and validation +## Types and validation These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). -That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code. +That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code. ## Pydantic `Settings` @@ -142,7 +24,7 @@ Fortunately, Pydantic provides a great utility to handle these settings coming f ### Install `pydantic-settings` -First, install the `pydantic-settings` package: +First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package: <div class="termy"> diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 43731ec36..416540ba4 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -8,7 +8,7 @@ There are utilities to configure it easily that you can use directly in your **F ## Install dependencies -Install `jinja2`: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`: <div class="termy"> diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 9655714b0..44c6c7428 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -4,7 +4,7 @@ You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets ## Install `WebSockets` -First you need to install `WebSockets`: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `websockets`: <div class="termy"> diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 63e1f359a..91d5724a8 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -6,117 +6,13 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- If you already cloned the <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">fastapi repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment. -### Virtual environment with `venv` +### Virtual environment -You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is): - -<div class="termy"> - -```console -$ python -m venv env -``` - -</div> - -That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. - -### Activate the environment - -Activate the new environment with: - -//// tab | Linux, macOS - -<div class="termy"> - -```console -$ source ./env/bin/activate -``` - -</div> - -//// - -//// tab | Windows PowerShell - -<div class="termy"> - -```console -$ .\env\Scripts\Activate.ps1 -``` - -</div> - -//// - -//// tab | Windows Bash - -Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): - -<div class="termy"> - -```console -$ source ./env/Scripts/activate -``` - -</div> - -//// - -To check it worked, use: - -//// tab | Linux, macOS, Windows Bash - -<div class="termy"> - -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -</div> - -//// - -//// tab | Windows PowerShell - -<div class="termy"> - -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -</div> - -//// - -If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 - -Make sure you have the latest pip version on your local environment to avoid errors on the next steps: - -<div class="termy"> - -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -</div> - -/// tip - -Every time you install a new package with `pip` under that environment, activate the environment again. - -This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. - -/// +Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`. ### Install requirements using pip -After activating the environment as described above: +After activating the environment, install the required packages: <div class="termy"> @@ -160,7 +56,19 @@ $ bash scripts/format.sh It will also auto-sort all your imports. -For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`. +## Tests + +There is a script that you can run locally to test all the code and generate coverage reports in HTML: + +<div class="termy"> + +```console +$ bash scripts/test-cov-html.sh +``` + +</div> + +This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. ## Docs @@ -482,17 +390,3 @@ Serving at: http://127.0.0.1:8008 * Search for such links in the translated document using the regex `#[^# ]`. * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. - -## Tests - -There is a script that you can run locally to test all the code and generate coverage reports in HTML: - -<div class="termy"> - -```console -$ bash scripts/test-cov-html.sh -``` - -</div> - -This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index d70c5e48b..3324a7503 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -82,7 +82,9 @@ When referring to the remote machine, it's common to call it **server**, but als When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command. -But you can also install an ASGI server manually: +But you can also install an ASGI server manually. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server: //// tab | Uvicorn diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 433371b9d..efde5f3a1 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -39,6 +39,8 @@ And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of ## Install Gunicorn and Uvicorn +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `gunicorn`: + <div class="termy"> ```console diff --git a/docs/en/docs/environment-variables.md b/docs/en/docs/environment-variables.md new file mode 100644 index 000000000..78e82d5af --- /dev/null +++ b/docs/en/docs/environment-variables.md @@ -0,0 +1,300 @@ +# Environment Variables + +/// tip + +If you already know what "environment variables" are and how to use them, feel free to skip this. + +/// + +An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well). + +Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc. + +## Create and Use Env Vars + +You can **create** and use environment variables in the **shell (terminal)**, without needing Python: + +//// tab | Linux, macOS, Windows Bash + +<div class="termy"> + +```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 +``` + +</div> + +//// + +//// tab | Windows PowerShell + +<div class="termy"> + +```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 +``` + +</div> + +//// + +## Read env vars in Python + +You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**. + +For example you could have a file `main.py` with: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return. + +If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +/// + +Then you could call that Python program: + +//// tab | Linux, macOS, Windows Bash + +<div class="termy"> + +```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 +``` + +</div> + +//// + +//// tab | Windows PowerShell + +<div class="termy"> + +```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 +``` + +</div> + +//// + +As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**. + +You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration. + +To do that, create it right before the program itself, on the same line: + +<div class="termy"> + +```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 +``` + +</div> + +/// tip + +You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>. + +/// + +## Types and Validation + +These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). + +That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code. + +You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Environment Variable + +There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run. + +The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows. + +For example, the `PATH` environment variable could look like this: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +This means that the system should look for programs in the directories: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +This means that the system should look for programs in the directories: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable. + +For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list. + +If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**. + +### Installing Python and Updating the `PATH` + +When you install Python, you might be asked if you want to update the `PATH` environment variable. + +//// tab | Linux, macOS + +Let's say you install Python and it ends up in a directory `/opt/custompython/bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable. + +It could look like this: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +//// + +//// tab | Windows + +Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one. + +//// + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +So, if you type: + +<div class="termy"> + +```console +$ python +``` + +</div> + +//// tab | Linux, macOS + +The system will **find** the `python` program in `/opt/custompython/bin` and run it. + +It would be roughly equivalent to typing: + +<div class="termy"> + +```console +$ /opt/custompython/bin/python +``` + +</div> + +//// + +//// tab | Windows + +The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it. + +It would be roughly equivalent to typing: + +<div class="termy"> + +```console +$ C:\opt\custompython\bin\python +``` + +</div> + +//// + +This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +With this you should have a basic understanding of what **environment variables** are and how to use them in Python. + +You can also read more about them in the <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">Wikipedia for Environment Variable</a>. + +In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them. + +For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md). diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index d76ef498b..ac4f4d00f 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -128,6 +128,8 @@ FastAPI stands on the shoulders of giants: ## Installation +Create and activate a <a href="https://fastapi.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install FastAPI: + <div class="termy"> ```console diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 5f8c51c4c..386fe5de9 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -4,9 +4,7 @@ This tutorial shows you how to use **FastAPI** with most of its features, step b Each section gradually builds on the previous ones, but it's structured to separate topics, so that you can go directly to any specific one to solve your specific API needs. -It is also built to work as a future reference. - -So you can come back and see exactly what you need. +It is also built to work as a future reference so you can come back and see exactly what you need. ## Run the code @@ -71,7 +69,9 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing ## Install FastAPI -The first step is to install FastAPI: +The first step is to install FastAPI. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then **install FastAPI**: <div class="termy"> diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 53d9eefde..9f19596a8 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -6,7 +6,11 @@ You can define files to be uploaded by the client using `File`. To receive uploaded files, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` This is because uploaded files are sent as "form data". diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 9b4342652..7830a2ba4 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -6,7 +6,11 @@ You can define files and form fields at the same time using `File` and `Form`. To receive uploaded files and/or form data, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` /// diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 88b5b86b6..87cfdefbc 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -6,7 +6,11 @@ When you need to receive form fields instead of JSON, you can use `Form`. To use forms, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` /// diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index c17e32f90..6a2093e6d 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -133,8 +133,17 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>. -E.g. `pip install email-validator` -or `pip install pydantic[email]`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install email-validator +``` + +or with: + +```console +$ pip install "pydantic[email]" +``` /// diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index ed427a282..4bd026caf 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -56,9 +56,13 @@ Prefer to use the `Annotated` version if possible. The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. -However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: +However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. -`pip install python-multipart` +To install it manually, make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it with: + +```console +$ pip install python-multipart +``` This is because **OAuth2** uses "form data" for sending the `username` and `password`. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 52877b916..ba2bfef29 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -28,7 +28,9 @@ If you want to play with JWT tokens and see how they work, check <a href="https: ## Install `PyJWT` -We need to install `PyJWT` to generate and verify the JWT tokens in Python: +We need to install `PyJWT` to generate and verify the JWT tokens in Python. + +Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `pyjwt`: <div class="termy"> @@ -70,7 +72,7 @@ It supports many secure hashing algorithms and utilities to work with them. The recommended algorithm is "Bcrypt". -So, install PassLib with Bcrypt: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install PassLib with Bcrypt: <div class="termy"> diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 0645cc9f1..56971bf9d 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -101,7 +101,9 @@ Now let's see what each file/module does. ## Install `SQLAlchemy` -First you need to install `SQLAlchemy`: +First you need to install `SQLAlchemy`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: <div class="termy"> diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 95c8c5bef..06a87e92e 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -12,7 +12,11 @@ With it, you can use <a href="https://docs.pytest.org/" class="external-link" ta To use `TestClient`, first install <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>. -E.g. `pip install httpx`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install httpx +``` /// @@ -206,7 +210,9 @@ If you have a Pydantic model in your test and you want to send its data to the a ## Run it -After that, you just need to install `pytest`: +After that, you just need to install `pytest`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: <div class="termy"> diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md new file mode 100644 index 000000000..3c4aa49c1 --- /dev/null +++ b/docs/en/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# Virtual Environments + +When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project. + +/// info + +If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓 + +/// + +/// tip + +A **virtual environment** is different than an **environment variable**. + +An **environment variable** is a variable in the system that can be used by programs. + +A **virtual environment** is a directory with some files in it. + +/// + +/// info + +This page will teach you how to use **virtual environments** and how they work. + +If you are ready to adopt a **tool that manages everything** for you (including installing Python), try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>. + +/// + +## Create a Project + +First, create a directory for your project. + +What I normally do is that I create a directory named `code` inside my home/user directory. + +And inside of that I create one directory per project. + +<div class="termy"> + +```console +// Go to the home directory +$ cd +// Create a directory for all your code projects +$ mkdir code +// Enter into that code directory +$ cd code +// Create a directory for this project +$ mkdir awesome-project +// Enter into that project directory +$ cd awesome-project +``` + +</div> + +## Create a Virtual Environment + +When you start working on a Python project **for the first time**, create a virtual environment **<abbr title="there are other options, this is a simple guideline">inside your project</abbr>**. + +/// tip + +You only need to do this **once per project**, not every time you work. + +/// + +//// tab | `venv` + +To create a virtual environment, you can use the `venv` module that comes with Python. + +<div class="termy"> + +```console +$ python -m venv .venv +``` + +</div> + +/// details | What that command means + +* `python`: use the program called `python` +* `-m`: call a module as a script, we'll tell it which module next +* `venv`: use the module called `venv` that normally comes installed with Python +* `.venv`: create the virtual environment in the new directory `.venv` + +/// + +//// + +//// tab | `uv` + +If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> installed, you can use it to create a virtual environment. + +<div class="termy"> + +```console +$ uv venv +``` + +</div> + +/// tip + +By default, `uv` will create a virtual environment in a directory called `.venv`. + +But you could customize it passing an additional argument with the directory name. + +/// + +//// + +That command creates a new virtual environment in a directory called `.venv`. + +/// details | `.venv` or other name + +You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`. + +/// + +## Activate the Virtual Environment + +Activate the new virtual environment so that any Python command you run or package you install uses it. + +/// tip + +Do this **every time** you start a **new terminal session** to work on the project. + +/// + +//// tab | Linux, macOS + +<div class="termy"> + +```console +$ source .venv/bin/activate +``` + +</div> + +//// + +//// tab | Windows PowerShell + +<div class="termy"> + +```console +$ .venv\Scripts\Activate.ps1 +``` + +</div> + +//// + +//// tab | Windows Bash + +Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): + +<div class="termy"> + +```console +$ source .venv/Scripts/activate +``` + +</div> + +//// + +/// tip + +Every time you install a **new package** in that environment, **activate** the environment again. + +This makes sure that if you use a **terminal (<abbr title="command line interface">CLI</abbr>) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need. + +/// + +## Check the Virtual Environment is Active + +Check that the virtual environment is active (the previous command worked). + +/// tip + +This is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended. + +/// + +//// tab | Linux, macOS, Windows Bash + +<div class="termy"> + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +</div> + +If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉 + +//// + +//// tab | Windows PowerShell + +<div class="termy"> + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +</div> + +If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉 + +//// + +## Upgrade `pip` + +/// tip + +If you use <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎 + +/// + +If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version. + +Many exotic errors while installing a package are solved by just upgrading `pip` first. + +/// tip + +You would normally do this **once**, right after you create the virtual environment. + +/// + +Make sure the virtual environment is active (with the command above) and then run: + +<div class="termy"> + +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +</div> + +## Add `.gitignore` + +If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git. + +/// tip + +If you used <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> to create the virtual environment, it already did this for you, you can skip this step. 😎 + +/// + +/// tip + +Do this **once**, right after you create the virtual environment. + +/// + +<div class="termy"> + +```console +$ echo "*" > .venv/.gitignore +``` + +</div> + +/// details | What that command means + +* `echo "*"`: will "print" the text `*` in the terminal (the next part changes that a bit) +* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>` +* `.gitignore`: the name of the file where the text should be written + +And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory. + +That command will create a file `.gitignore` with the content: + +```gitignore +* +``` + +/// + +## Install Packages + +After activating the environment, you can install packages in it. + +/// tip + +Do this **once** when installing or upgrading the packages your project needs. + +If you need to upgrade a version or add a new package you would **do this again**. + +/// + +### Install Packages Directly + +If you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly. + +/// tip + +It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`). + +/// + +//// tab | `pip` + +<div class="termy"> + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +</div> + +//// + +//// tab | `uv` + +If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>: + +<div class="termy"> + +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +</div> + +//// + +### Install from `requirements.txt` + +If you have a `requirements.txt`, you can now use it to install its packages. + +//// tab | `pip` + +<div class="termy"> + +```console +$ pip install -r requirements.txt +---> 100% +``` + +</div> + +//// + +//// tab | `uv` + +If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>: + +<div class="termy"> + +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +</div> + +//// + +/// details | `requirements.txt` + +A `requirements.txt` with some packages could look like: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Run Your Program + +After you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there. + +<div class="termy"> + +```console +$ python main.py + +Hello World +``` + +</div> + +## Configure Your Editor + +You would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors. + +For example: + +* <a href="https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment" class="external-link" target="_blank">VS Code</a> +* <a href="https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html" class="external-link" target="_blank">PyCharm</a> + +/// tip + +You normally have to do this only **once**, when you create the virtual environment. + +/// + +## Deactivate the Virtual Environment + +Once you are done working on your project you can **deactivate** the virtual environment. + +<div class="termy"> + +```console +$ deactivate +``` + +</div> + +This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there. + +## Ready to Work + +Now you're ready to start working on your project. + + + +/// tip + +Do you want to understand what's all that above? + +Continue reading. 👇🤓 + +/// + +## Why Virtual Environments + +To work with FastAPI you need to install <a href="https://www.python.org/" class="external-link" target="_blank">Python</a>. + +After that, you would need to **install** FastAPI and any other **packages** you want to use. + +To install packages you would normally use the `pip` command that comes with Python (or similar alternatives). + +Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python). + +### The Problem + +So, what's the problem with installing packages in the global Python environment? + +At some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱 + +For example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Then, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +But now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install. + +If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with: + +<div class="termy"> + +```console +$ pip install "harry==1" +``` + +</div> + +And then you would end up with `harry` version `1` installed in your global Python environment. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +But then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`). + +<div class="termy"> + +```console +$ pip install "harry==3" +``` + +</div> + +And then you would end up with `harry` version `3` installed in your global Python environment. + +And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[<strike>harry v1</strike>] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip + +It's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly. + +/// + +Now, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working. + +Also, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system. + +## Where are Packages Installed + +When you install Python, it creates some directories with some files in your computer. + +Some of these directories are the ones in charge of having all the packages you install. + +When you run: + +<div class="termy"> + +```console +// Don't run this now, it's just an example 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +</div> + +That will download a compressed file with the FastAPI code, normally from <a href="https://pypi.org/project/fastapi/" class="external-link" target="_blank">PyPI</a>. + +It will also **download** files for other packages that FastAPI depends on. + +Then it will **extract** all those files and put them in a directory in your computer. + +By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**. + +## What are Virtual Environments + +The solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on. + +A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project. + +This way, each project will have it's own virtual environment (`.venv` directory) with its own packages. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## What Does Activating a Virtual Environment Mean + +When you activate a virtual environment, for example with: + +//// tab | Linux, macOS + +<div class="termy"> + +```console +$ source .venv/bin/activate +``` + +</div> + +//// + +//// tab | Windows PowerShell + +<div class="termy"> + +```console +$ .venv\Scripts\Activate.ps1 +``` + +</div> + +//// + +//// tab | Windows Bash + +Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>): + +<div class="termy"> + +```console +$ source .venv/Scripts/activate +``` + +</div> + +//// + +That command will create or modify some [environment variables](environment-variables.md){.internal-link target=_blank} that will be available for the next commands. + +One of those variables is the `PATH` variable. + +/// tip + +You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable){.internal-link target=_blank} section. + +/// + +Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable. + +Let's say that before activating the environment, the `PATH` variable looked like this: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +That means that the system would look for programs in: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +That means that the system would look for programs in: + +* `C:\Windows\System32` + +//// + +After activating the virtual environment, the `PATH` variable would look something like this: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +That means that the system will now start looking first look for programs in: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +before looking in the other directories. + +So, when you type `python` in the terminal, the system will find the Python program in + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +and use that one. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +That means that the system will now start looking first look for programs in: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +before looking in the other directories. + +So, when you type `python` in the terminal, the system will find the Python program in + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +and use that one. + +//// + +An important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment). + +Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does. + +## Checking a Virtual Environment + +When you check if a virtual environment is active, for example with: + +//// tab | Linux, macOS, Windows Bash + +<div class="termy"> + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +</div> + +//// + +//// tab | Windows PowerShell + +<div class="termy"> + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +</div> + +//// + +That means that the `python` program that will be used is the one **in the virtual environment**. + +you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell. + +The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program. + +The most important part is that when you call `python`, that is the exact "`python`" that will be executed. + +So, you can confirm if you are in the correct virtual environment. + +/// tip + +It's easy to activate one virtual environment, get one Python, and then **go to another project**. + +And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project. + +It's useful being able to check what `python` is being used. 🤓 + +/// + +## Why Deactivate a Virtual Environment + +For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment. + +And then you want to work on **another project** `prisoner-of-azkaban`. + +You go to that project: + +<div class="termy"> + +```console +$ cd ~/code/prisoner-of-azkaban +``` + +</div> + +If you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`. + +<div class="termy"> + +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importing sirius, it's not installed 😱 +Traceback (most recent call last): + File "main.py", line 1, in <module> + import sirius +``` + +</div> + +But if you deactivate the virtual environment and activate the new one for `prisoner-of-askaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`. + +<div class="termy"> + +```console +$ cd ~/code/prisoner-of-azkaban + +// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎 +$ deactivate + +// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Now when you run python, it will find the package sirius installed in this virtual environment ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +</div> + +## Alternatives + +This is a simple guide to get you started and teach you how everything works **underneath**. + +There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects. + +Once you are ready and want to use a tool to **manage the entire project**, packages dependencies, virtual environments, etc. I would suggest you try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>. + +`uv` can do a lot of things, it can: + +* **Install Python** for you, including different versions +* Manage the **virtual environment** for your projects +* Install **packages** +* Manage package **dependencies and versions** for your project +* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking** +* And many other things + +## Conclusion + +If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓 + +Knowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎 diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d0527ca3c..6f1e12511 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -108,6 +108,8 @@ nav: - learn/index.md - python-types.md - async.md + - environment-variables.md + - virtual-environments.md - Tutorial - User Guide: - tutorial/index.md - tutorial/first-steps.md From d0ce9d2bdf7f3c78b6f193288b9925b952da27c9 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 22 Aug 2024 00:47:57 +0000 Subject: [PATCH 797/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 12f1f50cd..a8bbcc3b7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). From 8f037167571ca60f87677594418fc68a05db6a9f Mon Sep 17 00:00:00 2001 From: Aymen <aymenkrifa@gmail.com> Date: Sat, 24 Aug 2024 04:16:23 +0100 Subject: [PATCH 798/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20a=20typo=20in=20vi?= =?UTF-8?q?rtual=20environement=20page=20(#12064)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/virtual-environments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md index 3c4aa49c1..fcc72fbe7 100644 --- a/docs/en/docs/virtual-environments.md +++ b/docs/en/docs/virtual-environments.md @@ -558,7 +558,7 @@ The solution to the problems of having all the packages in the global environmen A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project. -This way, each project will have it's own virtual environment (`.venv` directory) with its own packages. +This way, each project will have its own virtual environment (`.venv` directory) with its own packages. ```mermaid flowchart TB From 6935fe8d38fe4befd0cc1cd8ddbbd836bb809497 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 24 Aug 2024 03:16:48 +0000 Subject: [PATCH 799/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a8bbcc3b7..8059de05d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Fix a typo in virtual environement page. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). * 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). From 22bf988dfb085f45449bc137401af0105a86cdf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 23 Aug 2024 22:48:20 -0500 Subject: [PATCH 800/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8059de05d..c872f59e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,7 +14,7 @@ hide: ### Docs -* 📝 Fix a typo in virtual environement page. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). +* 📝 Fix a typo in `docs/en/docs/virtual-environments.md`. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). * 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). @@ -36,7 +36,7 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). -* 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From 3a4ac2467594d0ccad92ecfb7f7f10ffa5d1d992 Mon Sep 17 00:00:00 2001 From: Pastukhov Nikita <diementros@yandex.ru> Date: Sat, 24 Aug 2024 22:09:52 +0300 Subject: [PATCH 801/846] =?UTF-8?q?=F0=9F=90=9B=20Ensure=20that=20`app.inc?= =?UTF-8?q?lude=5Frouter`=20merges=20nested=20lifespans=20(#9630)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- fastapi/routing.py | 27 +++++++- tests/test_router_events.py | 135 +++++++++++++++++++++++++++++++++++- 2 files changed, 158 insertions(+), 4 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 2e7959f3d..49f1b6013 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -3,14 +3,16 @@ import dataclasses import email.message import inspect import json -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, + AsyncIterator, Callable, Coroutine, Dict, List, + Mapping, Optional, Sequence, Set, @@ -67,7 +69,7 @@ from starlette.routing import ( websocket_session, ) from starlette.routing import Mount as Mount # noqa -from starlette.types import ASGIApp, Lifespan, Scope +from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated @@ -119,6 +121,23 @@ def _prepare_response_content( return res +def _merge_lifespan_context( + original_context: Lifespan[Any], nested_context: Lifespan[Any] +) -> Lifespan[Any]: + @asynccontextmanager + async def merged_lifespan( + app: AppType, + ) -> AsyncIterator[Optional[Mapping[str, Any]]]: + async with original_context(app) as maybe_original_state: + async with nested_context(app) as maybe_nested_state: + if maybe_nested_state is None and maybe_original_state is None: + yield None # old ASGI compatibility + else: + yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} + + return merged_lifespan # type: ignore[return-value] + + async def serialize_response( *, field: Optional[ModelField] = None, @@ -1308,6 +1327,10 @@ class APIRouter(routing.Router): self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) + self.lifespan_context = _merge_lifespan_context( + self.lifespan_context, + router.lifespan_context, + ) def get( self, diff --git a/tests/test_router_events.py b/tests/test_router_events.py index 1b9de18ae..dd7ff3314 100644 --- a/tests/test_router_events.py +++ b/tests/test_router_events.py @@ -1,8 +1,8 @@ from contextlib import asynccontextmanager -from typing import AsyncGenerator, Dict +from typing import AsyncGenerator, Dict, Union import pytest -from fastapi import APIRouter, FastAPI +from fastapi import APIRouter, FastAPI, Request from fastapi.testclient import TestClient from pydantic import BaseModel @@ -109,3 +109,134 @@ def test_app_lifespan_state(state: State) -> None: assert response.json() == {"message": "Hello World"} assert state.app_startup is True assert state.app_shutdown is True + + +def test_router_nested_lifespan_state(state: State) -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.app_startup = True + yield {"app": True} + state.app_shutdown = True + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.router_startup = True + yield {"router": True} + state.router_shutdown = True + + @asynccontextmanager + async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.sub_router_startup = True + yield {"sub_router": True} + state.sub_router_shutdown = True + + sub_router = APIRouter(lifespan=subrouter_lifespan) + + router = APIRouter(lifespan=router_lifespan) + router.include_router(sub_router) + + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + @app.get("/") + def main(request: Request) -> Dict[str, str]: + assert request.state.app + assert request.state.router + assert request.state.sub_router + return {"message": "Hello World"} + + assert state.app_startup is False + assert state.router_startup is False + assert state.sub_router_startup is False + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + + with TestClient(app) as client: + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == {"message": "Hello World"} + + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is True + assert state.router_shutdown is True + assert state.sub_router_shutdown is True + + +def test_router_nested_lifespan_state_overriding_by_parent() -> None: + @asynccontextmanager + async def lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "app_specific": True, + "overridden": "app", + } + + @asynccontextmanager + async def router_lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "router_specific": True, + "overridden": "router", # should override parent + } + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == { + "app_specific": True, + "router_specific": True, + "overridden": "app", + } + + +def test_merged_no_return_lifespans_return_none() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert not client.app_state + + +def test_merged_mixed_state_lifespans() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + yield {"router": True} + + @asynccontextmanager + async def sub_router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + sub_router = APIRouter(lifespan=sub_router_lifespan) + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + router.include_router(sub_router) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == {"router": True} From 48b36f26d83d607a044866633068dbf46e723e0f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 24 Aug 2024 19:10:14 +0000 Subject: [PATCH 802/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c872f59e9..d9cefc989 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik). + ### Refactors * 🎨 Fix typing annotation for semi-internal `FastAPI.add_api_route()`. PR [#10240](https://github.com/fastapi/fastapi/pull/10240) by [@ordinary-jamie](https://github.com/ordinary-jamie). From 51b625e127982f626886d467122ef85d5772d1db Mon Sep 17 00:00:00 2001 From: Giunio <59511892+giunio-prc@users.noreply.github.com> Date: Sat, 24 Aug 2024 21:27:37 +0200 Subject: [PATCH 803/846] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`allow=5Finf=5Fnan?= =?UTF-8?q?`=20option=20for=20Param=20and=20Body=20classes=20(#11867)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: svlandeg <svlandeg@github.com> --- fastapi/params.py | 4 +- tests/test_allow_inf_nan_in_enforcing.py | 83 ++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 tests/test_allow_inf_nan_in_enforcing.py diff --git a/fastapi/params.py b/fastapi/params.py index 860146531..cc2a5c13c 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -91,7 +91,7 @@ class Param(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, @@ -547,7 +547,7 @@ class Body(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, diff --git a/tests/test_allow_inf_nan_in_enforcing.py b/tests/test_allow_inf_nan_in_enforcing.py new file mode 100644 index 000000000..9e855fdf8 --- /dev/null +++ b/tests/test_allow_inf_nan_in_enforcing.py @@ -0,0 +1,83 @@ +import pytest +from fastapi import Body, FastAPI, Query +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/") +async def get( + x: Annotated[float, Query(allow_inf_nan=True)] = 0, + y: Annotated[float, Query(allow_inf_nan=False)] = 0, + z: Annotated[float, Query()] = 0, + b: Annotated[float, Body(allow_inf_nan=False)] = 0, +) -> str: + return "OK" + + +client = TestClient(app) + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_true(value: str, code: int): + response = client.post(f"/?x={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_false(value: str, code: int): + response = client.post(f"/?y={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_default(value: str, code: int): + response = client.post(f"/?z={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_body(value: str, code: int): + response = client.post("/", json=value) + assert response.status_code == code, response.text From b69a9f3b6f822e71be275ca20347a0ab3dfe99e8 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 24 Aug 2024 19:27:59 +0000 Subject: [PATCH 804/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d9cefc989..28d430ab0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Fixes +* 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc). * 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik). ### Refactors From d00af00d3f15e9a963e2f1baf8f9b4c8357f6f66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 24 Aug 2024 14:34:50 -0500 Subject: [PATCH 805/846] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?2.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 28d430ab0..2af28ae05 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.112.2 + ### Fixes * 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 0b79d45ef..ac2508d89 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.112.1" +__version__ = "0.112.2" from starlette import status as status From 9656895b60e85aeee82a599dc601813ba815b0df Mon Sep 17 00:00:00 2001 From: GPla <36087062+GPla@users.noreply.github.com> Date: Sat, 24 Aug 2024 22:04:30 +0200 Subject: [PATCH 806/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20in=20Docker?= =?UTF-8?q?=20docs=20about=20ensuring=20graceful=20shutdowns=20and=20lifes?= =?UTF-8?q?pan=20events=20with=20`CMD`=20exec=20form=20(#11960)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg <svlandeg@github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> --- docs/en/docs/deployment/docker.md | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 253e25fe5..ab1c2201f 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -232,6 +232,38 @@ Review what each line does by clicking each number bubble in the code. 👆 /// +/// warning + +Make sure to **always** use the **exec form** of the `CMD` instruction, as explained below. + +/// + +#### Use `CMD` - Exec Form + +The <a href="https://docs.docker.com/reference/dockerfile/#cmd" class="external-link" target="_blank">`CMD`</a> Docker instruction can be written using two forms: + +✅ **Exec** form: + +```Dockerfile +# ✅ Do this +CMD ["fastapi", "run", "app/main.py", "--port", "80"] +``` + +⛔️ **Shell** form: + +```Dockerfile +# ⛔️ Don't do this +CMD fastapi run app/main.py --port 80 +``` + +Make sure to always use the **exec** form to ensure that FastAPI can shutdown gracefully and [lifespan events](../advanced/events.md){.internal-link target=_blank} are triggered. + +You can read more about it in the <a href="https://docs.docker.com/reference/dockerfile/#shell-and-exec-form" class="external-link" target="_blank">Docker docs for shell and exec form</a>. + +This can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: <a href="https://docs.docker.com/compose/faq/#why-do-my-services-take-10-seconds-to-recreate-or-stop" class="external-link" target="_blank">Why do my services take 10 seconds to recreate or stop?</a>. + +#### Directory Structure + You should now have a directory structure like: ``` From e4727ed20aa83604a9d28d397e4ce4994f8b9640 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 24 Aug 2024 20:04:51 +0000 Subject: [PATCH 807/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2af28ae05..83d992b8b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). + ## 0.112.2 ### Fixes From 6aa44a85a211f5175b2b45d0dbf23128f6be0627 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem <svlandeg@users.noreply.github.com> Date: Sat, 24 Aug 2024 23:52:09 +0200 Subject: [PATCH 808/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20minor=20typos=20an?= =?UTF-8?q?d=20issues=20in=20the=20documentation=20(#12063)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/docs/advanced/response-directly.md | 2 +- docs/en/docs/async.md | 2 +- docs/en/docs/index.md | 2 +- docs/en/docs/python-types.md | 2 +- docs/en/docs/tutorial/bigger-applications.md | 4 ++-- docs/en/docs/tutorial/body-multiple-params.md | 2 +- docs/en/docs/tutorial/body-updates.md | 2 +- docs/en/docs/tutorial/body.md | 2 +- docs/en/docs/tutorial/cors.md | 2 +- .../docs/tutorial/dependencies/classes-as-dependencies.md | 2 +- docs/en/docs/tutorial/extra-data-types.md | 2 +- docs/en/docs/tutorial/handling-errors.md | 4 ++-- docs/en/docs/tutorial/index.md | 2 +- docs/en/docs/tutorial/middleware.md | 2 +- docs/en/docs/tutorial/query-params-str-validations.md | 6 +++--- docs/en/docs/tutorial/schema-extra-example.md | 2 +- docs/en/docs/tutorial/security/first-steps.md | 2 +- docs/en/docs/tutorial/security/get-current-user.md | 2 +- 19 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 889a89ed7..ec7a95497 100644 --- a/README.md +++ b/README.md @@ -394,7 +394,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 73071ed1b..2251659c5 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -28,7 +28,7 @@ This gives you a lot of flexibility. You can return any data type, override any ## Using the `jsonable_encoder` in a `Response` -Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it. +Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure its contents are ready for it. For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types. diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 7cf4af627..752a5c247 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -292,7 +292,7 @@ For example: ### Concurrency + Parallelism: Web + Machine Learning -With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS). +With **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS). But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index ac4f4d00f..3ed3d7bf6 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -390,7 +390,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 4ed1fc680..6994adb5f 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -324,7 +324,7 @@ In Python 3.6 and above (including Python 3.10) you can declare it by importing {!../../../docs_src/python_types/tutorial009.py!} ``` -Using `Optional[str]` instead of just `str` will let the editor help you detecting errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. +Using `Optional[str]` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. `Optional[Something]` is actually a shortcut for `Union[Something, None]`, they are equivalent. diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 97f6b205b..230f9c08c 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -1,6 +1,6 @@ # Bigger Applications - Multiple Files -If you are building an application or a web API, it's rarely the case that you can put everything on a single file. +If you are building an application or a web API, it's rarely the case that you can put everything in a single file. **FastAPI** provides a convenience tool to structure your application while keeping all the flexibility. @@ -478,7 +478,7 @@ We can declare all that without having to modify the original `APIRouter` by pas {!../../../docs_src/bigger_applications/app/main.py!} ``` -That way, the original `APIRouter` will keep unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. +That way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. The result is that in our app, each of the *path operations* from the `admin` module will have: diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 511fb358e..d63cd2529 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -97,7 +97,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: //// -In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models). +In this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models). So, it will then use the parameter names as keys (field names) in the body, and expect a body like: diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 261f44d33..3257f9a08 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -155,7 +155,7 @@ In summary, to apply partial updates you would: * Put that data in a Pydantic model. * Generate a `dict` without default values from the input model (using `exclude_unset`). * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model. -* Create a copy of the stored model, updating it's attributes with the received partial updates (using the `update` parameter). +* Create a copy of the stored model, updating its attributes with the received partial updates (using the `update` parameter). * Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`). * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. * Save the data to your DB. diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 608b50dbb..83f08ce84 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -123,7 +123,7 @@ The JSON Schemas of your models will be part of your OpenAPI generated schema, a <img src="/img/tutorial/body/image01.png"> -And will be also used in the API docs inside each *path operation* that needs them: +And will also be used in the API docs inside each *path operation* that needs them: <img src="/img/tutorial/body/image02.png"> diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index fd329e138..7dd0a5df5 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -40,7 +40,7 @@ You can configure it in your **FastAPI** application using the `CORSMiddleware`. * Create a list of allowed origins (as strings). * Add it as a "middleware" to your **FastAPI** application. -You can also specify if your backend allows: +You can also specify whether your backend allows: * Credentials (Authorization headers, Cookies, etc). * Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`. diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index a392672bb..b3394f14e 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -381,7 +381,7 @@ The last `CommonQueryParams`, in: ...is what **FastAPI** will actually use to know what is the dependency. -From it is that FastAPI will extract the declared parameters and that is what FastAPI will actually call. +It is from this one that FastAPI will extract the declared parameters and that is what FastAPI will actually call. --- diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index 849dee41f..3009acaf3 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -49,7 +49,7 @@ Here are some of the additional data types you can use: * `Decimal`: * Standard Python `Decimal`. * In requests and responses, handled the same as a `float`. -* You can check all the valid pydantic data types here: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic data types</a>. +* You can check all the valid Pydantic data types here: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic data types</a>. ## Example diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index ca3cff661..14a3cf998 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -176,7 +176,7 @@ These are technical details that you might skip if it's not important for you no **FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log. -But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`. +But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with an HTTP status code `500`. It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code. @@ -262,7 +262,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException ### Reuse **FastAPI**'s exception handlers -If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`: +If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" {!../../../docs_src/handling_errors/tutorial006.py!} diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 386fe5de9..bf613aace 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -95,7 +95,7 @@ If you don't want to have those optional dependencies, you can instead install ` There is also an **Advanced User Guide** that you can read later after this **Tutorial - User guide**. -The **Advanced User Guide**, builds on this, uses the same concepts, and teaches you some extra features. +The **Advanced User Guide** builds on this one, uses the same concepts, and teaches you some extra features. But you should first read the **Tutorial - User Guide** (what you are reading right now). diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index f0b3faf3b..06fb3f504 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -29,7 +29,7 @@ The middleware function receives: * A function `call_next` that will receive the `request` as a parameter. * This function will pass the `request` to the corresponding *path operation*. * Then it returns the `response` generated by the corresponding *path operation*. -* You can then modify further the `response` before returning it. +* You can then further modify the `response` before returning it. ```Python hl_lines="8-9 11 14" {!../../../docs_src/middleware/tutorial001.py!} diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 859242d93..dd101a2a6 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -273,7 +273,7 @@ The **default** value of the **function parameter** is the **actual default** va You could **call** that same function in **other places** without FastAPI, and it would **work as expected**. If there's a **required** parameter (without a default value), your **editor** will let you know with an error, **Python** will also complain if you run it without passing the required parameter. -When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other place**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out. +When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other places**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out. Because `Annotated` can have more than one metadata annotation, you could now even use the same function with other tools, like <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">Typer</a>. 🚀 @@ -645,7 +645,7 @@ Remember that in most of the cases, when something is required, you can simply o ## Query parameter list / multiple values -When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in other way, to receive multiple values. +When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values. For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: @@ -1182,4 +1182,4 @@ Validations specific for strings: In these examples you saw how to declare validations for `str` values. -See the next chapters to see how to declare validations for other types, like numbers. +See the next chapters to learn how to declare validations for other types, like numbers. diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 70745b048..20dee3a4f 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -347,7 +347,7 @@ If the ideas above already work for you, that might be enough, and you probably Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**. -JSON Schema didn't have `examples`, so OpenAPI added it's own `example` field to its own modified version. +JSON Schema didn't have `examples`, so OpenAPI added its own `example` field to its own modified version. OpenAPI also added `example` and `examples` fields to other parts of the specification: diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 4bd026caf..d1fe0163e 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -152,7 +152,7 @@ A "bearer" token is not the only option. But it's the best one for our use case. -And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs. +And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that better suits your needs. In that case, **FastAPI** also provides you with the tools to build it. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 6f3bf3944..7faaa3e13 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -316,7 +316,7 @@ And you can make it as complex as you want. And still, have it written only once But you can have thousands of endpoints (*path operations*) using the same security system. -And all of them (or any portion of them that you want) can take the advantage of re-using these dependencies or any other dependencies you create. +And all of them (or any portion of them that you want) can take advantage of re-using these dependencies or any other dependencies you create. And all these thousands of *path operations* can be as small as 3 lines: From d8e526c1db42b9049a3c9a26f2ac91109c896812 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 24 Aug 2024 21:52:29 +0000 Subject: [PATCH 809/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 83d992b8b..2218b352b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). ## 0.112.2 From c692176d4288e8b8f6f404c7c15aaab74083a6e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 24 Aug 2024 19:01:04 -0500 Subject: [PATCH 810/846] =?UTF-8?q?=F0=9F=93=9D=20Clarify=20`response=5Fcl?= =?UTF-8?q?ass`=20parameter,=20validations,=20and=20returning=20a=20respon?= =?UTF-8?q?se=20directly=20(#12067)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/custom-response.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 8a6555dba..79f755815 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -4,9 +4,9 @@ By default, **FastAPI** will return the responses using `JSONResponse`. You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}. -But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). +But if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). -But you can also declare the `Response` that you want to be used, in the *path operation decorator*. +But you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter. The contents that you return from your *path operation function* will be put inside of that `Response`. From b5cbff9521c6c800aebf37d73a3532951db95bff Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 25 Aug 2024 00:01:26 +0000 Subject: [PATCH 811/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2218b352b..ac8f16f53 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). From bd1b77548f0f1788c5ae0fbd8144f5139bdb959e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 24 Aug 2024 21:44:06 -0500 Subject: [PATCH 812/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20about=20?= =?UTF-8?q?serving=20FastAPI:=20ASGI=20servers,=20Docker=20containers,=20e?= =?UTF-8?q?tc.=20(#12069)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/sub-applications.md | 4 +- docs/en/docs/alternatives.md | 2 +- docs/en/docs/contributing.md | 2 +- docs/en/docs/deployment/concepts.md | 8 +- docs/en/docs/deployment/docker.md | 226 ++++--------------- docs/en/docs/deployment/manually.md | 89 +------- docs/en/docs/deployment/server-workers.md | 165 ++++++-------- docs/en/docs/deployment/versions.md | 2 +- docs/en/docs/tutorial/bigger-applications.md | 4 +- 9 files changed, 129 insertions(+), 373 deletions(-) diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index 8c52e091f..568a9deca 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -36,12 +36,12 @@ In this case, it will be mounted at the path `/subapi`: ### Check the automatic API docs -Now, run `uvicorn` with the main app, if your file is `main.py`, it would be: +Now, run the `fastapi` command with your file: <div class="termy"> ```console -$ uvicorn main:app --reload +$ fastapi dev main.py <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 2ad584c95..e98c0475a 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -474,7 +474,7 @@ It is the recommended server for Starlette and **FastAPI**. The main web server to run **FastAPI** applications. -You can combine it with Gunicorn, to have an asynchronous multi-process server. +You can also use the `--workers` command line option to have an asynchronous multi-process server. Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 91d5724a8..0dc07b89b 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -170,7 +170,7 @@ If you run the examples with, e.g.: <div class="termy"> ```console -$ uvicorn tutorial001:app --reload +$ fastapi dev tutorial001.py <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index f917d18b3..69ee71a73 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**, ### In a Remote Server -When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to use `fastapi run`, Uvicorn (or similar) manually, the same way you do when developing locally. +When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally. And it will work and will be useful **during development**. @@ -178,7 +178,7 @@ For example, this could be handled by: ## Replication - Processes and Memory -With a FastAPI application, using a server program like Uvicorn, running it once in **one process** can serve multiple clients concurrently. +With a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently. But in many cases, you will want to run several worker processes at the same time. @@ -232,9 +232,7 @@ The main constraint to consider is that there has to be a **single** component h Here are some possible combinations and strategies: -* **Gunicorn** managing **Uvicorn workers** - * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes**. -* **Uvicorn** managing **Uvicorn workers** +* **Uvicorn** with `--workers` * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**. * **Kubernetes** and other distributed **container systems** * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index ab1c2201f..2d832a238 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -167,22 +167,22 @@ def read_item(item_id: int, q: Union[str, None] = None): Now in the same project directory create a file `Dockerfile` with: ```{ .dockerfile .annotate } -# (1) +# (1)! FROM python:3.9 -# (2) +# (2)! WORKDIR /code -# (3) +# (3)! COPY ./requirements.txt /code/requirements.txt -# (4) +# (4)! RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (5) +# (5)! COPY ./app /code/app -# (6) +# (6)! CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` @@ -400,10 +400,10 @@ COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (1) +# (1)! COPY ./main.py /code/ -# (2) +# (2)! CMD ["fastapi", "run", "main.py", "--port", "80"] ``` @@ -456,11 +456,11 @@ Without using containers, making applications run on startup and with restarts c ## Replication - Number of Processes -If you have a <abbr title="A group of machines that are configured to be connected and work together in some way.">cluster</abbr> of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Gunicorn with workers) in each container. +If you have a <abbr title="A group of machines that are configured to be connected and work together in some way.">cluster</abbr> of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container. One of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**. -In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of running something like Gunicorn with Uvicorn workers. +In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers. ### Load Balancer @@ -490,37 +490,44 @@ And normally this **load balancer** would be able to handle requests that go to In this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level. -So, in this case, you **would not** want to have a process manager like Gunicorn with Uvicorn workers, or Uvicorn using its own Uvicorn workers. You would want to have just a **single Uvicorn process** per container (but probably multiple containers). +So, in this case, you **would not** want to have a multiple workers in the container, for example with the `--workers` command line option.You would want to have just a **single Uvicorn process** per container (but probably multiple containers). -Having another process manager inside the container (as would be with Gunicorn or Uvicorn managing Uvicorn workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. +Having another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. ### Containers with Multiple Processes and Special Cases -Of course, there are **special cases** where you could want to have **a container** with a **Gunicorn process manager** starting several **Uvicorn worker processes** inside. +Of course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside. -In those cases, you can use the **official Docker image** that includes **Gunicorn** as a process manager running multiple **Uvicorn worker processes**, and some default settings to adjust the number of workers based on the current CPU cores automatically. I'll tell you more about it below in [Official Docker Image with Gunicorn - Uvicorn](#official-docker-image-with-gunicorn-uvicorn). +In those cases, you can use the `--workers` command line option to set the number of workers that you want to run: -Here are some examples of when that could make sense: +```{ .dockerfile .annotate } +FROM python:3.9 -#### A Simple App +WORKDIR /code -You could want a process manager in the container if your application is **simple enough** that you don't need (at least not yet) to fine-tune the number of processes too much, and you can just use an automated default (with the official Docker image), and you are running it on a **single server**, not a cluster. +COPY ./requirements.txt /code/requirements.txt -#### Docker Compose +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. +COPY ./app /code/app -Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. +# (1)! +CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] +``` -#### Prometheus and Other Reasons +1. Here we use the `--workers` command line option to set the number of workers to 4. -You could also have **other reasons** that would make it easier to have a **single container** with **multiple processes** instead of having **multiple containers** with **a single process** in each of them. +Here are some examples of when that could make sense: -For example (depending on your setup) you could have some tool like a Prometheus exporter in the same container that should have access to **each of the requests** that come. +#### A Simple App + +You could want a process manager in the container if your application is **simple enough** that can run it on a **single server**, not a cluster. + +#### Docker Compose -In this case, if you had **multiple containers**, by default, when Prometheus came to **read the metrics**, it would get the ones for **a single container each time** (for the container that handled that particular request), instead of getting the **accumulated metrics** for all the replicated containers. +You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. -Then, in that case, it could be simpler to have **one container** with **multiple processes**, and a local tool (e.g. a Prometheus exporter) on the same container collecting Prometheus metrics for all the internal processes and exposing those metrics on that single container. +Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. --- @@ -541,7 +548,7 @@ And then you can set those same memory limits and requirements in your configura If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that runs in **each machine** (and maybe add more machines to your cluster). -If you run **multiple processes per container** (for example with the official Docker image) you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. +If you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. ## Previous Steps Before Starting and Containers @@ -561,80 +568,26 @@ If in your use case there's no problem in running those previous steps **multipl ### Single Container -If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. The official Docker image supports this internally. +If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. -## Official Docker Image with Gunicorn - Uvicorn +### Base Docker Image -There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](server-workers.md){.internal-link target=_blank}. +There used to be an official FastAPI Docker image: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. But it is now deprecated. ⛔️ -This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). - -* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. - -/// warning - -There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -/// +You should probably **not** use this base Docker image (or any other similar one). -This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available. +If you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). -It has **sensible defaults**, but you can still change and update all the configurations with **environment variables** or configuration files. +And if you need to have multiple workers, you can simply use the `--workers` command line option. -It also supports running <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**previous steps before starting**</a> with a script. +/// note | Technical Details -/// tip +The Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn, which added quite some complexity, just to have Gunicorn manage and restart the Uvicorn worker processes. -To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. +But now that Uvicorn (and the `fastapi` command) support using `--workers`, there's no reason to use a base Docker image instead of building your own (it's pretty much the same amount of code 😅). /// -### Number of Processes on the Official Docker Image - -The **number of processes** on this image is **computed automatically** from the CPU **cores** available. - -This means that it will try to **squeeze** as much **performance** from the CPU as possible. - -You can also adjust it with the configurations using **environment variables**, etc. - -But it also means that as the number of processes depends on the CPU the container is running, the **amount of memory consumed** will also depend on that. - -So, if your application consumes a lot of memory (for example with machine learning models), and your server has a lot of CPU cores **but little memory**, then your container could end up trying to use more memory than what is available, and degrading performance a lot (or even crashing). 🚨 - -### Create a `Dockerfile` - -Here's how you would create a `Dockerfile` based on this image: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt - -COPY ./app /app -``` - -### Bigger Applications - -If you followed the section about creating [Bigger Applications with Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}, your `Dockerfile` might instead look like: - -```Dockerfile hl_lines="7" -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt - -COPY ./app /app/app -``` - -### When to Use - -You should probably **not** use this official base image (or any other similar one) if you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -This image would be useful mainly in the special cases described above in [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). For example, if your application is **simple enough** that setting a default number of processes based on the CPU works well, you don't want to bother with manually configuring the replication at the cluster level, and you are not running more than one container with your app. Or if you are deploying with **Docker Compose**, running on a single server, etc. - ## Deploy the Container Image After having a Container (Docker) Image there are several ways to deploy it. @@ -647,98 +600,9 @@ For example: * With another tool like Nomad * With a cloud service that takes your container image and deploys it -## Docker Image with Poetry +## Docker Image with `uv` -If you use <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> to manage your project's dependencies, you could use Docker multi-stage building: - -```{ .dockerfile .annotate } -# (1) -FROM python:3.9 as requirements-stage - -# (2) -WORKDIR /tmp - -# (3) -RUN pip install poetry - -# (4) -COPY ./pyproject.toml ./poetry.lock* /tmp/ - -# (5) -RUN poetry export -f requirements.txt --output requirements.txt --without-hashes - -# (6) -FROM python:3.9 - -# (7) -WORKDIR /code - -# (8) -COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt - -# (9) -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -# (10) -COPY ./app /code/app - -# (11) -CMD ["fastapi", "run", "app/main.py", "--port", "80"] -``` - -1. This is the first stage, it is named `requirements-stage`. - -2. Set `/tmp` as the current working directory. - - Here's where we will generate the file `requirements.txt` - -3. Install Poetry in this Docker stage. - -4. Copy the `pyproject.toml` and `poetry.lock` files to the `/tmp` directory. - - Because it uses `./poetry.lock*` (ending with a `*`), it won't crash if that file is not available yet. - -5. Generate the `requirements.txt` file. - -6. This is the final stage, anything here will be preserved in the final container image. - -7. Set the current working directory to `/code`. - -8. Copy the `requirements.txt` file to the `/code` directory. - - This file only lives in the previous Docker stage, that's why we use `--from-requirements-stage` to copy it. - -9. Install the package dependencies in the generated `requirements.txt` file. - -10. Copy the `app` directory to the `/code` directory. - -11. Use the `fastapi run` command to run your app. - -/// tip - -Click the bubble numbers to see what each line does. - -/// - -A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later. - -The first stage will only be used to **install Poetry** and to **generate the `requirements.txt`** with your project dependencies from Poetry's `pyproject.toml` file. - -This `requirements.txt` file will be used with `pip` later in the **next stage**. - -In the final container image **only the final stage** is preserved. The previous stage(s) will be discarded. - -When using Poetry, it would make sense to use **Docker multi-stage builds** because you don't really need to have Poetry and its dependencies installed in the final container image, you **only need** to have the generated `requirements.txt` file to install your project dependencies. - -Then in the next (and final) stage you would build the image more or less in the same way as described before. - -### Behind a TLS Termination Proxy - Poetry - -Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command: - -```Dockerfile -CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] -``` +If you are using <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a> to install and manage your project, you can follow their <a href="https://docs.astral.sh/uv/guides/integration/docker/" class="external-link" target="_blank">uv Docker guide</a>. ## Recap @@ -754,5 +618,3 @@ Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fai In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** one based on the official Python Docker image. Taking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎 - -In certain special cases, you might want to use the official Docker image for FastAPI. 🤓 diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index 3324a7503..3f7c7a008 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -67,6 +67,8 @@ There are several alternatives, including: * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: a high performance ASGI server. * <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: an ASGI server compatible with HTTP/2 and Trio among other features. * <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: the ASGI server built for Django Channels. +* <a href="https://github.com/emmett-framework/granian" class="external-link" target="_blank">Granian</a>: A Rust HTTP server for Python applications. +* <a href="https://unit.nginx.org/howto/fastapi/" class="external-link" target="_blank">NGINX Unit</a>: NGINX Unit is a lightweight and versatile web application runtime. ## Server Machine and Server Program @@ -84,11 +86,9 @@ When you install FastAPI, it comes with a production server, Uvicorn, and you ca But you can also install an ASGI server manually. -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server application. -//// tab | Uvicorn - -* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools. +For example, to install Uvicorn: <div class="termy"> @@ -100,6 +100,8 @@ $ pip install "uvicorn[standard]" </div> +A similar process would apply to any other ASGI server program. + /// tip By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. @@ -110,32 +112,10 @@ When you install FastAPI with something like `pip install "fastapi[standard]"` y /// -//// - -//// tab | Hypercorn - -* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2. - -<div class="termy"> - -```console -$ pip install hypercorn - ----> 100% -``` - -</div> - -...or any other ASGI server. - -//// - ## Run the Server Program If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application: -//// tab | Uvicorn - <div class="termy"> ```console @@ -146,22 +126,6 @@ $ uvicorn main:app --host 0.0.0.0 --port 80 </div> -//// - -//// tab | Hypercorn - -<div class="termy"> - -```console -$ hypercorn main:app --bind 0.0.0.0:80 - -Running on 0.0.0.0:8080 over http (CTRL + C to quit) -``` - -</div> - -//// - /// note The command `uvicorn main:app` refers to: @@ -177,9 +141,11 @@ from main import app /// +Each alternative ASGI server program would have a similar command, you can read more in their respective documentation. + /// warning -Uvicorn and others support a `--reload` option that is useful during development. +Uvicorn and other servers support a `--reload` option that is useful during development. The `--reload` option consumes much more resources, is more unstable, etc. @@ -187,43 +153,6 @@ It helps a lot during **development**, but you **shouldn't** use it in **product /// -## Hypercorn with Trio - -Starlette and **FastAPI** are based on <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a>, which makes them compatible with both Python's standard library <a href="https://docs.python.org/3/library/asyncio-task.html" class="external-link" target="_blank">asyncio</a> and <a href="https://trio.readthedocs.io/en/stable/" class="external-link" target="_blank">Trio</a>. - -Nevertheless, Uvicorn is currently only compatible with asyncio, and it normally uses <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a>, the high-performance drop-in replacement for `asyncio`. - -But if you want to directly use **Trio**, then you can use **Hypercorn** as it supports it. ✨ - -### Install Hypercorn with Trio - -First you need to install Hypercorn with Trio support: - -<div class="termy"> - -```console -$ pip install "hypercorn[trio]" ----> 100% -``` - -</div> - -### Run with Trio - -Then you can pass the command line option `--worker-class` with the value `trio`: - -<div class="termy"> - -```console -$ hypercorn main:app --worker-class trio -``` - -</div> - -And that will start Hypercorn with your app using Trio as the backend. - -Now you can use Trio internally in your app. Or even better, you can use AnyIO, to keep your code compatible with both Trio and asyncio. 🎉 - ## Deployment Concepts These examples run the server program (e.g Uvicorn), starting **a single process**, listening on all the IPs (`0.0.0.0`) on a predefined port (e.g. `80`). diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index efde5f3a1..5e369e071 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -1,4 +1,4 @@ -# Server Workers - Gunicorn with Uvicorn +# Server Workers - Uvicorn with Workers Let's check back those deployment concepts from before: @@ -9,125 +9,92 @@ Let's check back those deployment concepts from before: * Memory * Previous steps before starting -Up to this point, with all the tutorials in the docs, you have probably been running a **server program** like Uvicorn, running a **single process**. +Up to this point, with all the tutorials in the docs, you have probably been running a **server program**, for example, using the `fastapi` command, that runs Uvicorn, running a **single process**. When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests. As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. -Here I'll show you how to use <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> with **Uvicorn worker processes**. +Here I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly. /// info If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. -In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. +In particular, when running on **Kubernetes** you will probably **not** want to use workers and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. /// -## Gunicorn with Uvicorn Workers +## Multiple Workers -**Gunicorn** is mainly an application server using the **WSGI standard**. That means that Gunicorn can serve applications like Flask and Django. Gunicorn by itself is not compatible with **FastAPI**, as FastAPI uses the newest **<a href="https://asgi.readthedocs.io/en/latest/" class="external-link" target="_blank">ASGI standard</a>**. +You can start multiple workers with the `--workers` command line option: -But Gunicorn supports working as a **process manager** and allowing users to tell it which specific **worker process class** to use. Then Gunicorn would start one or more **worker processes** using that class. +//// tab | `fastapi` -And **Uvicorn** has a **Gunicorn-compatible worker class**. - -Using that combination, Gunicorn would act as a **process manager**, listening on the **port** and the **IP**. And it would **transmit** the communication to the worker processes running the **Uvicorn class**. - -And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of converting the data sent by Gunicorn to the ASGI standard for FastAPI to use it. - -## Install Gunicorn and Uvicorn - -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `gunicorn`: +If you use the `fastapi` command: <div class="termy"> ```console -$ pip install "uvicorn[standard]" gunicorn - ----> 100% +$ <pre> <font color="#4E9A06">fastapi</font> run --workers 4 <u style="text-decoration-style:single">main.py</u> +<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font> +<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font> +<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files +<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> + + ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font> +<font color="#3465A4">INFO </font> Found importable FastAPI app + + ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ + │ │ + │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ + │ │ + ╰──────────────────────────╯ + +<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> + + <font color="#4E9A06">╭─────────── FastAPI CLI - Production mode ───────────╮</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ Serving at: http://0.0.0.0:8000 │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ API docs: http://0.0.0.0:8000/docs │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ Running in production mode, for development use: │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">│ </font><font color="#8AE234"><b>fastapi dev</b></font><font color="#4E9A06"> │</font> + <font color="#4E9A06">│ │</font> + <font color="#4E9A06">╰─────────────────────────────────────────────────────╯</font> + +<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://0.0.0.0:8000</b> (Press CTRL+C to quit) +<font color="#4E9A06">INFO</font>: Started parent process [<font color="#34E2E2"><b>27365</b></font>] +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27368</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27369</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27370</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">27367</font>] +<font color="#4E9A06">INFO</font>: Waiting for application startup. +<font color="#4E9A06">INFO</font>: Application startup complete. +</pre> ``` </div> -That will install both Uvicorn with the `standard` extra packages (to get high performance) and Gunicorn. +//// -## Run Gunicorn with Uvicorn Workers +//// tab | `uvicorn` -Then you can run Gunicorn with: - -<div class="termy"> - -```console -$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 - -[19499] [INFO] Starting gunicorn 20.1.0 -[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) -[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker -[19511] [INFO] Booting worker with pid: 19511 -[19513] [INFO] Booting worker with pid: 19513 -[19514] [INFO] Booting worker with pid: 19514 -[19515] [INFO] Booting worker with pid: 19515 -[19511] [INFO] Started server process [19511] -[19511] [INFO] Waiting for application startup. -[19511] [INFO] Application startup complete. -[19513] [INFO] Started server process [19513] -[19513] [INFO] Waiting for application startup. -[19513] [INFO] Application startup complete. -[19514] [INFO] Started server process [19514] -[19514] [INFO] Waiting for application startup. -[19514] [INFO] Application startup complete. -[19515] [INFO] Started server process [19515] -[19515] [INFO] Waiting for application startup. -[19515] [INFO] Application startup complete. -``` - -</div> - -Let's see what each of those options mean: - -* `main:app`: This is the same syntax used by Uvicorn, `main` means the Python module named "`main`", so, a file `main.py`. And `app` is the name of the variable that is the **FastAPI** application. - * You can imagine that `main:app` is equivalent to a Python `import` statement like: - - ```Python - from main import app - ``` - - * So, the colon in `main:app` would be equivalent to the Python `import` part in `from main import app`. - -* `--workers`: The number of worker processes to use, each will run a Uvicorn worker, in this case, 4 workers. - -* `--worker-class`: The Gunicorn-compatible worker class to use in the worker processes. - * Here we pass the class that Gunicorn can import and use with: - - ```Python - import uvicorn.workers.UvicornWorker - ``` - -* `--bind`: This tells Gunicorn the IP and the port to listen to, using a colon (`:`) to separate the IP and the port. - * If you were running Uvicorn directly, instead of `--bind 0.0.0.0:80` (the Gunicorn option) you would use `--host 0.0.0.0` and `--port 80`. - -In the output, you can see that it shows the **PID** (process ID) of each process (it's just a number). - -You can see that: - -* The Gunicorn **process manager** starts with PID `19499` (in your case it will be a different number). -* Then it starts `Listening at: http://0.0.0.0:80`. -* Then it detects that it has to use the worker class at `uvicorn.workers.UvicornWorker`. -* And then it starts **4 workers**, each with its own PID: `19511`, `19513`, `19514`, and `19515`. - -Gunicorn would also take care of managing **dead processes** and **restarting** new ones if needed to keep the number of workers. So that helps in part with the **restart** concept from the list above. - -Nevertheless, you would probably also want to have something outside making sure to **restart Gunicorn** if necessary, and also to **run it on startup**, etc. - -## Uvicorn with Workers - -Uvicorn also has an option to start and run several **worker processes**. - -Nevertheless, as of now, Uvicorn's capabilities for handling worker processes are more limited than Gunicorn's. So, if you want to have a process manager at this level (at the Python level), then it might be better to try with Gunicorn as the process manager. - -In any case, you would run it like this: +If you prefer to use the `uvicorn` command directly: <div class="termy"> @@ -151,13 +118,15 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 </div> +//// + The only new option here is `--workers` telling Uvicorn to start 4 worker processes. You can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`. ## Deployment Concepts -Here you saw how to use **Gunicorn** (or Uvicorn) managing **Uvicorn worker processes** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. +Here you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. From the list of deployment concepts from above, using workers would mainly help with the **replication** part, and a little bit with the **restarts**, but you still need to take care of the others: @@ -172,13 +141,11 @@ From the list of deployment concepts from above, using workers would mainly help In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. -I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases. - -There I'll also show you how to **build your own image from scratch** to run a single Uvicorn process (without Gunicorn). It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. +I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. ## Recap -You can use **Gunicorn** (or also Uvicorn) as a process manager with Uvicorn workers to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. +You can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. You could use these tools and ideas if you are setting up **your own deployment system** while taking care of the other deployment concepts yourself. diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index e387d5712..23f49cf99 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -30,7 +30,7 @@ fastapi[standard]>=0.112.0,<0.113.0 that would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted. -If you use any other tool to manage your installations, like Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. +If you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. ## Available versions diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 230f9c08c..1c33fd051 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -519,12 +519,12 @@ As we cannot just isolate them and "mount" them independently of the rest, the * ## Check the automatic API docs -Now, run `uvicorn`, using the module `app.main` and the variable `app`: +Now, run your app: <div class="termy"> ```console -$ uvicorn app.main:app --reload +$ fastapi dev app/main.py <span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` From 3a96938771c67a9cc343a38b143f55b618817bd3 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sun, 25 Aug 2024 02:44:27 +0000 Subject: [PATCH 813/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ac8f16f53..b5b3188ef 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). From 5fdbeed7928231a249d479c0c266f83877cafce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 25 Aug 2024 21:14:56 -0500 Subject: [PATCH 814/846] =?UTF-8?q?=F0=9F=91=B7=20Update=20`latest-changes?= =?UTF-8?q?`=20GitHub=20Action=20(#12073)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/latest-changes.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 27e062d09..16da3bc63 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,8 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.3.0 - # - uses: tiangolo/latest-changes@main + - uses: tiangolo/latest-changes@0.3.1 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md From 9416e89bd7e3491157f8c962012aebd7be7ed5d6 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Mon, 26 Aug 2024 02:15:38 +0000 Subject: [PATCH 815/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b5b3188ef..1dff0bddc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). +### Internal + +* 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.2 ### Fixes From f41f6234af886914ebd3022faad80bb6320bb1bf Mon Sep 17 00:00:00 2001 From: lkw123 <2020393267@qq.com> Date: Wed, 28 Aug 2024 21:48:13 +0800 Subject: [PATCH 816/846] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/how-to/index.md`=20(#12070)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/how-to/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md index 262dcfaee..ac097618b 100644 --- a/docs/zh/docs/how-to/index.md +++ b/docs/zh/docs/how-to/index.md @@ -6,7 +6,7 @@ 如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 -/// 小技巧 +/// tip | 小技巧 如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 From be9abcf35315cff34d30e86ce7d2deec3e3df9be Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 28 Aug 2024 13:48:40 +0000 Subject: [PATCH 817/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1dff0bddc..20caacd64 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). +### Translations + +* 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). + ### Internal * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From 4909e44a7ff9b7048f7e6db8c7ad72283fd6a30d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 28 Aug 2024 09:07:00 -0500 Subject: [PATCH 818/846] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12076)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.1 → v0.6.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.1...v0.6.2) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7532f21b5..317514062 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.1 + rev: v0.6.2 hooks: - id: ruff args: From 48bf0db58fb5008c78d758d830e0d58f34edfb62 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 28 Aug 2024 14:07:23 +0000 Subject: [PATCH 819/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 20caacd64..baf25d451 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). ## 0.112.2 From cabed9efb6a6b615f3bf45e9e523ff290f252f0f Mon Sep 17 00:00:00 2001 From: Alec Gillis <alec.gillis@quorum.us> Date: Wed, 28 Aug 2024 16:33:37 -0700 Subject: [PATCH 820/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20comma=20in=20`d?= =?UTF-8?q?ocs/en/docs/async.md`=20(#12062)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alec Gillis <alecgillis@quorum.us> Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> --- docs/en/docs/async.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 752a5c247..63bd8ca68 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -387,7 +387,7 @@ In previous versions of NodeJS / Browser JavaScript, you would have used "callba ## Coroutines -**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. +**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines". From a930128910f65e53bdff76f4e52f484e5129f60b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 28 Aug 2024 23:35:03 +0000 Subject: [PATCH 821/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index baf25d451..838516421 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). From 9b35d355bfb44c33000359a2b24f215286996693 Mon Sep 17 00:00:00 2001 From: Muhammad Ashiq Ameer <46787072+MuhammadAshiqAmeer@users.noreply.github.com> Date: Thu, 29 Aug 2024 05:09:15 +0530 Subject: [PATCH 822/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20`docs=5Fsrc/pat?= =?UTF-8?q?h=5Fparams=5Fnumeric=5Fvalidations/tutorial006.py`=20(#11478)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> --- docs_src/path_params_numeric_validations/tutorial006.py | 2 ++ docs_src/path_params_numeric_validations/tutorial006_an.py | 2 ++ docs_src/path_params_numeric_validations/tutorial006_an_py39.py | 2 ++ 3 files changed, 6 insertions(+) diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py index 0ea32694a..f07629aa0 100644 --- a/docs_src/path_params_numeric_validations/tutorial006.py +++ b/docs_src/path_params_numeric_validations/tutorial006.py @@ -13,4 +13,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py index 22a143623..ac4732573 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an.py @@ -14,4 +14,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py index 804751893..426ec3776 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py @@ -15,4 +15,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results From 33328952518b78ed40d5f58cf21f3e40e48f6615 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 28 Aug 2024 23:40:13 +0000 Subject: [PATCH 823/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 838516421..34a3fbc57 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). From ae27540348d943e786e83176a8fc32d535baece7 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem <svlandeg@users.noreply.github.com> Date: Thu, 29 Aug 2024 01:41:46 +0200 Subject: [PATCH 824/846] =?UTF-8?q?=F0=9F=8C=90=20Add=20Dutch=20translatio?= =?UTF-8?q?n=20for=20`docs/nl/docs/index.md`=20(#12042)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Max Scheijen <maxscheijen@gmail.com> --- docs/en/mkdocs.yml | 2 + docs/nl/docs/index.md | 494 ++++++++++++++++++++++++++++++++++++++++++ docs/nl/mkdocs.yml | 1 + 3 files changed, 497 insertions(+) create mode 100644 docs/nl/docs/index.md create mode 100644 docs/nl/mkdocs.yml diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 6f1e12511..528c80b8e 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -363,6 +363,8 @@ extra: name: ja - 日本語 - link: /ko/ name: ko - 한국어 + - link: /nl/ + name: nl - Nederlands - link: /pl/ name: pl - Polski - link: /pt/ diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md new file mode 100644 index 000000000..8edc3ba0c --- /dev/null +++ b/docs/nl/docs/index.md @@ -0,0 +1,494 @@ +# FastAPI + +<style> +.md-content .md-typeset h1 { display: none; } +</style> + +<p align="center"> + <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> +</p> +<p align="center"> + <em>FastAPI framework, zeer goede prestaties, eenvoudig te leren, snel te programmeren, klaar voor productie</em> +</p> +<p align="center"> +<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> + <img src="https://github.com/fastapi/fastapi/workflows/Test/badge.svg?event=push&branch=master" alt="Test"> +</a> +<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank"> + <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage"> +</a> +<a href="https://pypi.org/project/fastapi" target="_blank"> + <img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version"> +</a> +<a href="https://pypi.org/project/fastapi" target="_blank"> + <img src="https://img.shields.io/pypi/pyversions/fastapi.svg?color=%2334D058" alt="Supported Python versions"> +</a> +</p> + +--- + +**Documentatie**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> + +**Broncode**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> + +--- + +FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints. + +De belangrijkste kenmerken zijn: + +* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties). +* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. * +* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. * +* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. <abbr title="ook bekend als automatisch aanvullen, automatisch aanvullen, IntelliSense">Overal automische code aanvulling</abbr>. Minder tijd kwijt aan debuggen. +* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen. +* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs. +* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie. +* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (voorheen bekend als Swagger) en <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>. + +<small>* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties.</small> + +## Sponsors + +<!-- sponsors --> + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor -%} +{%- for sponsor in sponsors.silver -%} +<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> +{% endfor %} +{% endif %} + +<!-- /sponsors --> + +<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Overige sponsoren</a> + +## Meningen + +"_[...] Ik gebruik **FastAPI** heel vaak tegenwoordig. [...] Ik ben van plan om het te gebruiken voor alle **ML-services van mijn team bij Microsoft**. Sommige van deze worden geïntegreerd in het kernproduct van **Windows** en sommige **Office**-producten._" + +<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> + +--- + +"_We hebben de **FastAPI** library gebruikt om een **REST** server te maken die bevraagd kan worden om **voorspellingen** te maken. [voor Ludwig]_" + +<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin en Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div> + +--- + +"_**Netflix** is verheugd om een open-source release aan te kondigen van ons **crisismanagement**-orkestratieframework: **Dispatch**! [gebouwd met **FastAPI**]_" + +<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div> + +--- + +"_Ik ben super enthousiast over **FastAPI**. Het is zo leuk!_" + +<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong><a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> podcast presentator</strong> <a href="https://twitter.com/brianokken/status/1112220079972728832" target="_blank"><small>(ref)</small></a></div> + +--- + +"_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._" + +<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="https://www.hug.rest/" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div> + +--- + +"Wie geïnteresseerd is in een **modern framework** voor het bouwen van REST API's, bekijkt best eens **FastAPI** [...] Het is snel, gebruiksvriendelijk en gemakkelijk te leren [...]_" + +"_We zijn overgestapt naar **FastAPI** voor onze **API's** [...] Het gaat jou vast ook bevallen [...]_" + +<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> oprichters - <a href="https://spacy.io" target="_blank">spaCy</a> ontwikkelaars</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div> + +--- + +"_Wie een Python API wil bouwen voor productie, kan ik ten stelligste **FastAPI** aanraden. Het is **prachtig ontworpen**, **eenvoudig te gebruiken** en **gemakkelijk schaalbaar**, het is een **cruciale component** geworden in onze strategie om API's centraal te zetten, en het vereenvoudigt automatisering en diensten zoals onze Virtual TAC Engineer._" + +<div style="text-align: right; margin-right: 10%;">Deon Pillsbury - <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/" target="_blank"><small>(ref)</small></a></div> + +--- + +## **Typer**, de FastAPI van CLIs + +<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a> + +Als je een <abbr title="Command Line Interface">CLI</abbr>-app bouwt die in de terminal moet worden gebruikt in plaats van een web-API, gebruik dan <a href="https://typer.tiangolo.com/ " class="external-link" target="_blank">**Typer**</a>. + +**Typer** is het kleine broertje van FastAPI. En het is bedoeld als de **FastAPI van CLI's**. ️ + +## Vereisten + +FastAPI staat op de schouders van reuzen: + +* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> voor de webonderdelen. +* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> voor de datadelen. + +## Installatie + +<div class="termy"> + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +</div> + +**Opmerking**: Zet `"fastapi[standard]"` tussen aanhalingstekens om ervoor te zorgen dat het werkt in alle terminals. + +## Voorbeeld + +### Creëer het + +* Maak het bestand `main.py` aan met daarin: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +<details markdown="1"> +<summary>Of maak gebruik van <code>async def</code>...</summary> + +Als je code gebruik maakt van `async` / `await`, gebruik dan `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Opmerking**: + +Als je het niet weet, kijk dan in het gedeelte _"Heb je haast?"_ over <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` en `await` in de documentatie</a>. + +</details> + +### Voer het uit + +Run de server met: + +<div class="termy"> + +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +</div> + +<details markdown="1"> +<summary>Over het commando <code>fastapi dev main.py</code>...</summary> + +Het commando `fastapi dev` leest het `main.py` bestand, detecteert de **FastAPI** app, en start een server met <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>. + +Standaard zal dit commando `fastapi dev` starten met "auto-reload" geactiveerd voor ontwikkeling op het lokale systeem. + +Je kan hier meer over lezen in de <a href="https://fastapi.tiangolo.com/fastapi-cli/" target="_blank">FastAPI CLI documentatie</a>. + +</details> + +### Controleer het + +Open je browser op <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>. + +Je zult een JSON response zien: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Je hebt een API gemaakt die: + +* HTTP verzoeken kan ontvangen op de _paden_ `/` en `/items/{item_id}`. +* Beide _paden_ hebben `GET` <em>operaties</em> (ook bekend als HTTP _methoden_). +* Het _pad_ `/items/{item_id}` heeft een _pad parameter_ `item_id` dat een `int` moet zijn. +* Het _pad_ `/items/{item_id}` heeft een optionele `str` _query parameter_ `q`. + +### Interactieve API documentatie + +Ga naar <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +Je ziet de automatische interactieve API documentatie (verstrekt door <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>): + + + +### Alternatieve API documentatie + +Ga vervolgens naar <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>. + +Je ziet de automatische interactieve API documentatie (verstrekt door <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>): + + + +## Voorbeeld upgrade + +Pas nu het bestand `main.py` aan om de body van een `PUT` request te ontvangen. + +Dankzij Pydantic kunnen we de body declareren met standaard Python types. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +De `fastapi dev` server zou automatisch moeten herladen. + +### Interactieve API documentatie upgrade + +Ga nu naar <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. + +* De interactieve API-documentatie wordt automatisch bijgewerkt, inclusief de nieuwe body: + + + +* Klik op de knop "Try it out", hiermee kan je de parameters invullen en direct met de API interacteren: + + + +* Klik vervolgens op de knop "Execute", de gebruikersinterface zal communiceren met jouw API, de parameters verzenden, de resultaten ophalen en deze op het scherm tonen: + + + +### Alternatieve API documentatie upgrade + +Ga vervolgens naar <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>. + +* De alternatieve documentatie zal ook de nieuwe queryparameter en body weergeven: + + + +### Samenvatting + +Samengevat declareer je **eenmalig** de types van parameters, body, etc. als functieparameters. + +Dat doe je met standaard moderne Python types. + +Je hoeft geen nieuwe syntax te leren, de methods of klassen van een specifieke bibliotheek, etc. + +Gewoon standaard **Python**. + +Bijvoorbeeld, voor een `int`: + +```Python +item_id: int +``` + +of voor een complexer `Item` model: + +```Python +item: Item +``` + +...en met die ene verklaring krijg je: + +* Editor ondersteuning, inclusief: + * Code aanvulling. + * Type validatie. +* Validatie van data: + * Automatische en duidelijke foutboodschappen wanneer de data ongeldig is. + * Validatie zelfs voor diep geneste JSON objecten. +* <abbr title="ook bekend als: serialisatie, parsing, marshalling">Conversie</abbr> van invoergegevens: afkomstig van het netwerk naar Python-data en -types. Zoals: + * JSON. + * Pad parameters. + * Query parameters. + * Cookies. + * Headers. + * Formulieren. + * Bestanden. +* <abbr title="ook bekend als: serialisatie, parsing, marshalling">Conversie</abbr> van uitvoergegevens: converstie van Python-data en -types naar netwerkgegevens (zoals JSON): + * Converteer Python types (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` objecten. + * `UUID` objecten. + * Database modellen. + * ...en nog veel meer. +* Automatische interactieve API-documentatie, inclusief 2 alternatieve gebruikersinterfaces: + * Swagger UI. + * ReDoc. + +--- + +Terugkomend op het vorige code voorbeeld, **FastAPI** zal: + +* Valideren dat er een `item_id` bestaat in het pad voor `GET` en `PUT` verzoeken. +* Valideren dat het `item_id` van het type `int` is voor `GET` en `PUT` verzoeken. + * Wanneer dat niet het geval is, krijgt de cliënt een nuttige, duidelijke foutmelding. +* Controleren of er een optionele query parameter is met de naam `q` (zoals in `http://127.0.0.1:8000/items/foo?q=somequery`) voor `GET` verzoeken. + * Aangezien de `q` parameter werd gedeclareerd met `= None`, is deze optioneel. + * Zonder de `None` declaratie zou deze verplicht zijn (net als bij de body in het geval met `PUT`). +* Voor `PUT` verzoeken naar `/items/{item_id}`, lees de body als JSON: + * Controleer of het een verplicht attribuut `naam` heeft en dat dat een `str` is. + * Controleer of het een verplicht attribuut `price` heeft en dat dat een`float` is. + * Controleer of het een optioneel attribuut `is_offer` heeft, dat een `bool` is wanneer het aanwezig is. + * Dit alles werkt ook voor diep geneste JSON objecten. +* Converteer automatisch van en naar JSON. +* Documenteer alles met OpenAPI, dat gebruikt kan worden door: + * Interactieve documentatiesystemen. + * Automatische client code generatie systemen, voor vele talen. +* Biedt 2 interactieve documentatie-webinterfaces aan. + +--- + +Dit was nog maar een snel overzicht, maar je zou nu toch al een idee moeten hebben over hoe het allemaal werkt. + +Probeer deze regel te veranderen: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...van: + +```Python + ... "item_name": item.name ... +``` + +...naar: + +```Python + ... "item_price": item.price ... +``` + +...en zie hoe je editor de attributen automatisch invult en hun types herkent: + + + +Voor een vollediger voorbeeld met meer mogelijkheden, zie de <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - Gebruikershandleiding</a>. + +**Spoiler alert**: de tutorial - gebruikershandleiding bevat: + +* Declaratie van **parameters** op andere plaatsen zoals: **headers**, **cookies**, **formuliervelden** en **bestanden**. +* Hoe stel je **validatie restricties** in zoals `maximum_length` of een `regex`. +* Een zeer krachtig en eenvoudig te gebruiken **<abbr title="ook bekend als componenten, middelen, verstrekkers, diensten, injectables">Dependency Injection</abbr>** systeem. +* Beveiliging en authenticatie, inclusief ondersteuning voor **OAuth2** met **JWT-tokens** en **HTTP Basic** auth. +* Meer geavanceerde (maar even eenvoudige) technieken voor het declareren van **diep geneste JSON modellen** (dankzij Pydantic). +* **GraphQL** integratie met <a href="https://strawberry.rocks" class="external-link" target="_blank">Strawberry</a> en andere packages. +* Veel extra functies (dankzij Starlette) zoals: + * **WebSockets** + * uiterst gemakkelijke tests gebaseerd op HTTPX en `pytest` + * **CORS** + * **Cookie Sessions** + * ...en meer. + +## Prestaties + +Onafhankelijke TechEmpower benchmarks tonen **FastAPI** applicaties draaiend onder Uvicorn aan als <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">een van de snelste Python frameworks beschikbaar</a>, alleen onder Starlette en Uvicorn zelf (intern gebruikt door FastAPI). (*) + +Zie de sectie <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a> om hier meer over te lezen. + +## Afhankelijkheden + +FastAPI maakt gebruik van Pydantic en Starlette. + +### `standard` Afhankelijkheden + +Wanneer je FastAPI installeert met `pip install "fastapi[standard]"`, worden de volgende `standard` optionele afhankelijkheden geïnstalleerd: + +Gebruikt door Pydantic: + +* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - voor email validatie. + +Gebruikt door Starlette: + +* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Vereist indien je de `TestClient` wil gebruiken. +* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Vereist als je de standaard templateconfiguratie wil gebruiken. +* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Vereist indien je <abbr title="het omzetten van de string die uit een HTTP verzoek komt in Python data">"parsen"</abbr> van formulieren wil ondersteunen met `requests.form()`. + +Gebruikt door FastAPI / Starlette: + +* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - voor de server die jouw applicatie laadt en bedient. +* `fastapi-cli` - om het `fastapi` commando te voorzien. + +### Zonder `standard` Afhankelijkheden + +Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`. + +### Bijkomende Optionele Afhankelijkheden + +Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren. + +Bijkomende optionele afhankelijkheden voor Pydantic: + +* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - voor het beheren van settings. +* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - voor extra data types die gebruikt kunnen worden met Pydantic. + +Bijkomende optionele afhankelijkheden voor FastAPI: + +* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Vereist indien je `ORJSONResponse` wil gebruiken. +* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Vereist indien je `UJSONResponse` wil gebruiken. + +## Licentie + +Dit project is gelicenseerd onder de voorwaarden van de MIT licentie. diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/nl/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml From ffa6d2eafd8955d3157e77119e07a8b7c09efef2 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Wed, 28 Aug 2024 23:44:01 +0000 Subject: [PATCH 825/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 34a3fbc57..6cfbe779b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Translations +* 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). * 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). ### Internal From 4cf3421178d3ecd909cb393f39e52eed5744e44a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Wed, 28 Aug 2024 19:01:29 -0500 Subject: [PATCH 826/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20rem?= =?UTF-8?q?ove=20Kong=20(#12085)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- docs/en/overrides/main.html | 6 ------ 3 files changed, 10 deletions(-) diff --git a/README.md b/README.md index ec7a95497..d8de34e0c 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,6 @@ The key features are: <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> <a href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> -<a href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a> <a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a> <a href="https://fine.dev?ref=fastapibadge" target="_blank" title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"><img src="https://fastapi.tiangolo.com/img/sponsors/fine.png"></a> <a href="https://liblab.com?utm_source=fastapi" target="_blank" title="liblab - Generate SDKs from FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/liblab.png"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 8c0956ac5..76e20638a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -23,9 +23,6 @@ gold: - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral title: Simplify Full Stack Development with FastAPI & MongoDB img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png - - url: https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api - title: Kong Konnect - API management platform - img: https://fastapi.tiangolo.com/img/sponsors/kong.png - url: https://zuplo.link/fastapi-gh title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 229cbca71..851f8e895 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -70,12 +70,6 @@ <img class="sponsor-image" src="/img/sponsors/mongodb-banner.png" /> </a> </div> - <div class="item"> - <a title="Kong Konnect - API management platform" style="display: block; position: relative;" href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank"> - <span class="sponsor-badge">sponsor</span> - <img class="sponsor-image" src="/img/sponsors/kong-banner.png" /> - </a> - </div> <div class="item"> <a title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI" style="display: block; position: relative;" href="https://zuplo.link/fastapi-web" target="_blank"> <span class="sponsor-badge">sponsor</span> From 17a29149e4a40dd756f0eb02a9317229e6b3e718 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Thu, 29 Aug 2024 00:02:01 +0000 Subject: [PATCH 827/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6cfbe779b..71e7334ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From 6e98249c2121959b5253cecc1237ee5438f98758 Mon Sep 17 00:00:00 2001 From: Marcin Sulikowski <marcin.k.sulikowski@gmail.com> Date: Fri, 30 Aug 2024 18:00:41 +0200 Subject: [PATCH 828/846] =?UTF-8?q?=F0=9F=93=9D=20Fix=20async=20test=20exa?= =?UTF-8?q?mple=20not=20to=20trigger=20DeprecationWarning=20(#12084)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/async-tests.md | 2 +- docs/em/docs/advanced/async-tests.md | 2 +- docs/en/docs/advanced/async-tests.md | 2 +- docs/pt/docs/advanced/async-tests.md | 2 +- docs_src/async_tests/test_main.py | 6 ++++-- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 9f0bd4aa2..e56841faa 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wi Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 324b4f68a..11f885fe6 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index ac459ff0c..580d9142c 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Note that the test function is now `async def` instead of just `def` as before w Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index ab5bfa648..7cac26262 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs_src/async_tests/test_main.py b/docs_src/async_tests/test_main.py index 9f1527d5f..a57a31f7d 100644 --- a/docs_src/async_tests/test_main.py +++ b/docs_src/async_tests/test_main.py @@ -1,12 +1,14 @@ import pytest -from httpx import AsyncClient +from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): - async with AsyncClient(app=app, base_url="http://test") as ac: + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as ac: response = await ac.get("/") assert response.status_code == 200 assert response.json() == {"message": "Tomato"} From 4eec14fa8c8870898cfa0416b6ff20a724c0dd30 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 30 Aug 2024 16:01:05 +0000 Subject: [PATCH 829/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 71e7334ad..83080e0aa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). From 9519380764a371c4c642f969e8f1b82822f7de28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Fri, 30 Aug 2024 18:20:21 +0200 Subject: [PATCH 830/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20Coh?= =?UTF-8?q?erence=20(#12093)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/data/sponsors.yml | 2 +- docs/en/docs/deployment/cloud.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d8de34e0c..5554f71d4 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The key features are: <a href="https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor" target="_blank" title="Automate FastAPI documentation generation with Bump.sh"><img src="https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg"></a> <a href="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge" target="_blank" title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files"><img src="https://fastapi.tiangolo.com/img/sponsors/scalar.svg"></a> <a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a> -<a href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> +<a href="https://docs.withcoherence.com/coherence-templates/full-stack-template/#fastapi?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a> <a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a> <a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a> <a href="https://fine.dev?ref=fastapibadge" target="_blank" title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"><img src="https://fastapi.tiangolo.com/img/sponsors/fine.png"></a> diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 76e20638a..3a767b6b1 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -17,7 +17,7 @@ gold: - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png - - url: https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example + - url: https://docs.withcoherence.com/coherence-templates/full-stack-template/#fastapi?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs title: Coherence img: https://fastapi.tiangolo.com/img/sponsors/coherence.png - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index d34fbe2f7..3ea5087f8 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -14,4 +14,4 @@ You might want to try their services and follow their guides: * <a href="https://docs.platform.sh/languages/python.html?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" class="external-link" target="_blank">Platform.sh</a> * <a href="https://docs.porter.run/language-specific-guides/fastapi" class="external-link" target="_blank">Porter</a> -* <a href="https://docs.withcoherence.com/docs/configuration/frameworks?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024#fast-api-example" class="external-link" target="_blank">Coherence</a> +* <a href="https://docs.withcoherence.com/coherence-templates/full-stack-template/#fastapi?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs" class="external-link" target="_blank">Coherence</a> From a2458d594facb238f42dc471754612109b5f5c2d Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Fri, 30 Aug 2024 16:20:42 +0000 Subject: [PATCH 831/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 83080e0aa..2f7fb0cbd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). From 5827b922c3ebf999eae867dbb855c0bf2aa07a7e Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 03:23:14 +0000 Subject: [PATCH 832/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f7fb0cbd..d1ac98ed1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). From c37f2c976dfe71ac46ccc082b551d41cb7b6122f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 31 Aug 2024 12:15:50 +0200 Subject: [PATCH 833/846] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20about=20`ti?= =?UTF-8?q?me.perf=5Fcounter()`=20in=20middlewares=20(#12095)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/middleware.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 06fb3f504..199b593d3 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -63,6 +63,12 @@ For example, you could add a custom header `X-Process-Time` containing the time {!../../../docs_src/middleware/tutorial001.py!} ``` +/// tip + +Here we use <a href="https://docs.python.org/3/library/time.html#time.perf_counter" class="external-link" target="_blank">`time.perf_counter()`</a> instead of `time.time()` because it can be more precise for these use cases. 🤓 + +/// + ## Other middlewares You can later read more about other middlewares in the [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. From 6c8a205db106835c2cd4af5d0b5110f562c2a92f Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 10:16:12 +0000 Subject: [PATCH 834/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d1ac98ed1..e0e9192bd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). * 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). From 0077af97195ec77ab2fcc5a3cf1536c7ed6125d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 31 Aug 2024 12:18:37 +0200 Subject: [PATCH 835/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20labeler=20confi?= =?UTF-8?q?g=20to=20handle=20sponsorships=20data=20(#12096)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/labeler.yml b/.github/labeler.yml index 1d49a2411..c5b1f84f3 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -7,6 +7,8 @@ docs: - all-globs-to-all-files: - '!fastapi/**' - '!pyproject.toml' + - '!docs/en/data/sponsors.yml' + - '!docs/en/overrides/main.html' lang-all: - all: @@ -28,6 +30,8 @@ internal: - .pre-commit-config.yaml - pdm_build.py - requirements*.txt + - docs/en/data/sponsors.yml + - docs/en/overrides/main.html - all-globs-to-all-files: - '!docs/*/docs/**' - '!fastapi/**' From 83422b1923b070da891bfacec707f4d2c796a32c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 10:20:40 +0000 Subject: [PATCH 836/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e0e9192bd..a87ce21d4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Internal +* 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From eebc6c3d54f96cfd056c0a6fe4de7c3b0064ac42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 31 Aug 2024 17:35:58 +0200 Subject: [PATCH 837/846] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors=20link?= =?UTF-8?q?:=20Coherence=20(#12097)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/overrides/main.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 851f8e895..47e46c4bf 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -59,7 +59,7 @@ </a> </div> <div class="item"> - <a title="Coherence" style="display: block; position: relative;" href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank"> + <a title="Coherence" style="display: block; position: relative;" href="https://docs.withcoherence.com/coherence-templates/full-stack-template/#fastapi?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs" target="_blank"> <span class="sponsor-badge">sponsor</span> <img class="sponsor-image" src="/img/sponsors/coherence-banner.png" /> </a> From 47b3351be9c268a3b79faf9b41bf08921dbc8a8b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 15:36:24 +0000 Subject: [PATCH 838/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a87ce21d4..855338742 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Internal +* 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 581aacc4a9f3bbb872b082ee55535fe60655de2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 31 Aug 2024 22:19:30 +0200 Subject: [PATCH 839/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20s?= =?UTF-8?q?implify=20dependencies=20data=20structures=20with=20dataclasses?= =?UTF-8?q?=20(#12098)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/models.py | 75 ++++++++++++---------------------- fastapi/dependencies/utils.py | 2 +- 2 files changed, 28 insertions(+), 49 deletions(-) diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py index 61ef00638..418c11725 100644 --- a/fastapi/dependencies/models.py +++ b/fastapi/dependencies/models.py @@ -1,58 +1,37 @@ -from typing import Any, Callable, List, Optional, Sequence +from dataclasses import dataclass, field +from typing import Any, Callable, List, Optional, Sequence, Tuple from fastapi._compat import ModelField from fastapi.security.base import SecurityBase +@dataclass class SecurityRequirement: - def __init__( - self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None - ): - self.security_scheme = security_scheme - self.scopes = scopes + security_scheme: SecurityBase + scopes: Optional[Sequence[str]] = None +@dataclass class Dependant: - def __init__( - self, - *, - path_params: Optional[List[ModelField]] = None, - query_params: Optional[List[ModelField]] = None, - header_params: Optional[List[ModelField]] = None, - cookie_params: Optional[List[ModelField]] = None, - body_params: Optional[List[ModelField]] = None, - dependencies: Optional[List["Dependant"]] = None, - security_schemes: Optional[List[SecurityRequirement]] = None, - name: Optional[str] = None, - call: Optional[Callable[..., Any]] = None, - request_param_name: Optional[str] = None, - websocket_param_name: Optional[str] = None, - http_connection_param_name: Optional[str] = None, - response_param_name: Optional[str] = None, - background_tasks_param_name: Optional[str] = None, - security_scopes_param_name: Optional[str] = None, - security_scopes: Optional[List[str]] = None, - use_cache: bool = True, - path: Optional[str] = None, - ) -> None: - self.path_params = path_params or [] - self.query_params = query_params or [] - self.header_params = header_params or [] - self.cookie_params = cookie_params or [] - self.body_params = body_params or [] - self.dependencies = dependencies or [] - self.security_requirements = security_schemes or [] - self.request_param_name = request_param_name - self.websocket_param_name = websocket_param_name - self.http_connection_param_name = http_connection_param_name - self.response_param_name = response_param_name - self.background_tasks_param_name = background_tasks_param_name - self.security_scopes = security_scopes - self.security_scopes_param_name = security_scopes_param_name - self.name = name - self.call = call - self.use_cache = use_cache - # Store the path to be able to re-generate a dependable from it in overrides - self.path = path - # Save the cache key at creation to optimize performance + path_params: List[ModelField] = field(default_factory=list) + query_params: List[ModelField] = field(default_factory=list) + header_params: List[ModelField] = field(default_factory=list) + cookie_params: List[ModelField] = field(default_factory=list) + body_params: List[ModelField] = field(default_factory=list) + dependencies: List["Dependant"] = field(default_factory=list) + security_requirements: List[SecurityRequirement] = field(default_factory=list) + name: Optional[str] = None + call: Optional[Callable[..., Any]] = None + request_param_name: Optional[str] = None + websocket_param_name: Optional[str] = None + http_connection_param_name: Optional[str] = None + response_param_name: Optional[str] = None + background_tasks_param_name: Optional[str] = None + security_scopes_param_name: Optional[str] = None + security_scopes: Optional[List[str]] = None + use_cache: bool = True + path: Optional[str] = None + cache_key: Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] = field(init=False) + + def __post_init__(self) -> None: self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or [])))) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 3e8e7b410..85703c9e9 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -175,7 +175,7 @@ def get_flat_dependant( header_params=dependant.header_params.copy(), cookie_params=dependant.cookie_params.copy(), body_params=dependant.body_params.copy(), - security_schemes=dependant.security_requirements.copy(), + security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) From 75c4e7fc44fda0c63d5627af65cb0ba7919fd334 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 20:19:51 +0000 Subject: [PATCH 840/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 855338742..a02b722f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). From 08547e1d571df8e8cf71d8b15a767acbc38aea62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 31 Aug 2024 22:27:44 +0200 Subject: [PATCH 841/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20s?= =?UTF-8?q?implify=20internal=20`analyze=5Fparam()`=20to=20structure=20dat?= =?UTF-8?q?a=20with=20dataclasses=20instead=20of=20tuple=20(#12099)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 85703c9e9..5ebdddaf6 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,6 +1,7 @@ import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy +from dataclasses import dataclass from typing import ( Any, Callable, @@ -258,16 +259,16 @@ def get_dependant( ) for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names - type_annotation, depends, param_field = analyze_param( + param_details = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) - if depends is not None: + if param_details.depends is not None: sub_dependant = get_param_sub_dependant( param_name=param_name, - depends=depends, + depends=param_details.depends, path=path, security_scopes=security_scopes, ) @@ -275,18 +276,18 @@ def get_dependant( continue if add_non_field_param_to_dependency( param_name=param_name, - type_annotation=type_annotation, + type_annotation=param_details.type_annotation, dependant=dependant, ): assert ( - param_field is None + param_details.field is None ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" continue - assert param_field is not None - if is_body_param(param_field=param_field, is_path_param=is_path_param): - dependant.body_params.append(param_field) + assert param_details.field is not None + if is_body_param(param_field=param_details.field, is_path_param=is_path_param): + dependant.body_params.append(param_details.field) else: - add_param_to_fields(field=param_field, dependant=dependant) + add_param_to_fields(field=param_details.field, dependant=dependant) return dependant @@ -314,13 +315,20 @@ def add_non_field_param_to_dependency( return None +@dataclass +class ParamDetails: + type_annotation: Any + depends: Optional[params.Depends] + field: Optional[ModelField] + + def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, -) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: +) -> ParamDetails: field_info = None depends = None type_annotation: Any = Any @@ -450,7 +458,7 @@ def analyze_param( field_info=field_info, ) - return type_annotation, depends, field + return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: From 8d7d89e8c603ca13043ce037503c66cc6a662a48 Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 20:28:07 +0000 Subject: [PATCH 842/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a02b722f6..677816f40 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). ### Docs From 5b7fa3900e3156dcb93f496516740bc06903d7d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sat, 31 Aug 2024 22:52:06 +0200 Subject: [PATCH 843/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20s?= =?UTF-8?q?implify=20internal=20data=20from=20`solve=5Fdependencies()`=20u?= =?UTF-8?q?sing=20dataclasses=20(#12100)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 45 +++++++++++++++++++---------------- fastapi/routing.py | 33 +++++++++++++++---------- 2 files changed, 45 insertions(+), 33 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 5ebdddaf6..ed03df88b 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -529,6 +529,15 @@ async def solve_generator( return await stack.enter_async_context(cm) +@dataclass +class SolvedDependency: + values: Dict[str, Any] + errors: List[Any] + background_tasks: Optional[StarletteBackgroundTasks] + response: Response + dependency_cache: Dict[Tuple[Callable[..., Any], Tuple[str]], Any] + + async def solve_dependencies( *, request: Union[Request, WebSocket], @@ -539,13 +548,7 @@ async def solve_dependencies( dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, -) -> Tuple[ - Dict[str, Any], - List[Any], - Optional[StarletteBackgroundTasks], - Response, - Dict[Tuple[Callable[..., Any], Tuple[str]], Any], -]: +) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: @@ -587,27 +590,21 @@ async def solve_dependencies( dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, ) - ( - sub_values, - sub_errors, - background_tasks, - _, # the subdependency returns the same response we have - sub_dependency_cache, - ) = solved_result - dependency_cache.update(sub_dependency_cache) - if sub_errors: - errors.extend(sub_errors) + background_tasks = solved_result.background_tasks + dependency_cache.update(solved_result.dependency_cache) + if solved_result.errors: + errors.extend(solved_result.errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( - call=call, stack=async_exit_stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): - solved = await call(**sub_values) + solved = await call(**solved_result.values) else: - solved = await run_in_threadpool(call, **sub_values) + solved = await run_in_threadpool(call, **solved_result.values) if sub_dependant.name is not None: values[sub_dependant.name] = solved if sub_dependant.cache_key not in dependency_cache: @@ -654,7 +651,13 @@ async def solve_dependencies( values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) - return values, errors, background_tasks, response, dependency_cache + return SolvedDependency( + values=values, + errors=errors, + background_tasks=background_tasks, + response=response, + dependency_cache=dependency_cache, + ) def request_params_to_args( diff --git a/fastapi/routing.py b/fastapi/routing.py index 49f1b6013..c46772017 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -292,26 +292,34 @@ def get_request_handler( dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, ) - values, errors, background_tasks, sub_response, _ = solved_result + errors = solved_result.errors if not errors: raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine + dependant=dependant, + values=solved_result.values, + is_coroutine=is_coroutine, ) if isinstance(raw_response, Response): if raw_response.background is None: - raw_response.background = background_tasks + raw_response.background = solved_result.background_tasks response = raw_response else: - response_args: Dict[str, Any] = {"background": background_tasks} + response_args: Dict[str, Any] = { + "background": solved_result.background_tasks + } # If status_code was set, use it, otherwise use the default from the # response class, in the case of redirect it's 307 current_status_code = ( - status_code if status_code else sub_response.status_code + status_code + if status_code + else solved_result.response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code + if solved_result.response.status_code: + response_args["status_code"] = ( + solved_result.response.status_code + ) content = await serialize_response( field=response_field, response_content=raw_response, @@ -326,7 +334,7 @@ def get_request_handler( response = actual_response_class(content, **response_args) if not is_body_allowed_for_status_code(response.status_code): response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) + response.headers.raw.extend(solved_result.response.headers.raw) if errors: validation_error = RequestValidationError( _normalize_errors(errors), body=body @@ -360,11 +368,12 @@ def get_websocket_app( dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(_normalize_errors(errors)) + if solved_result.errors: + raise WebSocketRequestValidationError( + _normalize_errors(solved_result.errors) + ) assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + await dependant.call(**solved_result.values) return app From 3660c7a063ddc605269b0c204acd4724ccf2d69c Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 20:52:29 +0000 Subject: [PATCH 844/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 677816f40..3fc659cbb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). From d08b95ea57fa5740c8c04da554f2b6e259f4dea4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= <tiangolo@gmail.com> Date: Sun, 1 Sep 2024 01:46:03 +0200 Subject: [PATCH 845/846] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Rename=20internal?= =?UTF-8?q?=20`create=5Fresponse=5Ffield()`=20to=20`create=5Fmodel=5Ffield?= =?UTF-8?q?()`=20as=20it's=20used=20for=20more=20than=20response=20models?= =?UTF-8?q?=20(#12103)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 6 +++--- fastapi/routing.py | 6 +++--- fastapi/utils.py | 9 +++------ 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index ed03df88b..c5ed709f7 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -55,7 +55,7 @@ from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect -from fastapi.utils import create_response_field, get_path_param_names +from fastapi.utils import create_model_field, get_path_param_names from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool @@ -449,7 +449,7 @@ def analyze_param( else: alias = field_info.alias or param_name field_info.alias = alias - field = create_response_field( + field = create_model_field( name=param_name, type_=use_annotation_from_field_info, default=field_info.default, @@ -818,7 +818,7 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] - final_field = create_response_field( + final_field = create_model_field( name="body", type_=BodyModel, required=required, diff --git a/fastapi/routing.py b/fastapi/routing.py index c46772017..61a112fc4 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -49,7 +49,7 @@ from fastapi.exceptions import ( from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_cloned_field, - create_response_field, + create_model_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, @@ -497,7 +497,7 @@ class APIRoute(routing.Route): status_code ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id - self.response_field = create_response_field( + self.response_field = create_model_field( name=response_name, type_=self.response_model, mode="serialization", @@ -530,7 +530,7 @@ class APIRoute(routing.Route): additional_status_code ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" - response_field = create_response_field(name=response_name, type_=model) + response_field = create_model_field(name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields diff --git a/fastapi/utils.py b/fastapi/utils.py index 5c2538fac..4c7350fea 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -60,9 +60,9 @@ def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) -def create_response_field( +def create_model_field( name: str, - type_: Type[Any], + type_: Any, class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = Undefined, required: Union[bool, UndefinedType] = Undefined, @@ -71,9 +71,6 @@ def create_response_field( alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: - """ - Create a new response field. Raises if type_ is invalid. - """ class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( @@ -135,7 +132,7 @@ def create_cloned_field( use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) - new_field = create_response_field(name=field.name, type_=use_type) + new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] From d5c6cf8122cd8de3d4fcd37b616fbfa2ade1542b Mon Sep 17 00:00:00 2001 From: github-actions <github-actions@github.com> Date: Sat, 31 Aug 2024 23:46:26 +0000 Subject: [PATCH 846/846] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3fc659cbb..d7b278dbe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Rename internal `create_response_field()` to `create_model_field()` as it's used for more than response models. PR [#12103](https://github.com/fastapi/fastapi/pull/12103) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo).